drizzle-kit 0.28.0 → 0.28.1-166fb8d

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/README.md +7 -7
  2. package/api.js +1032 -710
  3. package/api.mjs +1032 -710
  4. package/bin.cjs +644 -49
  5. package/package.json +1 -1
package/api.js CHANGED
@@ -21121,7 +21121,7 @@ var version;
21121
21121
  var init_version = __esm({
21122
21122
  "../drizzle-orm/dist/version.js"() {
21123
21123
  "use strict";
21124
- version = "0.36.1";
21124
+ version = "0.36.4";
21125
21125
  }
21126
21126
  });
21127
21127
 
@@ -21407,7 +21407,11 @@ var init_sql = __esm({
21407
21407
  if (_config.invokeSource === "indexes") {
21408
21408
  return { sql: escapeName(columnName), params: [] };
21409
21409
  }
21410
- return { sql: escapeName(chunk.table[Table2.Symbol.Name]) + "." + escapeName(columnName), params: [] };
21410
+ const schemaName = chunk.table[Table2.Symbol.Schema];
21411
+ return {
21412
+ sql: chunk.table[IsAlias] || schemaName === void 0 ? escapeName(chunk.table[Table2.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[Table2.Symbol.Name]) + "." + escapeName(columnName),
21413
+ params: []
21414
+ };
21411
21415
  }
21412
21416
  if (is(chunk, View3)) {
21413
21417
  const schemaName = chunk[ViewBaseConfig].schema;
@@ -22140,7 +22144,7 @@ function haveSameKeys(left, right) {
22140
22144
  }
22141
22145
  function mapUpdateSet(table4, values) {
22142
22146
  const entries = Object.entries(values).filter(([, value]) => value !== void 0).map(([key, value]) => {
22143
- if (is(value, SQL)) {
22147
+ if (is(value, SQL) || is(value, Column2)) {
22144
22148
  return [key, value];
22145
22149
  } else {
22146
22150
  return [key, new Param(value, table4[Table2.Symbol.Columns][key])];
@@ -24579,9 +24583,10 @@ var init_delete = __esm({
24579
24583
  constructor(table4, session, dialect4, withList) {
24580
24584
  super();
24581
24585
  __publicField(this, "config");
24586
+ __publicField(this, "authToken");
24582
24587
  __publicField(this, "execute", (placeholderValues) => {
24583
24588
  return tracer.startActiveSpan("drizzle.operation", () => {
24584
- return this._prepare().execute(placeholderValues);
24589
+ return this._prepare().execute(placeholderValues, this.authToken);
24585
24590
  });
24586
24591
  });
24587
24592
  this.session = session;
@@ -24642,167 +24647,16 @@ var init_delete = __esm({
24642
24647
  prepare(name2) {
24643
24648
  return this._prepare(name2);
24644
24649
  }
24645
- $dynamic() {
24646
- return this;
24647
- }
24648
- };
24649
- __publicField(PgDeleteBase, _a124, "PgDelete");
24650
- }
24651
- });
24652
-
24653
- // ../drizzle-orm/dist/pg-core/query-builders/insert.js
24654
- var _a125, PgInsertBuilder, _a126, _b98, PgInsertBase;
24655
- var init_insert = __esm({
24656
- "../drizzle-orm/dist/pg-core/query-builders/insert.js"() {
24657
- "use strict";
24658
- init_entity();
24659
- init_query_promise();
24660
- init_sql();
24661
- init_table();
24662
- init_tracing();
24663
- init_utils2();
24664
- _a125 = entityKind;
24665
- PgInsertBuilder = class {
24666
- constructor(table4, session, dialect4, withList) {
24667
- this.table = table4;
24668
- this.session = session;
24669
- this.dialect = dialect4;
24670
- this.withList = withList;
24671
- }
24672
- values(values) {
24673
- values = Array.isArray(values) ? values : [values];
24674
- if (values.length === 0) {
24675
- throw new Error("values() must be called with at least one value");
24676
- }
24677
- const mappedValues = values.map((entry) => {
24678
- const result = {};
24679
- const cols = this.table[Table2.Symbol.Columns];
24680
- for (const colKey of Object.keys(entry)) {
24681
- const colValue = entry[colKey];
24682
- result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
24683
- }
24684
- return result;
24685
- });
24686
- return new PgInsertBase(this.table, mappedValues, this.session, this.dialect, this.withList);
24687
- }
24688
- };
24689
- __publicField(PgInsertBuilder, _a125, "PgInsertBuilder");
24690
- PgInsertBase = class extends (_b98 = QueryPromise, _a126 = entityKind, _b98) {
24691
- constructor(table4, values, session, dialect4, withList) {
24692
- super();
24693
- __publicField(this, "config");
24694
- __publicField(this, "execute", (placeholderValues) => {
24695
- return tracer.startActiveSpan("drizzle.operation", () => {
24696
- return this._prepare().execute(placeholderValues);
24697
- });
24698
- });
24699
- this.session = session;
24700
- this.dialect = dialect4;
24701
- this.config = { table: table4, values, withList };
24702
- }
24703
- returning(fields = this.config.table[Table2.Symbol.Columns]) {
24704
- this.config.returning = orderSelectedFields(fields);
24705
- return this;
24706
- }
24707
- /**
24708
- * Adds an `on conflict do nothing` clause to the query.
24709
- *
24710
- * Calling this method simply avoids inserting a row as its alternative action.
24711
- *
24712
- * See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}
24713
- *
24714
- * @param config The `target` and `where` clauses.
24715
- *
24716
- * @example
24717
- * ```ts
24718
- * // Insert one row and cancel the insert if there's a conflict
24719
- * await db.insert(cars)
24720
- * .values({ id: 1, brand: 'BMW' })
24721
- * .onConflictDoNothing();
24722
- *
24723
- * // Explicitly specify conflict target
24724
- * await db.insert(cars)
24725
- * .values({ id: 1, brand: 'BMW' })
24726
- * .onConflictDoNothing({ target: cars.id });
24727
- * ```
24728
- */
24729
- onConflictDoNothing(config = {}) {
24730
- if (config.target === void 0) {
24731
- this.config.onConflict = sql`do nothing`;
24732
- } else {
24733
- let targetColumn = "";
24734
- 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));
24735
- const whereSql = config.where ? sql` where ${config.where}` : void 0;
24736
- this.config.onConflict = sql`(${sql.raw(targetColumn)})${whereSql} do nothing`;
24737
- }
24738
- return this;
24739
- }
24740
- /**
24741
- * Adds an `on conflict do update` clause to the query.
24742
- *
24743
- * Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.
24744
- *
24745
- * See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}
24746
- *
24747
- * @param config The `target`, `set` and `where` clauses.
24748
- *
24749
- * @example
24750
- * ```ts
24751
- * // Update the row if there's a conflict
24752
- * await db.insert(cars)
24753
- * .values({ id: 1, brand: 'BMW' })
24754
- * .onConflictDoUpdate({
24755
- * target: cars.id,
24756
- * set: { brand: 'Porsche' }
24757
- * });
24758
- *
24759
- * // Upsert with 'where' clause
24760
- * await db.insert(cars)
24761
- * .values({ id: 1, brand: 'BMW' })
24762
- * .onConflictDoUpdate({
24763
- * target: cars.id,
24764
- * set: { brand: 'newBMW' },
24765
- * targetWhere: sql`${cars.createdAt} > '2023-01-01'::date`,
24766
- * });
24767
- * ```
24768
- */
24769
- onConflictDoUpdate(config) {
24770
- if (config.where && (config.targetWhere || config.setWhere)) {
24771
- throw new Error(
24772
- 'You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.'
24773
- );
24774
- }
24775
- const whereSql = config.where ? sql` where ${config.where}` : void 0;
24776
- const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : void 0;
24777
- const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : void 0;
24778
- const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
24779
- let targetColumn = "";
24780
- 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));
24781
- this.config.onConflict = sql`(${sql.raw(targetColumn)})${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`;
24782
- return this;
24783
- }
24784
- /** @internal */
24785
- getSQL() {
24786
- return this.dialect.buildInsertQuery(this.config);
24787
- }
24788
- toSQL() {
24789
- const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
24790
- return rest;
24791
- }
24792
24650
  /** @internal */
24793
- _prepare(name2) {
24794
- return tracer.startActiveSpan("drizzle.prepareQuery", () => {
24795
- return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name2, true);
24796
- });
24797
- }
24798
- prepare(name2) {
24799
- return this._prepare(name2);
24651
+ setToken(token) {
24652
+ this.authToken = token;
24653
+ return this;
24800
24654
  }
24801
24655
  $dynamic() {
24802
24656
  return this;
24803
24657
  }
24804
24658
  };
24805
- __publicField(PgInsertBase, _a126, "PgInsert");
24659
+ __publicField(PgDeleteBase, _a124, "PgDelete");
24806
24660
  }
24807
24661
  });
24808
24662
 
@@ -24821,13 +24675,13 @@ function toCamelCase(input) {
24821
24675
  function noopCase(input) {
24822
24676
  return input;
24823
24677
  }
24824
- var _a127, CasingCache;
24678
+ var _a125, CasingCache;
24825
24679
  var init_casing = __esm({
24826
24680
  "../drizzle-orm/dist/casing.js"() {
24827
24681
  "use strict";
24828
24682
  init_entity();
24829
24683
  init_table();
24830
- _a127 = entityKind;
24684
+ _a125 = entityKind;
24831
24685
  CasingCache = class {
24832
24686
  constructor(casing2) {
24833
24687
  /** @internal */
@@ -24864,25 +24718,25 @@ var init_casing = __esm({
24864
24718
  this.cachedTables = {};
24865
24719
  }
24866
24720
  };
24867
- __publicField(CasingCache, _a127, "CasingCache");
24721
+ __publicField(CasingCache, _a125, "CasingCache");
24868
24722
  }
24869
24723
  });
24870
24724
 
24871
24725
  // ../drizzle-orm/dist/pg-core/view-base.js
24872
- var _a128, _b99, PgViewBase;
24726
+ var _a126, _b98, PgViewBase;
24873
24727
  var init_view_base = __esm({
24874
24728
  "../drizzle-orm/dist/pg-core/view-base.js"() {
24875
24729
  "use strict";
24876
24730
  init_entity();
24877
24731
  init_sql();
24878
- PgViewBase = class extends (_b99 = View3, _a128 = entityKind, _b99) {
24732
+ PgViewBase = class extends (_b98 = View3, _a126 = entityKind, _b98) {
24879
24733
  };
24880
- __publicField(PgViewBase, _a128, "PgViewBase");
24734
+ __publicField(PgViewBase, _a126, "PgViewBase");
24881
24735
  }
24882
24736
  });
24883
24737
 
24884
24738
  // ../drizzle-orm/dist/pg-core/dialect.js
24885
- var _a129, PgDialect;
24739
+ var _a127, PgDialect;
24886
24740
  var init_dialect = __esm({
24887
24741
  "../drizzle-orm/dist/pg-core/dialect.js"() {
24888
24742
  "use strict";
@@ -24901,7 +24755,7 @@ var init_dialect = __esm({
24901
24755
  init_utils2();
24902
24756
  init_view_common();
24903
24757
  init_view_base();
24904
- _a129 = entityKind;
24758
+ _a127 = entityKind;
24905
24759
  PgDialect = class {
24906
24760
  constructor(config) {
24907
24761
  /** @internal */
@@ -24981,12 +24835,19 @@ var init_dialect = __esm({
24981
24835
  return [res];
24982
24836
  }));
24983
24837
  }
24984
- buildUpdateQuery({ table: table4, set, where, returning, withList }) {
24838
+ buildUpdateQuery({ table: table4, set, where, returning, withList, from, joins }) {
24985
24839
  const withSql = this.buildWithCTE(withList);
24840
+ const tableName = table4[PgTable.Symbol.Name];
24841
+ const tableSchema = table4[PgTable.Symbol.Schema];
24842
+ const origTableName = table4[PgTable.Symbol.OriginalName];
24843
+ const alias = tableName === origTableName ? void 0 : tableName;
24844
+ const tableSql = sql`${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}`;
24986
24845
  const setSql = this.buildUpdateSet(table4, set);
24987
- const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
24846
+ const fromSql = from && sql.join([sql.raw(" from "), this.buildFromTable(from)]);
24847
+ const joinsSql = this.buildJoins(joins);
24848
+ const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: !from })}` : void 0;
24988
24849
  const whereSql = where ? sql` where ${where}` : void 0;
24989
- return sql`${withSql}update ${table4} set ${setSql}${whereSql}${returningSql}`;
24850
+ return sql`${withSql}update ${tableSql} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}`;
24990
24851
  }
24991
24852
  /**
24992
24853
  * Builds selection SQL with provided fields/expressions
@@ -25038,6 +24899,54 @@ var init_dialect = __esm({
25038
24899
  });
25039
24900
  return sql.join(chunks);
25040
24901
  }
24902
+ buildJoins(joins) {
24903
+ if (!joins || joins.length === 0) {
24904
+ return void 0;
24905
+ }
24906
+ const joinsArray = [];
24907
+ for (const [index4, joinMeta] of joins.entries()) {
24908
+ if (index4 === 0) {
24909
+ joinsArray.push(sql` `);
24910
+ }
24911
+ const table4 = joinMeta.table;
24912
+ const lateralSql = joinMeta.lateral ? sql` lateral` : void 0;
24913
+ if (is(table4, PgTable)) {
24914
+ const tableName = table4[PgTable.Symbol.Name];
24915
+ const tableSchema = table4[PgTable.Symbol.Schema];
24916
+ const origTableName = table4[PgTable.Symbol.OriginalName];
24917
+ const alias = tableName === origTableName ? void 0 : joinMeta.alias;
24918
+ joinsArray.push(
24919
+ sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}`
24920
+ );
24921
+ } else if (is(table4, View3)) {
24922
+ const viewName = table4[ViewBaseConfig].name;
24923
+ const viewSchema = table4[ViewBaseConfig].schema;
24924
+ const origViewName = table4[ViewBaseConfig].originalName;
24925
+ const alias = viewName === origViewName ? void 0 : joinMeta.alias;
24926
+ joinsArray.push(
24927
+ sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? sql`${sql.identifier(viewSchema)}.` : void 0}${sql.identifier(origViewName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}`
24928
+ );
24929
+ } else {
24930
+ joinsArray.push(
24931
+ sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${table4} on ${joinMeta.on}`
24932
+ );
24933
+ }
24934
+ if (index4 < joins.length - 1) {
24935
+ joinsArray.push(sql` `);
24936
+ }
24937
+ }
24938
+ return sql.join(joinsArray);
24939
+ }
24940
+ buildFromTable(table4) {
24941
+ if (is(table4, Table2) && table4[Table2.Symbol.OriginalName] !== table4[Table2.Symbol.Name]) {
24942
+ let fullName = sql`${sql.identifier(table4[Table2.Symbol.OriginalName])}`;
24943
+ if (table4[Table2.Symbol.Schema]) {
24944
+ fullName = sql`${sql.identifier(table4[Table2.Symbol.Schema])}.${fullName}`;
24945
+ }
24946
+ return sql`${fullName} ${sql.identifier(table4[Table2.Symbol.Name])}`;
24947
+ }
24948
+ return table4;
24949
+ }
25041
24950
  buildSelectQuery({
25042
24951
  withList,
25043
24952
  fields,
@@ -25072,51 +24981,8 @@ var init_dialect = __esm({
25072
24981
  distinctSql = distinct === true ? sql` distinct` : sql` distinct on (${sql.join(distinct.on, sql`, `)})`;
25073
24982
  }
25074
24983
  const selection = this.buildSelection(fieldsList, { isSingleTable });
25075
- const tableSql = (() => {
25076
- if (is(table4, Table2) && table4[Table2.Symbol.OriginalName] !== table4[Table2.Symbol.Name]) {
25077
- let fullName = sql`${sql.identifier(table4[Table2.Symbol.OriginalName])}`;
25078
- if (table4[Table2.Symbol.Schema]) {
25079
- fullName = sql`${sql.identifier(table4[Table2.Symbol.Schema])}.${fullName}`;
25080
- }
25081
- return sql`${fullName} ${sql.identifier(table4[Table2.Symbol.Name])}`;
25082
- }
25083
- return table4;
25084
- })();
25085
- const joinsArray = [];
25086
- if (joins) {
25087
- for (const [index4, joinMeta] of joins.entries()) {
25088
- if (index4 === 0) {
25089
- joinsArray.push(sql` `);
25090
- }
25091
- const table22 = joinMeta.table;
25092
- const lateralSql = joinMeta.lateral ? sql` lateral` : void 0;
25093
- if (is(table22, PgTable)) {
25094
- const tableName = table22[PgTable.Symbol.Name];
25095
- const tableSchema = table22[PgTable.Symbol.Schema];
25096
- const origTableName = table22[PgTable.Symbol.OriginalName];
25097
- const alias = tableName === origTableName ? void 0 : joinMeta.alias;
25098
- joinsArray.push(
25099
- sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}`
25100
- );
25101
- } else if (is(table22, View3)) {
25102
- const viewName = table22[ViewBaseConfig].name;
25103
- const viewSchema = table22[ViewBaseConfig].schema;
25104
- const origViewName = table22[ViewBaseConfig].originalName;
25105
- const alias = viewName === origViewName ? void 0 : joinMeta.alias;
25106
- joinsArray.push(
25107
- sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? sql`${sql.identifier(viewSchema)}.` : void 0}${sql.identifier(origViewName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}`
25108
- );
25109
- } else {
25110
- joinsArray.push(
25111
- sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${table22} on ${joinMeta.on}`
25112
- );
25113
- }
25114
- if (index4 < joins.length - 1) {
25115
- joinsArray.push(sql` `);
25116
- }
25117
- }
25118
- }
25119
- const joinsSql = sql.join(joinsArray);
24984
+ const tableSql = this.buildFromTable(table4);
24985
+ const joinsSql = this.buildJoins(joins);
25120
24986
  const whereSql = where ? sql` where ${where}` : void 0;
25121
24987
  const havingSql = having ? sql` having ${having}` : void 0;
25122
24988
  let orderBySql;
@@ -25197,43 +25063,55 @@ var init_dialect = __esm({
25197
25063
  const offsetSql = offset ? sql` offset ${offset}` : void 0;
25198
25064
  return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
25199
25065
  }
25200
- buildInsertQuery({ table: table4, values, onConflict, returning, withList }) {
25066
+ buildInsertQuery({ table: table4, values: valuesOrSelect, onConflict, returning, withList, select, overridingSystemValue_ }) {
25201
25067
  const valuesSqlList = [];
25202
25068
  const columns = table4[Table2.Symbol.Columns];
25203
25069
  const colEntries = Object.entries(columns).filter(([_2, col]) => !col.shouldDisableInsert());
25204
25070
  const insertOrder = colEntries.map(
25205
25071
  ([, column4]) => sql.identifier(this.casing.getColumnCasing(column4))
25206
25072
  );
25207
- for (const [valueIndex, value] of values.entries()) {
25208
- const valueList = [];
25209
- for (const [fieldName, col] of colEntries) {
25210
- const colValue = value[fieldName];
25211
- if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) {
25212
- if (col.defaultFn !== void 0) {
25213
- const defaultFnResult = col.defaultFn();
25214
- const defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
25215
- valueList.push(defaultValue);
25216
- } else if (!col.default && col.onUpdateFn !== void 0) {
25217
- const onUpdateFnResult = col.onUpdateFn();
25218
- const newValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
25219
- valueList.push(newValue);
25073
+ if (select) {
25074
+ const select2 = valuesOrSelect;
25075
+ if (is(select2, SQL)) {
25076
+ valuesSqlList.push(select2);
25077
+ } else {
25078
+ valuesSqlList.push(select2.getSQL());
25079
+ }
25080
+ } else {
25081
+ const values = valuesOrSelect;
25082
+ valuesSqlList.push(sql.raw("values "));
25083
+ for (const [valueIndex, value] of values.entries()) {
25084
+ const valueList = [];
25085
+ for (const [fieldName, col] of colEntries) {
25086
+ const colValue = value[fieldName];
25087
+ if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) {
25088
+ if (col.defaultFn !== void 0) {
25089
+ const defaultFnResult = col.defaultFn();
25090
+ const defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
25091
+ valueList.push(defaultValue);
25092
+ } else if (!col.default && col.onUpdateFn !== void 0) {
25093
+ const onUpdateFnResult = col.onUpdateFn();
25094
+ const newValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
25095
+ valueList.push(newValue);
25096
+ } else {
25097
+ valueList.push(sql`default`);
25098
+ }
25220
25099
  } else {
25221
- valueList.push(sql`default`);
25100
+ valueList.push(colValue);
25222
25101
  }
25223
- } else {
25224
- valueList.push(colValue);
25225
25102
  }
25226
- }
25227
- valuesSqlList.push(valueList);
25228
- if (valueIndex < values.length - 1) {
25229
- valuesSqlList.push(sql`, `);
25103
+ valuesSqlList.push(valueList);
25104
+ if (valueIndex < values.length - 1) {
25105
+ valuesSqlList.push(sql`, `);
25106
+ }
25230
25107
  }
25231
25108
  }
25232
25109
  const withSql = this.buildWithCTE(withList);
25233
25110
  const valuesSql = sql.join(valuesSqlList);
25234
25111
  const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
25235
25112
  const onConflictSql = onConflict ? sql` on conflict ${onConflict}` : void 0;
25236
- return sql`${withSql}insert into ${table4} ${insertOrder} values ${valuesSql}${onConflictSql}${returningSql}`;
25113
+ const overridingSql = overridingSystemValue_ === true ? sql`overriding system value ` : void 0;
25114
+ return sql`${withSql}insert into ${table4} ${insertOrder} ${overridingSql}${valuesSql}${onConflictSql}${returningSql}`;
25237
25115
  }
25238
25116
  buildRefreshMaterializedViewQuery({ view: view4, concurrently, withNoData }) {
25239
25117
  const concurrentlySql = concurrently ? sql` concurrently` : void 0;
@@ -25969,12 +25847,12 @@ var init_dialect = __esm({
25969
25847
  };
25970
25848
  }
25971
25849
  };
25972
- __publicField(PgDialect, _a129, "PgDialect");
25850
+ __publicField(PgDialect, _a127, "PgDialect");
25973
25851
  }
25974
25852
  });
25975
25853
 
25976
25854
  // ../drizzle-orm/dist/selection-proxy.js
25977
- var _a130, _SelectionProxyHandler, SelectionProxyHandler;
25855
+ var _a128, _SelectionProxyHandler, SelectionProxyHandler;
25978
25856
  var init_selection_proxy = __esm({
25979
25857
  "../drizzle-orm/dist/selection-proxy.js"() {
25980
25858
  "use strict";
@@ -25984,7 +25862,7 @@ var init_selection_proxy = __esm({
25984
25862
  init_sql();
25985
25863
  init_subquery();
25986
25864
  init_view_common();
25987
- _a130 = entityKind;
25865
+ _a128 = entityKind;
25988
25866
  _SelectionProxyHandler = class _SelectionProxyHandler {
25989
25867
  constructor(config) {
25990
25868
  __publicField(this, "config");
@@ -26050,25 +25928,25 @@ var init_selection_proxy = __esm({
26050
25928
  return new Proxy(value, new _SelectionProxyHandler(this.config));
26051
25929
  }
26052
25930
  };
26053
- __publicField(_SelectionProxyHandler, _a130, "SelectionProxyHandler");
25931
+ __publicField(_SelectionProxyHandler, _a128, "SelectionProxyHandler");
26054
25932
  SelectionProxyHandler = _SelectionProxyHandler;
26055
25933
  }
26056
25934
  });
26057
25935
 
26058
25936
  // ../drizzle-orm/dist/query-builders/query-builder.js
26059
- var _a131, TypedQueryBuilder;
25937
+ var _a129, TypedQueryBuilder;
26060
25938
  var init_query_builder = __esm({
26061
25939
  "../drizzle-orm/dist/query-builders/query-builder.js"() {
26062
25940
  "use strict";
26063
25941
  init_entity();
26064
- _a131 = entityKind;
25942
+ _a129 = entityKind;
26065
25943
  TypedQueryBuilder = class {
26066
25944
  /** @internal */
26067
25945
  getSelectedFields() {
26068
25946
  return this._.selectedFields;
26069
25947
  }
26070
25948
  };
26071
- __publicField(TypedQueryBuilder, _a131, "TypedQueryBuilder");
25949
+ __publicField(TypedQueryBuilder, _a129, "TypedQueryBuilder");
26072
25950
  }
26073
25951
  });
26074
25952
 
@@ -26090,7 +25968,7 @@ function createSetOperator(type, isAll) {
26090
25968
  return leftSelect.addSetOperators(setOperators);
26091
25969
  };
26092
25970
  }
26093
- var _a132, PgSelectBuilder, _a133, _b100, PgSelectQueryBuilderBase, _a134, _b101, PgSelectBase, getPgSetOperators, union, unionAll, intersect, intersectAll, except, exceptAll;
25971
+ var _a130, PgSelectBuilder, _a131, _b99, PgSelectQueryBuilderBase, _a132, _b100, PgSelectBase, getPgSetOperators, union, unionAll, intersect, intersectAll, except, exceptAll;
26094
25972
  var init_select2 = __esm({
26095
25973
  "../drizzle-orm/dist/pg-core/query-builders/select.js"() {
26096
25974
  "use strict";
@@ -26106,7 +25984,7 @@ var init_select2 = __esm({
26106
25984
  init_utils2();
26107
25985
  init_utils2();
26108
25986
  init_view_common();
26109
- _a132 = entityKind;
25987
+ _a130 = entityKind;
26110
25988
  PgSelectBuilder = class {
26111
25989
  constructor(config) {
26112
25990
  __publicField(this, "fields");
@@ -26114,6 +25992,7 @@ var init_select2 = __esm({
26114
25992
  __publicField(this, "dialect");
26115
25993
  __publicField(this, "withList", []);
26116
25994
  __publicField(this, "distinct");
25995
+ __publicField(this, "authToken");
26117
25996
  this.fields = config.fields;
26118
25997
  this.session = config.session;
26119
25998
  this.dialect = config.dialect;
@@ -26122,6 +26001,11 @@ var init_select2 = __esm({
26122
26001
  }
26123
26002
  this.distinct = config.distinct;
26124
26003
  }
26004
+ /** @internal */
26005
+ setToken(token) {
26006
+ this.authToken = token;
26007
+ return this;
26008
+ }
26125
26009
  /**
26126
26010
  * Specify the table, subquery, or other target that you're
26127
26011
  * building a select query against.
@@ -26144,7 +26028,7 @@ var init_select2 = __esm({
26144
26028
  } else {
26145
26029
  fields = getTableColumns(source);
26146
26030
  }
26147
- return new PgSelectBase({
26031
+ return this.authToken === void 0 ? new PgSelectBase({
26148
26032
  table: source,
26149
26033
  fields,
26150
26034
  isPartialSelect,
@@ -26152,11 +26036,19 @@ var init_select2 = __esm({
26152
26036
  dialect: this.dialect,
26153
26037
  withList: this.withList,
26154
26038
  distinct: this.distinct
26155
- });
26039
+ }) : new PgSelectBase({
26040
+ table: source,
26041
+ fields,
26042
+ isPartialSelect,
26043
+ session: this.session,
26044
+ dialect: this.dialect,
26045
+ withList: this.withList,
26046
+ distinct: this.distinct
26047
+ }).setToken(this.authToken);
26156
26048
  }
26157
26049
  };
26158
- __publicField(PgSelectBuilder, _a132, "PgSelectBuilder");
26159
- PgSelectQueryBuilderBase = class extends (_b100 = TypedQueryBuilder, _a133 = entityKind, _b100) {
26050
+ __publicField(PgSelectBuilder, _a130, "PgSelectBuilder");
26051
+ PgSelectQueryBuilderBase = class extends (_b99 = TypedQueryBuilder, _a131 = entityKind, _b99) {
26160
26052
  constructor({ table: table4, fields, isPartialSelect, session, dialect: dialect4, withList, distinct }) {
26161
26053
  super();
26162
26054
  __publicField(this, "_");
@@ -26756,19 +26648,20 @@ var init_select2 = __esm({
26756
26648
  return this;
26757
26649
  }
26758
26650
  };
26759
- __publicField(PgSelectQueryBuilderBase, _a133, "PgSelectQueryBuilder");
26760
- PgSelectBase = class extends (_b101 = PgSelectQueryBuilderBase, _a134 = entityKind, _b101) {
26651
+ __publicField(PgSelectQueryBuilderBase, _a131, "PgSelectQueryBuilder");
26652
+ PgSelectBase = class extends (_b100 = PgSelectQueryBuilderBase, _a132 = entityKind, _b100) {
26761
26653
  constructor() {
26762
26654
  super(...arguments);
26655
+ __publicField(this, "authToken");
26763
26656
  __publicField(this, "execute", (placeholderValues) => {
26764
26657
  return tracer.startActiveSpan("drizzle.operation", () => {
26765
- return this._prepare().execute(placeholderValues);
26658
+ return this._prepare().execute(placeholderValues, this.authToken);
26766
26659
  });
26767
26660
  });
26768
26661
  }
26769
26662
  /** @internal */
26770
26663
  _prepare(name2) {
26771
- const { session, config, dialect: dialect4, joinsNotNullableMap } = this;
26664
+ const { session, config, dialect: dialect4, joinsNotNullableMap, authToken } = this;
26772
26665
  if (!session) {
26773
26666
  throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
26774
26667
  }
@@ -26776,7 +26669,7 @@ var init_select2 = __esm({
26776
26669
  const fieldsList = orderSelectedFields(config.fields);
26777
26670
  const query = session.prepareQuery(dialect4.sqlToQuery(this.getSQL()), fieldsList, name2, true);
26778
26671
  query.joinsNotNullableMap = joinsNotNullableMap;
26779
- return query;
26672
+ return authToken === void 0 ? query : query.setToken(authToken);
26780
26673
  });
26781
26674
  }
26782
26675
  /**
@@ -26789,8 +26682,13 @@ var init_select2 = __esm({
26789
26682
  prepare(name2) {
26790
26683
  return this._prepare(name2);
26791
26684
  }
26685
+ /** @internal */
26686
+ setToken(token) {
26687
+ this.authToken = token;
26688
+ return this;
26689
+ }
26792
26690
  };
26793
- __publicField(PgSelectBase, _a134, "PgSelect");
26691
+ __publicField(PgSelectBase, _a132, "PgSelect");
26794
26692
  applyMixins(PgSelectBase, [QueryPromise]);
26795
26693
  getPgSetOperators = () => ({
26796
26694
  union,
@@ -26810,7 +26708,7 @@ var init_select2 = __esm({
26810
26708
  });
26811
26709
 
26812
26710
  // ../drizzle-orm/dist/pg-core/query-builders/query-builder.js
26813
- var _a135, QueryBuilder;
26711
+ var _a133, QueryBuilder;
26814
26712
  var init_query_builder2 = __esm({
26815
26713
  "../drizzle-orm/dist/pg-core/query-builders/query-builder.js"() {
26816
26714
  "use strict";
@@ -26819,7 +26717,7 @@ var init_query_builder2 = __esm({
26819
26717
  init_selection_proxy();
26820
26718
  init_subquery();
26821
26719
  init_select2();
26822
- _a135 = entityKind;
26720
+ _a133 = entityKind;
26823
26721
  QueryBuilder = class {
26824
26722
  constructor(dialect4) {
26825
26723
  __publicField(this, "dialect");
@@ -26900,27 +26798,227 @@ var init_query_builder2 = __esm({
26900
26798
  return this.dialect;
26901
26799
  }
26902
26800
  };
26903
- __publicField(QueryBuilder, _a135, "PgQueryBuilder");
26801
+ __publicField(QueryBuilder, _a133, "PgQueryBuilder");
26904
26802
  }
26905
26803
  });
26906
26804
 
26907
- // ../drizzle-orm/dist/pg-core/query-builders/refresh-materialized-view.js
26908
- var _a136, _b102, PgRefreshMaterializedView;
26909
- var init_refresh_materialized_view = __esm({
26910
- "../drizzle-orm/dist/pg-core/query-builders/refresh-materialized-view.js"() {
26805
+ // ../drizzle-orm/dist/pg-core/query-builders/insert.js
26806
+ var _a134, PgInsertBuilder, _a135, _b101, PgInsertBase;
26807
+ var init_insert = __esm({
26808
+ "../drizzle-orm/dist/pg-core/query-builders/insert.js"() {
26911
26809
  "use strict";
26912
26810
  init_entity();
26913
26811
  init_query_promise();
26812
+ init_sql();
26813
+ init_table();
26914
26814
  init_tracing();
26915
- PgRefreshMaterializedView = class extends (_b102 = QueryPromise, _a136 = entityKind, _b102) {
26916
- constructor(view4, session, dialect4) {
26917
- super();
26918
- __publicField(this, "config");
26919
- __publicField(this, "execute", (placeholderValues) => {
26920
- return tracer.startActiveSpan("drizzle.operation", () => {
26921
- return this._prepare().execute(placeholderValues);
26922
- });
26923
- });
26815
+ init_utils2();
26816
+ init_query_builder2();
26817
+ _a134 = entityKind;
26818
+ PgInsertBuilder = class {
26819
+ constructor(table4, session, dialect4, withList, overridingSystemValue_) {
26820
+ __publicField(this, "authToken");
26821
+ this.table = table4;
26822
+ this.session = session;
26823
+ this.dialect = dialect4;
26824
+ this.withList = withList;
26825
+ this.overridingSystemValue_ = overridingSystemValue_;
26826
+ }
26827
+ /** @internal */
26828
+ setToken(token) {
26829
+ this.authToken = token;
26830
+ return this;
26831
+ }
26832
+ overridingSystemValue() {
26833
+ this.overridingSystemValue_ = true;
26834
+ return this;
26835
+ }
26836
+ values(values) {
26837
+ values = Array.isArray(values) ? values : [values];
26838
+ if (values.length === 0) {
26839
+ throw new Error("values() must be called with at least one value");
26840
+ }
26841
+ const mappedValues = values.map((entry) => {
26842
+ const result = {};
26843
+ const cols = this.table[Table2.Symbol.Columns];
26844
+ for (const colKey of Object.keys(entry)) {
26845
+ const colValue = entry[colKey];
26846
+ result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
26847
+ }
26848
+ return result;
26849
+ });
26850
+ return this.authToken === void 0 ? new PgInsertBase(
26851
+ this.table,
26852
+ mappedValues,
26853
+ this.session,
26854
+ this.dialect,
26855
+ this.withList,
26856
+ false,
26857
+ this.overridingSystemValue_
26858
+ ) : new PgInsertBase(
26859
+ this.table,
26860
+ mappedValues,
26861
+ this.session,
26862
+ this.dialect,
26863
+ this.withList,
26864
+ false,
26865
+ this.overridingSystemValue_
26866
+ ).setToken(this.authToken);
26867
+ }
26868
+ select(selectQuery) {
26869
+ const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder()) : selectQuery;
26870
+ if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) {
26871
+ throw new Error(
26872
+ "Insert select error: selected fields are not the same or are in a different order compared to the table definition"
26873
+ );
26874
+ }
26875
+ return new PgInsertBase(this.table, select, this.session, this.dialect, this.withList, true);
26876
+ }
26877
+ };
26878
+ __publicField(PgInsertBuilder, _a134, "PgInsertBuilder");
26879
+ PgInsertBase = class extends (_b101 = QueryPromise, _a135 = entityKind, _b101) {
26880
+ constructor(table4, values, session, dialect4, withList, select, overridingSystemValue_) {
26881
+ super();
26882
+ __publicField(this, "config");
26883
+ __publicField(this, "authToken");
26884
+ __publicField(this, "execute", (placeholderValues) => {
26885
+ return tracer.startActiveSpan("drizzle.operation", () => {
26886
+ return this._prepare().execute(placeholderValues, this.authToken);
26887
+ });
26888
+ });
26889
+ this.session = session;
26890
+ this.dialect = dialect4;
26891
+ this.config = { table: table4, values, withList, select, overridingSystemValue_ };
26892
+ }
26893
+ returning(fields = this.config.table[Table2.Symbol.Columns]) {
26894
+ this.config.returning = orderSelectedFields(fields);
26895
+ return this;
26896
+ }
26897
+ /**
26898
+ * Adds an `on conflict do nothing` clause to the query.
26899
+ *
26900
+ * Calling this method simply avoids inserting a row as its alternative action.
26901
+ *
26902
+ * See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}
26903
+ *
26904
+ * @param config The `target` and `where` clauses.
26905
+ *
26906
+ * @example
26907
+ * ```ts
26908
+ * // Insert one row and cancel the insert if there's a conflict
26909
+ * await db.insert(cars)
26910
+ * .values({ id: 1, brand: 'BMW' })
26911
+ * .onConflictDoNothing();
26912
+ *
26913
+ * // Explicitly specify conflict target
26914
+ * await db.insert(cars)
26915
+ * .values({ id: 1, brand: 'BMW' })
26916
+ * .onConflictDoNothing({ target: cars.id });
26917
+ * ```
26918
+ */
26919
+ onConflictDoNothing(config = {}) {
26920
+ if (config.target === void 0) {
26921
+ this.config.onConflict = sql`do nothing`;
26922
+ } else {
26923
+ let targetColumn = "";
26924
+ 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));
26925
+ const whereSql = config.where ? sql` where ${config.where}` : void 0;
26926
+ this.config.onConflict = sql`(${sql.raw(targetColumn)})${whereSql} do nothing`;
26927
+ }
26928
+ return this;
26929
+ }
26930
+ /**
26931
+ * Adds an `on conflict do update` clause to the query.
26932
+ *
26933
+ * Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.
26934
+ *
26935
+ * See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}
26936
+ *
26937
+ * @param config The `target`, `set` and `where` clauses.
26938
+ *
26939
+ * @example
26940
+ * ```ts
26941
+ * // Update the row if there's a conflict
26942
+ * await db.insert(cars)
26943
+ * .values({ id: 1, brand: 'BMW' })
26944
+ * .onConflictDoUpdate({
26945
+ * target: cars.id,
26946
+ * set: { brand: 'Porsche' }
26947
+ * });
26948
+ *
26949
+ * // Upsert with 'where' clause
26950
+ * await db.insert(cars)
26951
+ * .values({ id: 1, brand: 'BMW' })
26952
+ * .onConflictDoUpdate({
26953
+ * target: cars.id,
26954
+ * set: { brand: 'newBMW' },
26955
+ * targetWhere: sql`${cars.createdAt} > '2023-01-01'::date`,
26956
+ * });
26957
+ * ```
26958
+ */
26959
+ onConflictDoUpdate(config) {
26960
+ if (config.where && (config.targetWhere || config.setWhere)) {
26961
+ throw new Error(
26962
+ 'You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.'
26963
+ );
26964
+ }
26965
+ const whereSql = config.where ? sql` where ${config.where}` : void 0;
26966
+ const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : void 0;
26967
+ const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : void 0;
26968
+ const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
26969
+ let targetColumn = "";
26970
+ 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));
26971
+ this.config.onConflict = sql`(${sql.raw(targetColumn)})${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`;
26972
+ return this;
26973
+ }
26974
+ /** @internal */
26975
+ getSQL() {
26976
+ return this.dialect.buildInsertQuery(this.config);
26977
+ }
26978
+ toSQL() {
26979
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
26980
+ return rest;
26981
+ }
26982
+ /** @internal */
26983
+ _prepare(name2) {
26984
+ return tracer.startActiveSpan("drizzle.prepareQuery", () => {
26985
+ return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name2, true);
26986
+ });
26987
+ }
26988
+ prepare(name2) {
26989
+ return this._prepare(name2);
26990
+ }
26991
+ /** @internal */
26992
+ setToken(token) {
26993
+ this.authToken = token;
26994
+ return this;
26995
+ }
26996
+ $dynamic() {
26997
+ return this;
26998
+ }
26999
+ };
27000
+ __publicField(PgInsertBase, _a135, "PgInsert");
27001
+ }
27002
+ });
27003
+
27004
+ // ../drizzle-orm/dist/pg-core/query-builders/refresh-materialized-view.js
27005
+ var _a136, _b102, PgRefreshMaterializedView;
27006
+ var init_refresh_materialized_view = __esm({
27007
+ "../drizzle-orm/dist/pg-core/query-builders/refresh-materialized-view.js"() {
27008
+ "use strict";
27009
+ init_entity();
27010
+ init_query_promise();
27011
+ init_tracing();
27012
+ PgRefreshMaterializedView = class extends (_b102 = QueryPromise, _a136 = entityKind, _b102) {
27013
+ constructor(view4, session, dialect4) {
27014
+ super();
27015
+ __publicField(this, "config");
27016
+ __publicField(this, "authToken");
27017
+ __publicField(this, "execute", (placeholderValues) => {
27018
+ return tracer.startActiveSpan("drizzle.operation", () => {
27019
+ return this._prepare().execute(placeholderValues, this.authToken);
27020
+ });
27021
+ });
26924
27022
  this.session = session;
26925
27023
  this.dialect = dialect4;
26926
27024
  this.config = { view: view4 };
@@ -26956,6 +27054,11 @@ var init_refresh_materialized_view = __esm({
26956
27054
  prepare(name2) {
26957
27055
  return this._prepare(name2);
26958
27056
  }
27057
+ /** @internal */
27058
+ setToken(token) {
27059
+ this.authToken = token;
27060
+ return this;
27061
+ }
26959
27062
  };
26960
27063
  __publicField(PgRefreshMaterializedView, _a136, "PgRefreshMaterializedView");
26961
27064
  }
@@ -26974,25 +27077,41 @@ var init_update = __esm({
26974
27077
  "../drizzle-orm/dist/pg-core/query-builders/update.js"() {
26975
27078
  "use strict";
26976
27079
  init_entity();
27080
+ init_table2();
26977
27081
  init_query_promise();
27082
+ init_selection_proxy();
27083
+ init_sql();
27084
+ init_subquery();
26978
27085
  init_table();
26979
27086
  init_utils2();
27087
+ init_view_common();
26980
27088
  _a137 = entityKind;
26981
27089
  PgUpdateBuilder = class {
26982
27090
  constructor(table4, session, dialect4, withList) {
27091
+ __publicField(this, "authToken");
26983
27092
  this.table = table4;
26984
27093
  this.session = session;
26985
27094
  this.dialect = dialect4;
26986
27095
  this.withList = withList;
26987
27096
  }
27097
+ setToken(token) {
27098
+ this.authToken = token;
27099
+ return this;
27100
+ }
26988
27101
  set(values) {
26989
- return new PgUpdateBase(
27102
+ return this.authToken === void 0 ? new PgUpdateBase(
26990
27103
  this.table,
26991
27104
  mapUpdateSet(this.table, values),
26992
27105
  this.session,
26993
27106
  this.dialect,
26994
27107
  this.withList
26995
- );
27108
+ ) : new PgUpdateBase(
27109
+ this.table,
27110
+ mapUpdateSet(this.table, values),
27111
+ this.session,
27112
+ this.dialect,
27113
+ this.withList
27114
+ ).setToken(this.authToken);
26996
27115
  }
26997
27116
  };
26998
27117
  __publicField(PgUpdateBuilder, _a137, "PgUpdateBuilder");
@@ -27000,12 +27119,86 @@ var init_update = __esm({
27000
27119
  constructor(table4, set, session, dialect4, withList) {
27001
27120
  super();
27002
27121
  __publicField(this, "config");
27122
+ __publicField(this, "tableName");
27123
+ __publicField(this, "joinsNotNullableMap");
27124
+ __publicField(this, "leftJoin", this.createJoin("left"));
27125
+ __publicField(this, "rightJoin", this.createJoin("right"));
27126
+ __publicField(this, "innerJoin", this.createJoin("inner"));
27127
+ __publicField(this, "fullJoin", this.createJoin("full"));
27128
+ __publicField(this, "authToken");
27003
27129
  __publicField(this, "execute", (placeholderValues) => {
27004
- return this._prepare().execute(placeholderValues);
27130
+ return this._prepare().execute(placeholderValues, this.authToken);
27005
27131
  });
27006
27132
  this.session = session;
27007
27133
  this.dialect = dialect4;
27008
- this.config = { set, table: table4, withList };
27134
+ this.config = { set, table: table4, withList, joins: [] };
27135
+ this.tableName = getTableLikeName(table4);
27136
+ this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
27137
+ }
27138
+ from(source) {
27139
+ const tableName = getTableLikeName(source);
27140
+ if (typeof tableName === "string") {
27141
+ this.joinsNotNullableMap[tableName] = true;
27142
+ }
27143
+ this.config.from = source;
27144
+ return this;
27145
+ }
27146
+ getTableLikeFields(table4) {
27147
+ if (is(table4, PgTable)) {
27148
+ return table4[Table2.Symbol.Columns];
27149
+ } else if (is(table4, Subquery)) {
27150
+ return table4._.selectedFields;
27151
+ }
27152
+ return table4[ViewBaseConfig].selectedFields;
27153
+ }
27154
+ createJoin(joinType) {
27155
+ return (table4, on) => {
27156
+ const tableName = getTableLikeName(table4);
27157
+ if (typeof tableName === "string" && this.config.joins.some((join) => join.alias === tableName)) {
27158
+ throw new Error(`Alias "${tableName}" is already used in this query`);
27159
+ }
27160
+ if (typeof on === "function") {
27161
+ const from = this.config.from && !is(this.config.from, SQL) ? this.getTableLikeFields(this.config.from) : void 0;
27162
+ on = on(
27163
+ new Proxy(
27164
+ this.config.table[Table2.Symbol.Columns],
27165
+ new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
27166
+ ),
27167
+ from && new Proxy(
27168
+ from,
27169
+ new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
27170
+ )
27171
+ );
27172
+ }
27173
+ this.config.joins.push({ on, table: table4, joinType, alias: tableName });
27174
+ if (typeof tableName === "string") {
27175
+ switch (joinType) {
27176
+ case "left": {
27177
+ this.joinsNotNullableMap[tableName] = false;
27178
+ break;
27179
+ }
27180
+ case "right": {
27181
+ this.joinsNotNullableMap = Object.fromEntries(
27182
+ Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
27183
+ );
27184
+ this.joinsNotNullableMap[tableName] = true;
27185
+ break;
27186
+ }
27187
+ case "inner": {
27188
+ this.joinsNotNullableMap[tableName] = true;
27189
+ break;
27190
+ }
27191
+ case "full": {
27192
+ this.joinsNotNullableMap = Object.fromEntries(
27193
+ Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
27194
+ );
27195
+ this.joinsNotNullableMap[tableName] = false;
27196
+ break;
27197
+ }
27198
+ }
27199
+ }
27200
+ return this;
27201
+ };
27009
27202
  }
27010
27203
  /**
27011
27204
  * Adds a 'where' clause to the query.
@@ -27044,7 +27237,24 @@ var init_update = __esm({
27044
27237
  this.config.where = where;
27045
27238
  return this;
27046
27239
  }
27047
- returning(fields = this.config.table[Table2.Symbol.Columns]) {
27240
+ returning(fields) {
27241
+ if (!fields) {
27242
+ fields = Object.assign({}, this.config.table[Table2.Symbol.Columns]);
27243
+ if (this.config.from) {
27244
+ const tableName = getTableLikeName(this.config.from);
27245
+ if (typeof tableName === "string" && this.config.from && !is(this.config.from, SQL)) {
27246
+ const fromFields = this.getTableLikeFields(this.config.from);
27247
+ fields[tableName] = fromFields;
27248
+ }
27249
+ for (const join of this.config.joins) {
27250
+ const tableName2 = getTableLikeName(join.table);
27251
+ if (typeof tableName2 === "string" && !is(join.table, SQL)) {
27252
+ const fromFields = this.getTableLikeFields(join.table);
27253
+ fields[tableName2] = fromFields;
27254
+ }
27255
+ }
27256
+ }
27257
+ }
27048
27258
  this.config.returning = orderSelectedFields(fields);
27049
27259
  return this;
27050
27260
  }
@@ -27058,11 +27268,18 @@ var init_update = __esm({
27058
27268
  }
27059
27269
  /** @internal */
27060
27270
  _prepare(name2) {
27061
- return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name2, true);
27271
+ const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name2, true);
27272
+ query.joinsNotNullableMap = this.joinsNotNullableMap;
27273
+ return query;
27062
27274
  }
27063
27275
  prepare(name2) {
27064
27276
  return this._prepare(name2);
27065
27277
  }
27278
+ /** @internal */
27279
+ setToken(token) {
27280
+ this.authToken = token;
27281
+ return this;
27282
+ }
27066
27283
  $dynamic() {
27067
27284
  return this;
27068
27285
  }
@@ -27096,6 +27313,7 @@ var init_count = __esm({
27096
27313
  constructor(params) {
27097
27314
  super(_PgCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
27098
27315
  __publicField(this, "sql");
27316
+ __publicField(this, "token");
27099
27317
  __publicField(this, _a139, "PgCountBuilder");
27100
27318
  __publicField(this, "session");
27101
27319
  this.params = params;
@@ -27112,8 +27330,12 @@ var init_count = __esm({
27112
27330
  static buildCount(source, filters) {
27113
27331
  return sql`select count(*) as count from ${source}${sql.raw(" where ").if(filters)}${filters};`;
27114
27332
  }
27333
+ /** @intrnal */
27334
+ setToken(token) {
27335
+ this.token = token;
27336
+ }
27115
27337
  then(onfulfilled, onrejected) {
27116
- return Promise.resolve(this.session.count(this.sql)).then(
27338
+ return Promise.resolve(this.session.count(this.sql, this.token)).then(
27117
27339
  onfulfilled,
27118
27340
  onrejected
27119
27341
  );
@@ -27190,6 +27412,7 @@ var init_query = __esm({
27190
27412
  PgRelationalQuery = class extends (_b105 = QueryPromise, _a141 = entityKind, _b105) {
27191
27413
  constructor(fullSchema, schema4, tableNamesMap, table4, tableConfig, dialect4, session, config, mode) {
27192
27414
  super();
27415
+ __publicField(this, "authToken");
27193
27416
  this.fullSchema = fullSchema;
27194
27417
  this.schema = schema4;
27195
27418
  this.tableNamesMap = tableNamesMap;
@@ -27247,9 +27470,14 @@ var init_query = __esm({
27247
27470
  toSQL() {
27248
27471
  return this._toSQL().builtQuery;
27249
27472
  }
27473
+ /** @internal */
27474
+ setToken(token) {
27475
+ this.authToken = token;
27476
+ return this;
27477
+ }
27250
27478
  execute() {
27251
27479
  return tracer.startActiveSpan("drizzle.operation", () => {
27252
- return this._prepare().execute();
27480
+ return this._prepare().execute(void 0, this.authToken);
27253
27481
  });
27254
27482
  }
27255
27483
  };
@@ -27312,6 +27540,7 @@ var init_db = __esm({
27312
27540
  PgDatabase = class {
27313
27541
  constructor(dialect4, session, schema4) {
27314
27542
  __publicField(this, "query");
27543
+ __publicField(this, "authToken");
27315
27544
  this.dialect = dialect4;
27316
27545
  this.session = session;
27317
27546
  this._ = schema4 ? {
@@ -27567,7 +27796,7 @@ var init_db = __esm({
27567
27796
  false
27568
27797
  );
27569
27798
  return new PgRaw(
27570
- () => prepared.execute(),
27799
+ () => prepared.execute(void 0, this.authToken),
27571
27800
  sequel,
27572
27801
  builtQuery,
27573
27802
  (result) => prepared.mapResult(result, true)
@@ -28112,6 +28341,7 @@ var init_session = __esm({
28112
28341
  _a159 = entityKind;
28113
28342
  PgPreparedQuery = class {
28114
28343
  constructor(query) {
28344
+ __publicField(this, "authToken");
28115
28345
  /** @internal */
28116
28346
  __publicField(this, "joinsNotNullableMap");
28117
28347
  this.query = query;
@@ -28122,6 +28352,11 @@ var init_session = __esm({
28122
28352
  mapResult(response, _isFromBatch) {
28123
28353
  return response;
28124
28354
  }
28355
+ /** @internal */
28356
+ setToken(token) {
28357
+ this.authToken = token;
28358
+ return this;
28359
+ }
28125
28360
  };
28126
28361
  __publicField(PgPreparedQuery, _a159, "PgPreparedQuery");
28127
28362
  _a160 = entityKind;
@@ -28129,7 +28364,8 @@ var init_session = __esm({
28129
28364
  constructor(dialect4) {
28130
28365
  this.dialect = dialect4;
28131
28366
  }
28132
- execute(query) {
28367
+ /** @internal */
28368
+ execute(query, token) {
28133
28369
  return tracer.startActiveSpan("drizzle.operation", () => {
28134
28370
  const prepared = tracer.startActiveSpan("drizzle.prepareQuery", () => {
28135
28371
  return this.prepareQuery(
@@ -28139,7 +28375,7 @@ var init_session = __esm({
28139
28375
  false
28140
28376
  );
28141
28377
  });
28142
- return prepared.execute();
28378
+ return prepared.setToken(token).execute(void 0, token);
28143
28379
  });
28144
28380
  }
28145
28381
  all(query) {
@@ -28150,8 +28386,9 @@ var init_session = __esm({
28150
28386
  false
28151
28387
  ).all();
28152
28388
  }
28153
- async count(sql2) {
28154
- const res = await this.execute(sql2);
28389
+ /** @internal */
28390
+ async count(sql2, token) {
28391
+ const res = await this.execute(sql2, token);
28155
28392
  return Number(
28156
28393
  res[0]["count"]
28157
28394
  );
@@ -30785,180 +31022,12 @@ var init_delete2 = __esm({
30785
31022
  return this;
30786
31023
  }
30787
31024
  returning(fields = this.table[SQLiteTable.Symbol.Columns]) {
30788
- this.config.returning = orderSelectedFields(fields);
30789
- return this;
30790
- }
30791
- /** @internal */
30792
- getSQL() {
30793
- return this.dialect.buildDeleteQuery(this.config);
30794
- }
30795
- toSQL() {
30796
- const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
30797
- return rest;
30798
- }
30799
- /** @internal */
30800
- _prepare(isOneTimeQuery = true) {
30801
- return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](
30802
- this.dialect.sqlToQuery(this.getSQL()),
30803
- this.config.returning,
30804
- this.config.returning ? "all" : "run",
30805
- true
30806
- );
30807
- }
30808
- prepare() {
30809
- return this._prepare(false);
30810
- }
30811
- async execute(placeholderValues) {
30812
- return this._prepare().execute(placeholderValues);
30813
- }
30814
- $dynamic() {
30815
- return this;
30816
- }
30817
- };
30818
- __publicField(SQLiteDeleteBase, _a196, "SQLiteDelete");
30819
- }
30820
- });
30821
-
30822
- // ../drizzle-orm/dist/sqlite-core/query-builders/insert.js
30823
- var _a197, SQLiteInsertBuilder, _a198, _b142, SQLiteInsertBase;
30824
- var init_insert2 = __esm({
30825
- "../drizzle-orm/dist/sqlite-core/query-builders/insert.js"() {
30826
- "use strict";
30827
- init_entity();
30828
- init_query_promise();
30829
- init_sql();
30830
- init_table3();
30831
- init_table();
30832
- init_utils2();
30833
- _a197 = entityKind;
30834
- SQLiteInsertBuilder = class {
30835
- constructor(table4, session, dialect4, withList) {
30836
- this.table = table4;
30837
- this.session = session;
30838
- this.dialect = dialect4;
30839
- this.withList = withList;
30840
- }
30841
- values(values) {
30842
- values = Array.isArray(values) ? values : [values];
30843
- if (values.length === 0) {
30844
- throw new Error("values() must be called with at least one value");
30845
- }
30846
- const mappedValues = values.map((entry) => {
30847
- const result = {};
30848
- const cols = this.table[Table2.Symbol.Columns];
30849
- for (const colKey of Object.keys(entry)) {
30850
- const colValue = entry[colKey];
30851
- result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
30852
- }
30853
- return result;
30854
- });
30855
- return new SQLiteInsertBase(this.table, mappedValues, this.session, this.dialect, this.withList);
30856
- }
30857
- };
30858
- __publicField(SQLiteInsertBuilder, _a197, "SQLiteInsertBuilder");
30859
- SQLiteInsertBase = class extends (_b142 = QueryPromise, _a198 = entityKind, _b142) {
30860
- constructor(table4, values, session, dialect4, withList) {
30861
- super();
30862
- /** @internal */
30863
- __publicField(this, "config");
30864
- __publicField(this, "run", (placeholderValues) => {
30865
- return this._prepare().run(placeholderValues);
30866
- });
30867
- __publicField(this, "all", (placeholderValues) => {
30868
- return this._prepare().all(placeholderValues);
30869
- });
30870
- __publicField(this, "get", (placeholderValues) => {
30871
- return this._prepare().get(placeholderValues);
30872
- });
30873
- __publicField(this, "values", (placeholderValues) => {
30874
- return this._prepare().values(placeholderValues);
30875
- });
30876
- this.session = session;
30877
- this.dialect = dialect4;
30878
- this.config = { table: table4, values, withList };
30879
- }
30880
- returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) {
30881
- this.config.returning = orderSelectedFields(fields);
30882
- return this;
30883
- }
30884
- /**
30885
- * Adds an `on conflict do nothing` clause to the query.
30886
- *
30887
- * Calling this method simply avoids inserting a row as its alternative action.
30888
- *
30889
- * See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}
30890
- *
30891
- * @param config The `target` and `where` clauses.
30892
- *
30893
- * @example
30894
- * ```ts
30895
- * // Insert one row and cancel the insert if there's a conflict
30896
- * await db.insert(cars)
30897
- * .values({ id: 1, brand: 'BMW' })
30898
- * .onConflictDoNothing();
30899
- *
30900
- * // Explicitly specify conflict target
30901
- * await db.insert(cars)
30902
- * .values({ id: 1, brand: 'BMW' })
30903
- * .onConflictDoNothing({ target: cars.id });
30904
- * ```
30905
- */
30906
- onConflictDoNothing(config = {}) {
30907
- if (config.target === void 0) {
30908
- this.config.onConflict = sql`do nothing`;
30909
- } else {
30910
- const targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;
30911
- const whereSql = config.where ? sql` where ${config.where}` : sql``;
30912
- this.config.onConflict = sql`${targetSql} do nothing${whereSql}`;
30913
- }
30914
- return this;
30915
- }
30916
- /**
30917
- * Adds an `on conflict do update` clause to the query.
30918
- *
30919
- * Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.
30920
- *
30921
- * See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}
30922
- *
30923
- * @param config The `target`, `set` and `where` clauses.
30924
- *
30925
- * @example
30926
- * ```ts
30927
- * // Update the row if there's a conflict
30928
- * await db.insert(cars)
30929
- * .values({ id: 1, brand: 'BMW' })
30930
- * .onConflictDoUpdate({
30931
- * target: cars.id,
30932
- * set: { brand: 'Porsche' }
30933
- * });
30934
- *
30935
- * // Upsert with 'where' clause
30936
- * await db.insert(cars)
30937
- * .values({ id: 1, brand: 'BMW' })
30938
- * .onConflictDoUpdate({
30939
- * target: cars.id,
30940
- * set: { brand: 'newBMW' },
30941
- * where: sql`${cars.createdAt} > '2023-01-01'::date`,
30942
- * });
30943
- * ```
30944
- */
30945
- onConflictDoUpdate(config) {
30946
- if (config.where && (config.targetWhere || config.setWhere)) {
30947
- throw new Error(
30948
- 'You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.'
30949
- );
30950
- }
30951
- const whereSql = config.where ? sql` where ${config.where}` : void 0;
30952
- const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : void 0;
30953
- const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : void 0;
30954
- const targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;
30955
- const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
30956
- this.config.onConflict = sql`${targetSql}${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`;
31025
+ this.config.returning = orderSelectedFields(fields);
30957
31026
  return this;
30958
31027
  }
30959
31028
  /** @internal */
30960
31029
  getSQL() {
30961
- return this.dialect.buildInsertQuery(this.config);
31030
+ return this.dialect.buildDeleteQuery(this.config);
30962
31031
  }
30963
31032
  toSQL() {
30964
31033
  const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
@@ -30976,32 +31045,32 @@ var init_insert2 = __esm({
30976
31045
  prepare() {
30977
31046
  return this._prepare(false);
30978
31047
  }
30979
- async execute() {
30980
- return this.config.returning ? this.all() : this.run();
31048
+ async execute(placeholderValues) {
31049
+ return this._prepare().execute(placeholderValues);
30981
31050
  }
30982
31051
  $dynamic() {
30983
31052
  return this;
30984
31053
  }
30985
31054
  };
30986
- __publicField(SQLiteInsertBase, _a198, "SQLiteInsert");
31055
+ __publicField(SQLiteDeleteBase, _a196, "SQLiteDelete");
30987
31056
  }
30988
31057
  });
30989
31058
 
30990
31059
  // ../drizzle-orm/dist/sqlite-core/view-base.js
30991
- var _a199, _b143, SQLiteViewBase;
31060
+ var _a197, _b142, SQLiteViewBase;
30992
31061
  var init_view_base2 = __esm({
30993
31062
  "../drizzle-orm/dist/sqlite-core/view-base.js"() {
30994
31063
  "use strict";
30995
31064
  init_entity();
30996
31065
  init_sql();
30997
- SQLiteViewBase = class extends (_b143 = View3, _a199 = entityKind, _b143) {
31066
+ SQLiteViewBase = class extends (_b142 = View3, _a197 = entityKind, _b142) {
30998
31067
  };
30999
- __publicField(SQLiteViewBase, _a199, "SQLiteViewBase");
31068
+ __publicField(SQLiteViewBase, _a197, "SQLiteViewBase");
31000
31069
  }
31001
31070
  });
31002
31071
 
31003
31072
  // ../drizzle-orm/dist/sqlite-core/dialect.js
31004
- var _a200, SQLiteDialect, _a201, _b144, SQLiteSyncDialect, _a202, _b145, SQLiteAsyncDialect;
31073
+ var _a198, SQLiteDialect, _a199, _b143, SQLiteSyncDialect, _a200, _b144, SQLiteAsyncDialect;
31005
31074
  var init_dialect2 = __esm({
31006
31075
  "../drizzle-orm/dist/sqlite-core/dialect.js"() {
31007
31076
  "use strict";
@@ -31020,7 +31089,7 @@ var init_dialect2 = __esm({
31020
31089
  init_utils2();
31021
31090
  init_view_common();
31022
31091
  init_view_base2();
31023
- _a200 = entityKind;
31092
+ _a198 = entityKind;
31024
31093
  SQLiteDialect = class {
31025
31094
  constructor(config) {
31026
31095
  /** @internal */
@@ -31073,14 +31142,16 @@ var init_dialect2 = __esm({
31073
31142
  return [res];
31074
31143
  }));
31075
31144
  }
31076
- buildUpdateQuery({ table: table4, set, where, returning, withList, limit, orderBy }) {
31145
+ buildUpdateQuery({ table: table4, set, where, returning, withList, joins, from, limit, orderBy }) {
31077
31146
  const withSql = this.buildWithCTE(withList);
31078
31147
  const setSql = this.buildUpdateSet(table4, set);
31148
+ const fromSql = from && sql.join([sql.raw(" from "), this.buildFromTable(from)]);
31149
+ const joinsSql = this.buildJoins(joins);
31079
31150
  const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
31080
31151
  const whereSql = where ? sql` where ${where}` : void 0;
31081
31152
  const orderBySql = this.buildOrderBy(orderBy);
31082
31153
  const limitSql = this.buildLimit(limit);
31083
- return sql`${withSql}update ${table4} set ${setSql}${whereSql}${returningSql}${orderBySql}${limitSql}`;
31154
+ return sql`${withSql}update ${table4} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}${orderBySql}${limitSql}`;
31084
31155
  }
31085
31156
  /**
31086
31157
  * Builds selection SQL with provided fields/expressions
@@ -31133,6 +31204,37 @@ var init_dialect2 = __esm({
31133
31204
  });
31134
31205
  return sql.join(chunks);
31135
31206
  }
31207
+ buildJoins(joins) {
31208
+ if (!joins || joins.length === 0) {
31209
+ return void 0;
31210
+ }
31211
+ const joinsArray = [];
31212
+ if (joins) {
31213
+ for (const [index4, joinMeta] of joins.entries()) {
31214
+ if (index4 === 0) {
31215
+ joinsArray.push(sql` `);
31216
+ }
31217
+ const table4 = joinMeta.table;
31218
+ if (is(table4, SQLiteTable)) {
31219
+ const tableName = table4[SQLiteTable.Symbol.Name];
31220
+ const tableSchema = table4[SQLiteTable.Symbol.Schema];
31221
+ const origTableName = table4[SQLiteTable.Symbol.OriginalName];
31222
+ const alias = tableName === origTableName ? void 0 : joinMeta.alias;
31223
+ joinsArray.push(
31224
+ sql`${sql.raw(joinMeta.joinType)} join ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}`
31225
+ );
31226
+ } else {
31227
+ joinsArray.push(
31228
+ sql`${sql.raw(joinMeta.joinType)} join ${table4} on ${joinMeta.on}`
31229
+ );
31230
+ }
31231
+ if (index4 < joins.length - 1) {
31232
+ joinsArray.push(sql` `);
31233
+ }
31234
+ }
31235
+ }
31236
+ return sql.join(joinsArray);
31237
+ }
31136
31238
  buildLimit(limit) {
31137
31239
  return typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
31138
31240
  }
@@ -31148,6 +31250,12 @@ var init_dialect2 = __esm({
31148
31250
  }
31149
31251
  return orderByList.length > 0 ? sql` order by ${sql.join(orderByList)}` : void 0;
31150
31252
  }
31253
+ buildFromTable(table4) {
31254
+ if (is(table4, Table2) && table4[Table2.Symbol.OriginalName] !== table4[Table2.Symbol.Name]) {
31255
+ return sql`${sql.identifier(table4[Table2.Symbol.OriginalName])} ${sql.identifier(table4[Table2.Symbol.Name])}`;
31256
+ }
31257
+ return table4;
31258
+ }
31151
31259
  buildSelectQuery({
31152
31260
  withList,
31153
31261
  fields,
@@ -31178,38 +31286,8 @@ var init_dialect2 = __esm({
31178
31286
  const withSql = this.buildWithCTE(withList);
31179
31287
  const distinctSql = distinct ? sql` distinct` : void 0;
31180
31288
  const selection = this.buildSelection(fieldsList, { isSingleTable });
31181
- const tableSql = (() => {
31182
- if (is(table4, Table2) && table4[Table2.Symbol.OriginalName] !== table4[Table2.Symbol.Name]) {
31183
- return sql`${sql.identifier(table4[Table2.Symbol.OriginalName])} ${sql.identifier(table4[Table2.Symbol.Name])}`;
31184
- }
31185
- return table4;
31186
- })();
31187
- const joinsArray = [];
31188
- if (joins) {
31189
- for (const [index4, joinMeta] of joins.entries()) {
31190
- if (index4 === 0) {
31191
- joinsArray.push(sql` `);
31192
- }
31193
- const table22 = joinMeta.table;
31194
- if (is(table22, SQLiteTable)) {
31195
- const tableName = table22[SQLiteTable.Symbol.Name];
31196
- const tableSchema = table22[SQLiteTable.Symbol.Schema];
31197
- const origTableName = table22[SQLiteTable.Symbol.OriginalName];
31198
- const alias = tableName === origTableName ? void 0 : joinMeta.alias;
31199
- joinsArray.push(
31200
- sql`${sql.raw(joinMeta.joinType)} join ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}`
31201
- );
31202
- } else {
31203
- joinsArray.push(
31204
- sql`${sql.raw(joinMeta.joinType)} join ${table22} on ${joinMeta.on}`
31205
- );
31206
- }
31207
- if (index4 < joins.length - 1) {
31208
- joinsArray.push(sql` `);
31209
- }
31210
- }
31211
- }
31212
- const joinsSql = sql.join(joinsArray);
31289
+ const tableSql = this.buildFromTable(table4);
31290
+ const joinsSql = this.buildJoins(joins);
31213
31291
  const whereSql = where ? sql` where ${where}` : void 0;
31214
31292
  const havingSql = having ? sql` having ${having}` : void 0;
31215
31293
  const groupByList = [];
@@ -31275,45 +31353,56 @@ var init_dialect2 = __esm({
31275
31353
  const offsetSql = offset ? sql` offset ${offset}` : void 0;
31276
31354
  return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
31277
31355
  }
31278
- buildInsertQuery({ table: table4, values, onConflict, returning, withList }) {
31356
+ buildInsertQuery({ table: table4, values: valuesOrSelect, onConflict, returning, withList, select }) {
31279
31357
  const valuesSqlList = [];
31280
31358
  const columns = table4[Table2.Symbol.Columns];
31281
31359
  const colEntries = Object.entries(columns).filter(
31282
31360
  ([_2, col]) => !col.shouldDisableInsert()
31283
31361
  );
31284
31362
  const insertOrder = colEntries.map(([, column4]) => sql.identifier(this.casing.getColumnCasing(column4)));
31285
- for (const [valueIndex, value] of values.entries()) {
31286
- const valueList = [];
31287
- for (const [fieldName, col] of colEntries) {
31288
- const colValue = value[fieldName];
31289
- if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) {
31290
- let defaultValue;
31291
- if (col.default !== null && col.default !== void 0) {
31292
- defaultValue = is(col.default, SQL) ? col.default : sql.param(col.default, col);
31293
- } else if (col.defaultFn !== void 0) {
31294
- const defaultFnResult = col.defaultFn();
31295
- defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
31296
- } else if (!col.default && col.onUpdateFn !== void 0) {
31297
- const onUpdateFnResult = col.onUpdateFn();
31298
- defaultValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
31363
+ if (select) {
31364
+ const select2 = valuesOrSelect;
31365
+ if (is(select2, SQL)) {
31366
+ valuesSqlList.push(select2);
31367
+ } else {
31368
+ valuesSqlList.push(select2.getSQL());
31369
+ }
31370
+ } else {
31371
+ const values = valuesOrSelect;
31372
+ valuesSqlList.push(sql.raw("values "));
31373
+ for (const [valueIndex, value] of values.entries()) {
31374
+ const valueList = [];
31375
+ for (const [fieldName, col] of colEntries) {
31376
+ const colValue = value[fieldName];
31377
+ if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) {
31378
+ let defaultValue;
31379
+ if (col.default !== null && col.default !== void 0) {
31380
+ defaultValue = is(col.default, SQL) ? col.default : sql.param(col.default, col);
31381
+ } else if (col.defaultFn !== void 0) {
31382
+ const defaultFnResult = col.defaultFn();
31383
+ defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
31384
+ } else if (!col.default && col.onUpdateFn !== void 0) {
31385
+ const onUpdateFnResult = col.onUpdateFn();
31386
+ defaultValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
31387
+ } else {
31388
+ defaultValue = sql`null`;
31389
+ }
31390
+ valueList.push(defaultValue);
31299
31391
  } else {
31300
- defaultValue = sql`null`;
31392
+ valueList.push(colValue);
31301
31393
  }
31302
- valueList.push(defaultValue);
31303
- } else {
31304
- valueList.push(colValue);
31305
31394
  }
31306
- }
31307
- valuesSqlList.push(valueList);
31308
- if (valueIndex < values.length - 1) {
31309
- valuesSqlList.push(sql`, `);
31395
+ valuesSqlList.push(valueList);
31396
+ if (valueIndex < values.length - 1) {
31397
+ valuesSqlList.push(sql`, `);
31398
+ }
31310
31399
  }
31311
31400
  }
31312
31401
  const withSql = this.buildWithCTE(withList);
31313
31402
  const valuesSql = sql.join(valuesSqlList);
31314
31403
  const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
31315
31404
  const onConflictSql = onConflict ? sql` on conflict ${onConflict}` : void 0;
31316
- return sql`${withSql}insert into ${table4} ${insertOrder} values ${valuesSql}${onConflictSql}${returningSql}`;
31405
+ return sql`${withSql}insert into ${table4} ${insertOrder} ${valuesSql}${onConflictSql}${returningSql}`;
31317
31406
  }
31318
31407
  sqlToQuery(sql2, invokeSource) {
31319
31408
  return sql2.toQuery({
@@ -31542,8 +31631,8 @@ var init_dialect2 = __esm({
31542
31631
  };
31543
31632
  }
31544
31633
  };
31545
- __publicField(SQLiteDialect, _a200, "SQLiteDialect");
31546
- SQLiteSyncDialect = class extends (_b144 = SQLiteDialect, _a201 = entityKind, _b144) {
31634
+ __publicField(SQLiteDialect, _a198, "SQLiteDialect");
31635
+ SQLiteSyncDialect = class extends (_b143 = SQLiteDialect, _a199 = entityKind, _b143) {
31547
31636
  migrate(migrations, session, config) {
31548
31637
  const migrationsTable = config === void 0 ? "__drizzle_migrations" : typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
31549
31638
  const migrationTableCreate = sql`
@@ -31577,8 +31666,8 @@ var init_dialect2 = __esm({
31577
31666
  }
31578
31667
  }
31579
31668
  };
31580
- __publicField(SQLiteSyncDialect, _a201, "SQLiteSyncDialect");
31581
- SQLiteAsyncDialect = class extends (_b145 = SQLiteDialect, _a202 = entityKind, _b145) {
31669
+ __publicField(SQLiteSyncDialect, _a199, "SQLiteSyncDialect");
31670
+ SQLiteAsyncDialect = class extends (_b144 = SQLiteDialect, _a200 = entityKind, _b144) {
31582
31671
  async migrate(migrations, session, config) {
31583
31672
  const migrationsTable = config === void 0 ? "__drizzle_migrations" : typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
31584
31673
  const migrationTableCreate = sql`
@@ -31607,7 +31696,7 @@ var init_dialect2 = __esm({
31607
31696
  });
31608
31697
  }
31609
31698
  };
31610
- __publicField(SQLiteAsyncDialect, _a202, "SQLiteAsyncDialect");
31699
+ __publicField(SQLiteAsyncDialect, _a200, "SQLiteAsyncDialect");
31611
31700
  }
31612
31701
  });
31613
31702
 
@@ -31629,7 +31718,7 @@ function createSetOperator2(type, isAll) {
31629
31718
  return leftSelect.addSetOperators(setOperators);
31630
31719
  };
31631
31720
  }
31632
- var _a203, SQLiteSelectBuilder, _a204, _b146, SQLiteSelectQueryBuilderBase, _a205, _b147, SQLiteSelectBase, getSQLiteSetOperators, union2, unionAll2, intersect2, except2;
31721
+ var _a201, SQLiteSelectBuilder, _a202, _b145, SQLiteSelectQueryBuilderBase, _a203, _b146, SQLiteSelectBase, getSQLiteSetOperators, union2, unionAll2, intersect2, except2;
31633
31722
  var init_select3 = __esm({
31634
31723
  "../drizzle-orm/dist/sqlite-core/query-builders/select.js"() {
31635
31724
  "use strict";
@@ -31643,7 +31732,7 @@ var init_select3 = __esm({
31643
31732
  init_utils2();
31644
31733
  init_view_common();
31645
31734
  init_view_base2();
31646
- _a203 = entityKind;
31735
+ _a201 = entityKind;
31647
31736
  SQLiteSelectBuilder = class {
31648
31737
  constructor(config) {
31649
31738
  __publicField(this, "fields");
@@ -31684,8 +31773,8 @@ var init_select3 = __esm({
31684
31773
  });
31685
31774
  }
31686
31775
  };
31687
- __publicField(SQLiteSelectBuilder, _a203, "SQLiteSelectBuilder");
31688
- SQLiteSelectQueryBuilderBase = class extends (_b146 = TypedQueryBuilder, _a204 = entityKind, _b146) {
31776
+ __publicField(SQLiteSelectBuilder, _a201, "SQLiteSelectBuilder");
31777
+ SQLiteSelectQueryBuilderBase = class extends (_b145 = TypedQueryBuilder, _a202 = entityKind, _b145) {
31689
31778
  constructor({ table: table4, fields, isPartialSelect, session, dialect: dialect4, withList, distinct }) {
31690
31779
  super();
31691
31780
  __publicField(this, "_");
@@ -32190,8 +32279,8 @@ var init_select3 = __esm({
32190
32279
  return this;
32191
32280
  }
32192
32281
  };
32193
- __publicField(SQLiteSelectQueryBuilderBase, _a204, "SQLiteSelectQueryBuilder");
32194
- SQLiteSelectBase = class extends (_b147 = SQLiteSelectQueryBuilderBase, _a205 = entityKind, _b147) {
32282
+ __publicField(SQLiteSelectQueryBuilderBase, _a202, "SQLiteSelectQueryBuilder");
32283
+ SQLiteSelectBase = class extends (_b146 = SQLiteSelectQueryBuilderBase, _a203 = entityKind, _b146) {
32195
32284
  constructor() {
32196
32285
  super(...arguments);
32197
32286
  __publicField(this, "run", (placeholderValues) => {
@@ -32229,7 +32318,7 @@ var init_select3 = __esm({
32229
32318
  return this.all();
32230
32319
  }
32231
32320
  };
32232
- __publicField(SQLiteSelectBase, _a205, "SQLiteSelect");
32321
+ __publicField(SQLiteSelectBase, _a203, "SQLiteSelect");
32233
32322
  applyMixins(SQLiteSelectBase, [QueryPromise]);
32234
32323
  getSQLiteSetOperators = () => ({
32235
32324
  union: union2,
@@ -32245,7 +32334,7 @@ var init_select3 = __esm({
32245
32334
  });
32246
32335
 
32247
32336
  // ../drizzle-orm/dist/sqlite-core/query-builders/query-builder.js
32248
- var _a206, QueryBuilder2;
32337
+ var _a204, QueryBuilder2;
32249
32338
  var init_query_builder3 = __esm({
32250
32339
  "../drizzle-orm/dist/sqlite-core/query-builders/query-builder.js"() {
32251
32340
  "use strict";
@@ -32254,7 +32343,7 @@ var init_query_builder3 = __esm({
32254
32343
  init_dialect2();
32255
32344
  init_subquery();
32256
32345
  init_select3();
32257
- _a206 = entityKind;
32346
+ _a204 = entityKind;
32258
32347
  QueryBuilder2 = class {
32259
32348
  constructor(dialect4) {
32260
32349
  __publicField(this, "dialect");
@@ -32316,7 +32405,185 @@ var init_query_builder3 = __esm({
32316
32405
  return this.dialect;
32317
32406
  }
32318
32407
  };
32319
- __publicField(QueryBuilder2, _a206, "SQLiteQueryBuilder");
32408
+ __publicField(QueryBuilder2, _a204, "SQLiteQueryBuilder");
32409
+ }
32410
+ });
32411
+
32412
+ // ../drizzle-orm/dist/sqlite-core/query-builders/insert.js
32413
+ var _a205, SQLiteInsertBuilder, _a206, _b147, SQLiteInsertBase;
32414
+ var init_insert2 = __esm({
32415
+ "../drizzle-orm/dist/sqlite-core/query-builders/insert.js"() {
32416
+ "use strict";
32417
+ init_entity();
32418
+ init_query_promise();
32419
+ init_sql();
32420
+ init_table3();
32421
+ init_table();
32422
+ init_utils2();
32423
+ init_query_builder3();
32424
+ _a205 = entityKind;
32425
+ SQLiteInsertBuilder = class {
32426
+ constructor(table4, session, dialect4, withList) {
32427
+ this.table = table4;
32428
+ this.session = session;
32429
+ this.dialect = dialect4;
32430
+ this.withList = withList;
32431
+ }
32432
+ values(values) {
32433
+ values = Array.isArray(values) ? values : [values];
32434
+ if (values.length === 0) {
32435
+ throw new Error("values() must be called with at least one value");
32436
+ }
32437
+ const mappedValues = values.map((entry) => {
32438
+ const result = {};
32439
+ const cols = this.table[Table2.Symbol.Columns];
32440
+ for (const colKey of Object.keys(entry)) {
32441
+ const colValue = entry[colKey];
32442
+ result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
32443
+ }
32444
+ return result;
32445
+ });
32446
+ return new SQLiteInsertBase(this.table, mappedValues, this.session, this.dialect, this.withList);
32447
+ }
32448
+ select(selectQuery) {
32449
+ const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder2()) : selectQuery;
32450
+ if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) {
32451
+ throw new Error(
32452
+ "Insert select error: selected fields are not the same or are in a different order compared to the table definition"
32453
+ );
32454
+ }
32455
+ return new SQLiteInsertBase(this.table, select, this.session, this.dialect, this.withList, true);
32456
+ }
32457
+ };
32458
+ __publicField(SQLiteInsertBuilder, _a205, "SQLiteInsertBuilder");
32459
+ SQLiteInsertBase = class extends (_b147 = QueryPromise, _a206 = entityKind, _b147) {
32460
+ constructor(table4, values, session, dialect4, withList, select) {
32461
+ super();
32462
+ /** @internal */
32463
+ __publicField(this, "config");
32464
+ __publicField(this, "run", (placeholderValues) => {
32465
+ return this._prepare().run(placeholderValues);
32466
+ });
32467
+ __publicField(this, "all", (placeholderValues) => {
32468
+ return this._prepare().all(placeholderValues);
32469
+ });
32470
+ __publicField(this, "get", (placeholderValues) => {
32471
+ return this._prepare().get(placeholderValues);
32472
+ });
32473
+ __publicField(this, "values", (placeholderValues) => {
32474
+ return this._prepare().values(placeholderValues);
32475
+ });
32476
+ this.session = session;
32477
+ this.dialect = dialect4;
32478
+ this.config = { table: table4, values, withList, select };
32479
+ }
32480
+ returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) {
32481
+ this.config.returning = orderSelectedFields(fields);
32482
+ return this;
32483
+ }
32484
+ /**
32485
+ * Adds an `on conflict do nothing` clause to the query.
32486
+ *
32487
+ * Calling this method simply avoids inserting a row as its alternative action.
32488
+ *
32489
+ * See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}
32490
+ *
32491
+ * @param config The `target` and `where` clauses.
32492
+ *
32493
+ * @example
32494
+ * ```ts
32495
+ * // Insert one row and cancel the insert if there's a conflict
32496
+ * await db.insert(cars)
32497
+ * .values({ id: 1, brand: 'BMW' })
32498
+ * .onConflictDoNothing();
32499
+ *
32500
+ * // Explicitly specify conflict target
32501
+ * await db.insert(cars)
32502
+ * .values({ id: 1, brand: 'BMW' })
32503
+ * .onConflictDoNothing({ target: cars.id });
32504
+ * ```
32505
+ */
32506
+ onConflictDoNothing(config = {}) {
32507
+ if (config.target === void 0) {
32508
+ this.config.onConflict = sql`do nothing`;
32509
+ } else {
32510
+ const targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;
32511
+ const whereSql = config.where ? sql` where ${config.where}` : sql``;
32512
+ this.config.onConflict = sql`${targetSql} do nothing${whereSql}`;
32513
+ }
32514
+ return this;
32515
+ }
32516
+ /**
32517
+ * Adds an `on conflict do update` clause to the query.
32518
+ *
32519
+ * Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.
32520
+ *
32521
+ * See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}
32522
+ *
32523
+ * @param config The `target`, `set` and `where` clauses.
32524
+ *
32525
+ * @example
32526
+ * ```ts
32527
+ * // Update the row if there's a conflict
32528
+ * await db.insert(cars)
32529
+ * .values({ id: 1, brand: 'BMW' })
32530
+ * .onConflictDoUpdate({
32531
+ * target: cars.id,
32532
+ * set: { brand: 'Porsche' }
32533
+ * });
32534
+ *
32535
+ * // Upsert with 'where' clause
32536
+ * await db.insert(cars)
32537
+ * .values({ id: 1, brand: 'BMW' })
32538
+ * .onConflictDoUpdate({
32539
+ * target: cars.id,
32540
+ * set: { brand: 'newBMW' },
32541
+ * where: sql`${cars.createdAt} > '2023-01-01'::date`,
32542
+ * });
32543
+ * ```
32544
+ */
32545
+ onConflictDoUpdate(config) {
32546
+ if (config.where && (config.targetWhere || config.setWhere)) {
32547
+ throw new Error(
32548
+ 'You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.'
32549
+ );
32550
+ }
32551
+ const whereSql = config.where ? sql` where ${config.where}` : void 0;
32552
+ const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : void 0;
32553
+ const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : void 0;
32554
+ const targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;
32555
+ const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
32556
+ this.config.onConflict = sql`${targetSql}${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`;
32557
+ return this;
32558
+ }
32559
+ /** @internal */
32560
+ getSQL() {
32561
+ return this.dialect.buildInsertQuery(this.config);
32562
+ }
32563
+ toSQL() {
32564
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
32565
+ return rest;
32566
+ }
32567
+ /** @internal */
32568
+ _prepare(isOneTimeQuery = true) {
32569
+ return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](
32570
+ this.dialect.sqlToQuery(this.getSQL()),
32571
+ this.config.returning,
32572
+ this.config.returning ? "all" : "run",
32573
+ true
32574
+ );
32575
+ }
32576
+ prepare() {
32577
+ return this._prepare(false);
32578
+ }
32579
+ async execute() {
32580
+ return this.config.returning ? this.all() : this.run();
32581
+ }
32582
+ $dynamic() {
32583
+ return this;
32584
+ }
32585
+ };
32586
+ __publicField(SQLiteInsertBase, _a206, "SQLiteInsert");
32320
32587
  }
32321
32588
  });
32322
32589
 
@@ -32336,8 +32603,11 @@ var init_update2 = __esm({
32336
32603
  init_query_promise();
32337
32604
  init_selection_proxy();
32338
32605
  init_table3();
32606
+ init_subquery();
32339
32607
  init_table();
32340
32608
  init_utils2();
32609
+ init_view_common();
32610
+ init_view_base2();
32341
32611
  _a207 = entityKind;
32342
32612
  SQLiteUpdateBuilder = class {
32343
32613
  constructor(table4, session, dialect4, withList) {
@@ -32362,6 +32632,10 @@ var init_update2 = __esm({
32362
32632
  super();
32363
32633
  /** @internal */
32364
32634
  __publicField(this, "config");
32635
+ __publicField(this, "leftJoin", this.createJoin("left"));
32636
+ __publicField(this, "rightJoin", this.createJoin("right"));
32637
+ __publicField(this, "innerJoin", this.createJoin("inner"));
32638
+ __publicField(this, "fullJoin", this.createJoin("full"));
32365
32639
  __publicField(this, "run", (placeholderValues) => {
32366
32640
  return this._prepare().run(placeholderValues);
32367
32641
  });
@@ -32376,7 +32650,34 @@ var init_update2 = __esm({
32376
32650
  });
32377
32651
  this.session = session;
32378
32652
  this.dialect = dialect4;
32379
- this.config = { set, table: table4, withList };
32653
+ this.config = { set, table: table4, withList, joins: [] };
32654
+ }
32655
+ from(source) {
32656
+ this.config.from = source;
32657
+ return this;
32658
+ }
32659
+ createJoin(joinType) {
32660
+ return (table4, on) => {
32661
+ const tableName = getTableLikeName(table4);
32662
+ if (typeof tableName === "string" && this.config.joins.some((join) => join.alias === tableName)) {
32663
+ throw new Error(`Alias "${tableName}" is already used in this query`);
32664
+ }
32665
+ if (typeof on === "function") {
32666
+ const from = this.config.from ? is(table4, SQLiteTable) ? table4[Table2.Symbol.Columns] : is(table4, Subquery) ? table4._.selectedFields : is(table4, SQLiteViewBase) ? table4[ViewBaseConfig].selectedFields : void 0 : void 0;
32667
+ on = on(
32668
+ new Proxy(
32669
+ this.config.table[Table2.Symbol.Columns],
32670
+ new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
32671
+ ),
32672
+ from && new Proxy(
32673
+ from,
32674
+ new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
32675
+ )
32676
+ );
32677
+ }
32678
+ this.config.joins.push({ on, table: table4, joinType, alias: tableName });
32679
+ return this;
32680
+ };
32380
32681
  }
32381
32682
  /**
32382
32683
  * Adds a 'where' clause to the query.
@@ -35674,131 +35975,6 @@ var init_delete3 = __esm({
35674
35975
  }
35675
35976
  });
35676
35977
 
35677
- // ../drizzle-orm/dist/mysql-core/query-builders/insert.js
35678
- var _a299, MySqlInsertBuilder, _a300, _b222, MySqlInsertBase;
35679
- var init_insert3 = __esm({
35680
- "../drizzle-orm/dist/mysql-core/query-builders/insert.js"() {
35681
- "use strict";
35682
- init_entity();
35683
- init_query_promise();
35684
- init_sql();
35685
- init_table();
35686
- init_utils2();
35687
- _a299 = entityKind;
35688
- MySqlInsertBuilder = class {
35689
- constructor(table4, session, dialect4) {
35690
- __publicField(this, "shouldIgnore", false);
35691
- this.table = table4;
35692
- this.session = session;
35693
- this.dialect = dialect4;
35694
- }
35695
- ignore() {
35696
- this.shouldIgnore = true;
35697
- return this;
35698
- }
35699
- values(values) {
35700
- values = Array.isArray(values) ? values : [values];
35701
- if (values.length === 0) {
35702
- throw new Error("values() must be called with at least one value");
35703
- }
35704
- const mappedValues = values.map((entry) => {
35705
- const result = {};
35706
- const cols = this.table[Table2.Symbol.Columns];
35707
- for (const colKey of Object.keys(entry)) {
35708
- const colValue = entry[colKey];
35709
- result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
35710
- }
35711
- return result;
35712
- });
35713
- return new MySqlInsertBase(this.table, mappedValues, this.shouldIgnore, this.session, this.dialect);
35714
- }
35715
- };
35716
- __publicField(MySqlInsertBuilder, _a299, "MySqlInsertBuilder");
35717
- MySqlInsertBase = class extends (_b222 = QueryPromise, _a300 = entityKind, _b222) {
35718
- constructor(table4, values, ignore, session, dialect4) {
35719
- super();
35720
- __publicField(this, "config");
35721
- __publicField(this, "execute", (placeholderValues) => {
35722
- return this.prepare().execute(placeholderValues);
35723
- });
35724
- __publicField(this, "createIterator", () => {
35725
- const self2 = this;
35726
- return async function* (placeholderValues) {
35727
- yield* self2.prepare().iterator(placeholderValues);
35728
- };
35729
- });
35730
- __publicField(this, "iterator", this.createIterator());
35731
- this.session = session;
35732
- this.dialect = dialect4;
35733
- this.config = { table: table4, values, ignore };
35734
- }
35735
- /**
35736
- * Adds an `on duplicate key update` clause to the query.
35737
- *
35738
- * Calling this method will update update the row if any unique index conflicts. MySQL will automatically determine the conflict target based on the primary key and unique indexes.
35739
- *
35740
- * See docs: {@link https://orm.drizzle.team/docs/insert#on-duplicate-key-update}
35741
- *
35742
- * @param config The `set` clause
35743
- *
35744
- * @example
35745
- * ```ts
35746
- * await db.insert(cars)
35747
- * .values({ id: 1, brand: 'BMW'})
35748
- * .onDuplicateKeyUpdate({ set: { brand: 'Porsche' }});
35749
- * ```
35750
- *
35751
- * 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:
35752
- *
35753
- * ```ts
35754
- * import { sql } from 'drizzle-orm';
35755
- *
35756
- * await db.insert(cars)
35757
- * .values({ id: 1, brand: 'BMW' })
35758
- * .onDuplicateKeyUpdate({ set: { id: sql`id` } });
35759
- * ```
35760
- */
35761
- onDuplicateKeyUpdate(config) {
35762
- const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
35763
- this.config.onConflict = sql`update ${setSql}`;
35764
- return this;
35765
- }
35766
- $returningId() {
35767
- const returning = [];
35768
- for (const [key, value] of Object.entries(this.config.table[Table2.Symbol.Columns])) {
35769
- if (value.primary) {
35770
- returning.push({ field: value, path: [key] });
35771
- }
35772
- }
35773
- this.config.returning = orderSelectedFields(this.config.table[Table2.Symbol.Columns]);
35774
- return this;
35775
- }
35776
- /** @internal */
35777
- getSQL() {
35778
- return this.dialect.buildInsertQuery(this.config).sql;
35779
- }
35780
- toSQL() {
35781
- const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
35782
- return rest;
35783
- }
35784
- prepare() {
35785
- const { sql: sql2, generatedIds } = this.dialect.buildInsertQuery(this.config);
35786
- return this.session.prepareQuery(
35787
- this.dialect.sqlToQuery(sql2),
35788
- void 0,
35789
- void 0,
35790
- generatedIds,
35791
- this.config.returning
35792
- );
35793
- }
35794
- $dynamic() {
35795
- return this;
35796
- }
35797
- };
35798
- __publicField(MySqlInsertBase, _a300, "MySqlInsert");
35799
- }
35800
- });
35801
-
35802
35978
  // ../drizzle-orm/dist/mysql-core/columns/all.js
35803
35979
  function getMySqlColumnBuilders() {
35804
35980
  return {
@@ -35879,7 +36055,7 @@ function mysqlTableWithSchema(name2, columns, extraConfig, schema4, baseName = n
35879
36055
  }
35880
36056
  return table4;
35881
36057
  }
35882
- var InlineForeignKeys3, _a301, _b223, _c9, _d4, _e4, MySqlTable, mysqlTable;
36058
+ var InlineForeignKeys3, _a299, _b222, _c9, _d4, _e4, MySqlTable, mysqlTable;
35883
36059
  var init_table4 = __esm({
35884
36060
  "../drizzle-orm/dist/mysql-core/table.js"() {
35885
36061
  "use strict";
@@ -35887,15 +36063,15 @@ var init_table4 = __esm({
35887
36063
  init_table();
35888
36064
  init_all3();
35889
36065
  InlineForeignKeys3 = Symbol.for("drizzle:MySqlInlineForeignKeys");
35890
- MySqlTable = class extends (_e4 = Table2, _d4 = entityKind, _c9 = Table2.Symbol.Columns, _b223 = InlineForeignKeys3, _a301 = Table2.Symbol.ExtraConfigBuilder, _e4) {
36066
+ MySqlTable = class extends (_e4 = Table2, _d4 = entityKind, _c9 = Table2.Symbol.Columns, _b222 = InlineForeignKeys3, _a299 = Table2.Symbol.ExtraConfigBuilder, _e4) {
35891
36067
  constructor() {
35892
36068
  super(...arguments);
35893
36069
  /** @internal */
35894
36070
  __publicField(this, _c9);
35895
36071
  /** @internal */
35896
- __publicField(this, _b223, []);
36072
+ __publicField(this, _b222, []);
35897
36073
  /** @internal */
35898
- __publicField(this, _a301);
36074
+ __publicField(this, _a299);
35899
36075
  }
35900
36076
  };
35901
36077
  __publicField(MySqlTable, _d4, "MySqlTable");
@@ -35910,20 +36086,20 @@ var init_table4 = __esm({
35910
36086
  });
35911
36087
 
35912
36088
  // ../drizzle-orm/dist/mysql-core/view-base.js
35913
- var _a302, _b224, MySqlViewBase;
36089
+ var _a300, _b223, MySqlViewBase;
35914
36090
  var init_view_base3 = __esm({
35915
36091
  "../drizzle-orm/dist/mysql-core/view-base.js"() {
35916
36092
  "use strict";
35917
36093
  init_entity();
35918
36094
  init_sql();
35919
- MySqlViewBase = class extends (_b224 = View3, _a302 = entityKind, _b224) {
36095
+ MySqlViewBase = class extends (_b223 = View3, _a300 = entityKind, _b223) {
35920
36096
  };
35921
- __publicField(MySqlViewBase, _a302, "MySqlViewBase");
36097
+ __publicField(MySqlViewBase, _a300, "MySqlViewBase");
35922
36098
  }
35923
36099
  });
35924
36100
 
35925
36101
  // ../drizzle-orm/dist/mysql-core/dialect.js
35926
- var _a303, MySqlDialect;
36102
+ var _a301, MySqlDialect;
35927
36103
  var init_dialect3 = __esm({
35928
36104
  "../drizzle-orm/dist/mysql-core/dialect.js"() {
35929
36105
  "use strict";
@@ -35942,7 +36118,7 @@ var init_dialect3 = __esm({
35942
36118
  init_common4();
35943
36119
  init_table4();
35944
36120
  init_view_base3();
35945
- _a303 = entityKind;
36121
+ _a301 = entityKind;
35946
36122
  MySqlDialect = class {
35947
36123
  constructor(config) {
35948
36124
  /** @internal */
@@ -36225,7 +36401,7 @@ var init_dialect3 = __esm({
36225
36401
  const offsetSql = offset ? sql` offset ${offset}` : void 0;
36226
36402
  return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
36227
36403
  }
36228
- buildInsertQuery({ table: table4, values, ignore, onConflict }) {
36404
+ buildInsertQuery({ table: table4, values: valuesOrSelect, ignore, onConflict, select }) {
36229
36405
  const valuesSqlList = [];
36230
36406
  const columns = table4[Table2.Symbol.Columns];
36231
36407
  const colEntries = Object.entries(columns).filter(
@@ -36233,42 +36409,53 @@ var init_dialect3 = __esm({
36233
36409
  );
36234
36410
  const insertOrder = colEntries.map(([, column4]) => sql.identifier(this.casing.getColumnCasing(column4)));
36235
36411
  const generatedIdsResponse = [];
36236
- for (const [valueIndex, value] of values.entries()) {
36237
- const generatedIds = {};
36238
- const valueList = [];
36239
- for (const [fieldName, col] of colEntries) {
36240
- const colValue = value[fieldName];
36241
- if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) {
36242
- if (col.defaultFn !== void 0) {
36243
- const defaultFnResult = col.defaultFn();
36244
- generatedIds[fieldName] = defaultFnResult;
36245
- const defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
36246
- valueList.push(defaultValue);
36247
- } else if (!col.default && col.onUpdateFn !== void 0) {
36248
- const onUpdateFnResult = col.onUpdateFn();
36249
- const newValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
36250
- valueList.push(newValue);
36412
+ if (select) {
36413
+ const select2 = valuesOrSelect;
36414
+ if (is(select2, SQL)) {
36415
+ valuesSqlList.push(select2);
36416
+ } else {
36417
+ valuesSqlList.push(select2.getSQL());
36418
+ }
36419
+ } else {
36420
+ const values = valuesOrSelect;
36421
+ valuesSqlList.push(sql.raw("values "));
36422
+ for (const [valueIndex, value] of values.entries()) {
36423
+ const generatedIds = {};
36424
+ const valueList = [];
36425
+ for (const [fieldName, col] of colEntries) {
36426
+ const colValue = value[fieldName];
36427
+ if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) {
36428
+ if (col.defaultFn !== void 0) {
36429
+ const defaultFnResult = col.defaultFn();
36430
+ generatedIds[fieldName] = defaultFnResult;
36431
+ const defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
36432
+ valueList.push(defaultValue);
36433
+ } else if (!col.default && col.onUpdateFn !== void 0) {
36434
+ const onUpdateFnResult = col.onUpdateFn();
36435
+ const newValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
36436
+ valueList.push(newValue);
36437
+ } else {
36438
+ valueList.push(sql`default`);
36439
+ }
36251
36440
  } else {
36252
- valueList.push(sql`default`);
36253
- }
36254
- } else {
36255
- if (col.defaultFn && is(colValue, Param)) {
36256
- generatedIds[fieldName] = colValue.value;
36441
+ if (col.defaultFn && is(colValue, Param)) {
36442
+ generatedIds[fieldName] = colValue.value;
36443
+ }
36444
+ valueList.push(colValue);
36257
36445
  }
36258
- valueList.push(colValue);
36259
36446
  }
36260
- }
36261
- generatedIdsResponse.push(generatedIds);
36262
- valuesSqlList.push(valueList);
36263
- if (valueIndex < values.length - 1) {
36264
- valuesSqlList.push(sql`, `);
36447
+ generatedIdsResponse.push(generatedIds);
36448
+ valuesSqlList.push(valueList);
36449
+ if (valueIndex < values.length - 1) {
36450
+ valuesSqlList.push(sql`, `);
36451
+ }
36265
36452
  }
36266
36453
  }
36267
36454
  const valuesSql = sql.join(valuesSqlList);
36268
36455
  const ignoreSql = ignore ? sql` ignore` : void 0;
36269
36456
  const onConflictSql = onConflict ? sql` on duplicate key ${onConflict}` : void 0;
36270
36457
  return {
36271
- sql: sql`insert${ignoreSql} into ${table4} ${insertOrder} values ${valuesSql}${onConflictSql}`,
36458
+ sql: sql`insert${ignoreSql} into ${table4} ${insertOrder} ${valuesSql}${onConflictSql}`,
36272
36459
  generatedIds: generatedIdsResponse
36273
36460
  };
36274
36461
  }
@@ -36728,7 +36915,7 @@ var init_dialect3 = __esm({
36728
36915
  };
36729
36916
  }
36730
36917
  };
36731
- __publicField(MySqlDialect, _a303, "MySqlDialect");
36918
+ __publicField(MySqlDialect, _a301, "MySqlDialect");
36732
36919
  }
36733
36920
  });
36734
36921
 
@@ -36750,7 +36937,7 @@ function createSetOperator3(type, isAll) {
36750
36937
  return leftSelect.addSetOperators(setOperators);
36751
36938
  };
36752
36939
  }
36753
- var _a304, MySqlSelectBuilder, _a305, _b225, MySqlSelectQueryBuilderBase, _a306, _b226, MySqlSelectBase, getMySqlSetOperators, union3, unionAll3, intersect3, intersectAll2, except3, exceptAll2;
36940
+ var _a302, MySqlSelectBuilder, _a303, _b224, MySqlSelectQueryBuilderBase, _a304, _b225, MySqlSelectBase, getMySqlSetOperators, union3, unionAll3, intersect3, intersectAll2, except3, exceptAll2;
36754
36941
  var init_select4 = __esm({
36755
36942
  "../drizzle-orm/dist/mysql-core/query-builders/select.js"() {
36756
36943
  "use strict";
@@ -36765,7 +36952,7 @@ var init_select4 = __esm({
36765
36952
  init_utils2();
36766
36953
  init_view_common();
36767
36954
  init_view_base3();
36768
- _a304 = entityKind;
36955
+ _a302 = entityKind;
36769
36956
  MySqlSelectBuilder = class {
36770
36957
  constructor(config) {
36771
36958
  __publicField(this, "fields");
@@ -36810,8 +36997,8 @@ var init_select4 = __esm({
36810
36997
  );
36811
36998
  }
36812
36999
  };
36813
- __publicField(MySqlSelectBuilder, _a304, "MySqlSelectBuilder");
36814
- MySqlSelectQueryBuilderBase = class extends (_b225 = TypedQueryBuilder, _a305 = entityKind, _b225) {
37000
+ __publicField(MySqlSelectBuilder, _a302, "MySqlSelectBuilder");
37001
+ MySqlSelectQueryBuilderBase = class extends (_b224 = TypedQueryBuilder, _a303 = entityKind, _b224) {
36815
37002
  constructor({ table: table4, fields, isPartialSelect, session, dialect: dialect4, withList, distinct }) {
36816
37003
  super();
36817
37004
  __publicField(this, "_");
@@ -37412,8 +37599,8 @@ var init_select4 = __esm({
37412
37599
  return this;
37413
37600
  }
37414
37601
  };
37415
- __publicField(MySqlSelectQueryBuilderBase, _a305, "MySqlSelectQueryBuilder");
37416
- MySqlSelectBase = class extends (_b226 = MySqlSelectQueryBuilderBase, _a306 = entityKind, _b226) {
37602
+ __publicField(MySqlSelectQueryBuilderBase, _a303, "MySqlSelectQueryBuilder");
37603
+ MySqlSelectBase = class extends (_b225 = MySqlSelectQueryBuilderBase, _a304 = entityKind, _b225) {
37417
37604
  constructor() {
37418
37605
  super(...arguments);
37419
37606
  __publicField(this, "execute", (placeholderValues) => {
@@ -37437,7 +37624,7 @@ var init_select4 = __esm({
37437
37624
  return query;
37438
37625
  }
37439
37626
  };
37440
- __publicField(MySqlSelectBase, _a306, "MySqlSelect");
37627
+ __publicField(MySqlSelectBase, _a304, "MySqlSelect");
37441
37628
  applyMixins(MySqlSelectBase, [QueryPromise]);
37442
37629
  getMySqlSetOperators = () => ({
37443
37630
  union: union3,
@@ -37457,7 +37644,7 @@ var init_select4 = __esm({
37457
37644
  });
37458
37645
 
37459
37646
  // ../drizzle-orm/dist/mysql-core/query-builders/query-builder.js
37460
- var _a307, QueryBuilder3;
37647
+ var _a305, QueryBuilder3;
37461
37648
  var init_query_builder4 = __esm({
37462
37649
  "../drizzle-orm/dist/mysql-core/query-builders/query-builder.js"() {
37463
37650
  "use strict";
@@ -37466,7 +37653,7 @@ var init_query_builder4 = __esm({
37466
37653
  init_selection_proxy();
37467
37654
  init_subquery();
37468
37655
  init_select4();
37469
- _a307 = entityKind;
37656
+ _a305 = entityKind;
37470
37657
  QueryBuilder3 = class {
37471
37658
  constructor(dialect4) {
37472
37659
  __publicField(this, "dialect");
@@ -37528,7 +37715,142 @@ var init_query_builder4 = __esm({
37528
37715
  return this.dialect;
37529
37716
  }
37530
37717
  };
37531
- __publicField(QueryBuilder3, _a307, "MySqlQueryBuilder");
37718
+ __publicField(QueryBuilder3, _a305, "MySqlQueryBuilder");
37719
+ }
37720
+ });
37721
+
37722
+ // ../drizzle-orm/dist/mysql-core/query-builders/insert.js
37723
+ var _a306, MySqlInsertBuilder, _a307, _b226, MySqlInsertBase;
37724
+ var init_insert3 = __esm({
37725
+ "../drizzle-orm/dist/mysql-core/query-builders/insert.js"() {
37726
+ "use strict";
37727
+ init_entity();
37728
+ init_query_promise();
37729
+ init_sql();
37730
+ init_table();
37731
+ init_utils2();
37732
+ init_query_builder4();
37733
+ _a306 = entityKind;
37734
+ MySqlInsertBuilder = class {
37735
+ constructor(table4, session, dialect4) {
37736
+ __publicField(this, "shouldIgnore", false);
37737
+ this.table = table4;
37738
+ this.session = session;
37739
+ this.dialect = dialect4;
37740
+ }
37741
+ ignore() {
37742
+ this.shouldIgnore = true;
37743
+ return this;
37744
+ }
37745
+ values(values) {
37746
+ values = Array.isArray(values) ? values : [values];
37747
+ if (values.length === 0) {
37748
+ throw new Error("values() must be called with at least one value");
37749
+ }
37750
+ const mappedValues = values.map((entry) => {
37751
+ const result = {};
37752
+ const cols = this.table[Table2.Symbol.Columns];
37753
+ for (const colKey of Object.keys(entry)) {
37754
+ const colValue = entry[colKey];
37755
+ result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
37756
+ }
37757
+ return result;
37758
+ });
37759
+ return new MySqlInsertBase(this.table, mappedValues, this.shouldIgnore, this.session, this.dialect);
37760
+ }
37761
+ select(selectQuery) {
37762
+ const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder3()) : selectQuery;
37763
+ if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) {
37764
+ throw new Error(
37765
+ "Insert select error: selected fields are not the same or are in a different order compared to the table definition"
37766
+ );
37767
+ }
37768
+ return new MySqlInsertBase(this.table, select, this.shouldIgnore, this.session, this.dialect, true);
37769
+ }
37770
+ };
37771
+ __publicField(MySqlInsertBuilder, _a306, "MySqlInsertBuilder");
37772
+ MySqlInsertBase = class extends (_b226 = QueryPromise, _a307 = entityKind, _b226) {
37773
+ constructor(table4, values, ignore, session, dialect4, select) {
37774
+ super();
37775
+ __publicField(this, "config");
37776
+ __publicField(this, "execute", (placeholderValues) => {
37777
+ return this.prepare().execute(placeholderValues);
37778
+ });
37779
+ __publicField(this, "createIterator", () => {
37780
+ const self2 = this;
37781
+ return async function* (placeholderValues) {
37782
+ yield* self2.prepare().iterator(placeholderValues);
37783
+ };
37784
+ });
37785
+ __publicField(this, "iterator", this.createIterator());
37786
+ this.session = session;
37787
+ this.dialect = dialect4;
37788
+ this.config = { table: table4, values, select, ignore };
37789
+ }
37790
+ /**
37791
+ * Adds an `on duplicate key update` clause to the query.
37792
+ *
37793
+ * 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.
37794
+ *
37795
+ * See docs: {@link https://orm.drizzle.team/docs/insert#on-duplicate-key-update}
37796
+ *
37797
+ * @param config The `set` clause
37798
+ *
37799
+ * @example
37800
+ * ```ts
37801
+ * await db.insert(cars)
37802
+ * .values({ id: 1, brand: 'BMW'})
37803
+ * .onDuplicateKeyUpdate({ set: { brand: 'Porsche' }});
37804
+ * ```
37805
+ *
37806
+ * 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:
37807
+ *
37808
+ * ```ts
37809
+ * import { sql } from 'drizzle-orm';
37810
+ *
37811
+ * await db.insert(cars)
37812
+ * .values({ id: 1, brand: 'BMW' })
37813
+ * .onDuplicateKeyUpdate({ set: { id: sql`id` } });
37814
+ * ```
37815
+ */
37816
+ onDuplicateKeyUpdate(config) {
37817
+ const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
37818
+ this.config.onConflict = sql`update ${setSql}`;
37819
+ return this;
37820
+ }
37821
+ $returningId() {
37822
+ const returning = [];
37823
+ for (const [key, value] of Object.entries(this.config.table[Table2.Symbol.Columns])) {
37824
+ if (value.primary) {
37825
+ returning.push({ field: value, path: [key] });
37826
+ }
37827
+ }
37828
+ this.config.returning = returning;
37829
+ return this;
37830
+ }
37831
+ /** @internal */
37832
+ getSQL() {
37833
+ return this.dialect.buildInsertQuery(this.config).sql;
37834
+ }
37835
+ toSQL() {
37836
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
37837
+ return rest;
37838
+ }
37839
+ prepare() {
37840
+ const { sql: sql2, generatedIds } = this.dialect.buildInsertQuery(this.config);
37841
+ return this.session.prepareQuery(
37842
+ this.dialect.sqlToQuery(sql2),
37843
+ void 0,
37844
+ void 0,
37845
+ generatedIds,
37846
+ this.config.returning
37847
+ );
37848
+ }
37849
+ $dynamic() {
37850
+ return this;
37851
+ }
37852
+ };
37853
+ __publicField(MySqlInsertBase, _a307, "MySqlInsert");
37532
37854
  }
37533
37855
  });
37534
37856