drizzle-kit 0.30.3 → 0.30.4-4647df7

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 (4) hide show
  1. package/api.js +1542 -1420
  2. package/api.mjs +1542 -1420
  3. package/bin.cjs +285 -2246
  4. package/package.json +2 -2
package/api.mjs CHANGED
@@ -22095,13 +22095,14 @@ var init_subquery = __esm({
22095
22095
  init_entity();
22096
22096
  _a16 = entityKind;
22097
22097
  Subquery = class {
22098
- constructor(sql2, selection, alias, isWith = false) {
22098
+ constructor(sql2, fields, alias, isWith = false, usedTables = []) {
22099
22099
  this._ = {
22100
22100
  brand: "Subquery",
22101
22101
  sql: sql2,
22102
- selectedFields: selection,
22102
+ selectedFields: fields,
22103
22103
  alias,
22104
- isWith
22104
+ isWith,
22105
+ usedTables
22105
22106
  };
22106
22107
  }
22107
22108
  // getSQL(): SQL<unknown> {
@@ -22120,7 +22121,7 @@ var version;
22120
22121
  var init_version = __esm({
22121
22122
  "../drizzle-orm/dist/version.js"() {
22122
22123
  "use strict";
22123
- version = "0.39.0";
22124
+ version = "0.39.2";
22124
22125
  }
22125
22126
  });
22126
22127
 
@@ -22343,7 +22344,14 @@ var init_sql = __esm({
22343
22344
  /** @internal */
22344
22345
  __publicField(this, "decoder", noopDecoder);
22345
22346
  __publicField(this, "shouldInlineParams", false);
22347
+ /** @internal */
22348
+ __publicField(this, "usedTables", []);
22346
22349
  this.queryChunks = queryChunks;
22350
+ for (const chunk of queryChunks) {
22351
+ if (is(chunk, Table2)) {
22352
+ this.usedTables.push(chunk[Table2.Symbol.Schema] ?? "public." + chunk[Table2.Symbol.Name]);
22353
+ }
22354
+ }
22347
22355
  }
22348
22356
  append(query) {
22349
22357
  this.queryChunks.push(...query.queryChunks);
@@ -22403,7 +22411,7 @@ var init_sql = __esm({
22403
22411
  const schemaName = chunk[Table2.Symbol.Schema];
22404
22412
  const tableName = chunk[Table2.Symbol.Name];
22405
22413
  return {
22406
- sql: schemaName === void 0 ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName),
22414
+ sql: schemaName === void 0 || chunk[IsAlias] ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName),
22407
22415
  params: []
22408
22416
  };
22409
22417
  }
@@ -22422,7 +22430,7 @@ var init_sql = __esm({
22422
22430
  const schemaName = chunk[ViewBaseConfig].schema;
22423
22431
  const viewName = chunk[ViewBaseConfig].name;
22424
22432
  return {
22425
- sql: schemaName === void 0 ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName),
22433
+ sql: schemaName === void 0 || chunk[ViewBaseConfig].isAlias ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName),
22426
22434
  params: []
22427
22435
  };
22428
22436
  }
@@ -25674,107 +25682,164 @@ var init_selection_proxy = __esm({
25674
25682
  }
25675
25683
  });
25676
25684
 
25677
- // ../drizzle-orm/dist/pg-core/query-builders/delete.js
25678
- var _a125, _b97, PgDeleteBase;
25679
- var init_delete = __esm({
25680
- "../drizzle-orm/dist/pg-core/query-builders/delete.js"() {
25685
+ // ../drizzle-orm/dist/pg-core/indexes.js
25686
+ var _a125, IndexBuilderOn, _a126, IndexBuilder, _a127, Index2;
25687
+ var init_indexes = __esm({
25688
+ "../drizzle-orm/dist/pg-core/indexes.js"() {
25681
25689
  "use strict";
25690
+ init_sql();
25682
25691
  init_entity();
25683
- init_query_promise();
25684
- init_selection_proxy();
25685
- init_table();
25686
- init_tracing();
25687
- init_utils2();
25688
- PgDeleteBase = class extends (_b97 = QueryPromise, _a125 = entityKind, _b97) {
25689
- constructor(table5, session, dialect6, withList) {
25690
- super();
25691
- __publicField(this, "config");
25692
- __publicField(this, "authToken");
25693
- __publicField(this, "execute", (placeholderValues) => {
25694
- return tracer.startActiveSpan("drizzle.operation", () => {
25695
- return this._prepare().execute(placeholderValues, this.authToken);
25696
- });
25697
- });
25698
- this.session = session;
25699
- this.dialect = dialect6;
25700
- this.config = { table: table5, withList };
25692
+ init_columns();
25693
+ _a125 = entityKind;
25694
+ IndexBuilderOn = class {
25695
+ constructor(unique, name2) {
25696
+ this.unique = unique;
25697
+ this.name = name2;
25698
+ }
25699
+ on(...columns) {
25700
+ return new IndexBuilder(
25701
+ columns.map((it) => {
25702
+ if (is(it, SQL)) {
25703
+ return it;
25704
+ }
25705
+ it = it;
25706
+ const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);
25707
+ it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig));
25708
+ return clonedIndexedColumn;
25709
+ }),
25710
+ this.unique,
25711
+ false,
25712
+ this.name
25713
+ );
25714
+ }
25715
+ onOnly(...columns) {
25716
+ return new IndexBuilder(
25717
+ columns.map((it) => {
25718
+ if (is(it, SQL)) {
25719
+ return it;
25720
+ }
25721
+ it = it;
25722
+ const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);
25723
+ it.indexConfig = it.defaultConfig;
25724
+ return clonedIndexedColumn;
25725
+ }),
25726
+ this.unique,
25727
+ true,
25728
+ this.name
25729
+ );
25701
25730
  }
25702
25731
  /**
25703
- * Adds a `where` clause to the query.
25704
- *
25705
- * Calling this method will delete only those rows that fulfill a specified condition.
25706
- *
25707
- * See docs: {@link https://orm.drizzle.team/docs/delete}
25708
- *
25709
- * @param where the `where` clause.
25710
- *
25711
- * @example
25712
- * You can use conditional operators and `sql function` to filter the rows to be deleted.
25713
- *
25714
- * ```ts
25715
- * // Delete all cars with green color
25716
- * await db.delete(cars).where(eq(cars.color, 'green'));
25717
- * // or
25718
- * await db.delete(cars).where(sql`${cars.color} = 'green'`)
25719
- * ```
25732
+ * Specify what index method to use. Choices are `btree`, `hash`, `gist`, `spgist`, `gin`, `brin`, or user-installed access methods like `bloom`. The default method is `btree.
25720
25733
  *
25721
- * You can logically combine conditional operators with `and()` and `or()` operators:
25734
+ * If you have the `pg_vector` extension installed in your database, you can use the `hnsw` and `ivfflat` options, which are predefined types.
25722
25735
  *
25723
- * ```ts
25724
- * // Delete all BMW cars with a green color
25725
- * await db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
25736
+ * **You can always specify any string you want in the method, in case Drizzle doesn't have it natively in its types**
25726
25737
  *
25727
- * // Delete all cars with the green or blue color
25728
- * await db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
25729
- * ```
25738
+ * @param method The name of the index method to be used
25739
+ * @param columns
25740
+ * @returns
25730
25741
  */
25731
- where(where) {
25732
- this.config.where = where;
25733
- return this;
25742
+ using(method, ...columns) {
25743
+ return new IndexBuilder(
25744
+ columns.map((it) => {
25745
+ if (is(it, SQL)) {
25746
+ return it;
25747
+ }
25748
+ it = it;
25749
+ const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);
25750
+ it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig));
25751
+ return clonedIndexedColumn;
25752
+ }),
25753
+ this.unique,
25754
+ true,
25755
+ this.name,
25756
+ method
25757
+ );
25734
25758
  }
25735
- returning(fields = this.config.table[Table2.Symbol.Columns]) {
25736
- this.config.returningFields = fields;
25737
- this.config.returning = orderSelectedFields(fields);
25759
+ };
25760
+ __publicField(IndexBuilderOn, _a125, "PgIndexBuilderOn");
25761
+ _a126 = entityKind;
25762
+ IndexBuilder = class {
25763
+ constructor(columns, unique, only, name2, method = "btree") {
25764
+ /** @internal */
25765
+ __publicField(this, "config");
25766
+ this.config = {
25767
+ name: name2,
25768
+ columns,
25769
+ unique,
25770
+ only,
25771
+ method
25772
+ };
25773
+ }
25774
+ concurrently() {
25775
+ this.config.concurrently = true;
25738
25776
  return this;
25739
25777
  }
25740
- /** @internal */
25741
- getSQL() {
25742
- return this.dialect.buildDeleteQuery(this.config);
25778
+ with(obj) {
25779
+ this.config.with = obj;
25780
+ return this;
25743
25781
  }
25744
- toSQL() {
25745
- const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
25746
- return rest;
25782
+ where(condition) {
25783
+ this.config.where = condition;
25784
+ return this;
25747
25785
  }
25748
25786
  /** @internal */
25749
- _prepare(name2) {
25750
- return tracer.startActiveSpan("drizzle.prepareQuery", () => {
25751
- return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name2, true);
25752
- });
25753
- }
25754
- prepare(name2) {
25755
- return this._prepare(name2);
25787
+ build(table5) {
25788
+ return new Index2(this.config, table5);
25756
25789
  }
25757
- /** @internal */
25758
- setToken(token) {
25759
- this.authToken = token;
25760
- return this;
25790
+ };
25791
+ __publicField(IndexBuilder, _a126, "PgIndexBuilder");
25792
+ _a127 = entityKind;
25793
+ Index2 = class {
25794
+ constructor(config, table5) {
25795
+ __publicField(this, "config");
25796
+ this.config = { ...config, table: table5 };
25761
25797
  }
25762
- /** @internal */
25763
- getSelectedFields() {
25764
- return this.config.returningFields ? new Proxy(
25765
- this.config.returningFields,
25766
- new SelectionProxyHandler({
25767
- alias: getTableName(this.config.table),
25768
- sqlAliasedBehavior: "alias",
25769
- sqlBehavior: "error"
25770
- })
25771
- ) : void 0;
25798
+ };
25799
+ __publicField(Index2, _a127, "PgIndex");
25800
+ }
25801
+ });
25802
+
25803
+ // ../drizzle-orm/dist/pg-core/policies.js
25804
+ var _a128, PgPolicy;
25805
+ var init_policies = __esm({
25806
+ "../drizzle-orm/dist/pg-core/policies.js"() {
25807
+ "use strict";
25808
+ init_entity();
25809
+ _a128 = entityKind;
25810
+ PgPolicy = class {
25811
+ constructor(name2, config) {
25812
+ __publicField(this, "as");
25813
+ __publicField(this, "for");
25814
+ __publicField(this, "to");
25815
+ __publicField(this, "using");
25816
+ __publicField(this, "withCheck");
25817
+ /** @internal */
25818
+ __publicField(this, "_linkedTable");
25819
+ this.name = name2;
25820
+ if (config) {
25821
+ this.as = config.as;
25822
+ this.for = config.for;
25823
+ this.to = config.to;
25824
+ this.using = config.using;
25825
+ this.withCheck = config.withCheck;
25826
+ }
25772
25827
  }
25773
- $dynamic() {
25828
+ link(table5) {
25829
+ this._linkedTable = table5;
25774
25830
  return this;
25775
25831
  }
25776
25832
  };
25777
- __publicField(PgDeleteBase, _a125, "PgDelete");
25833
+ __publicField(PgPolicy, _a128, "PgPolicy");
25834
+ }
25835
+ });
25836
+
25837
+ // ../drizzle-orm/dist/pg-core/view-common.js
25838
+ var PgViewConfig;
25839
+ var init_view_common2 = __esm({
25840
+ "../drizzle-orm/dist/pg-core/view-common.js"() {
25841
+ "use strict";
25842
+ PgViewConfig = Symbol.for("drizzle:PgViewConfig");
25778
25843
  }
25779
25844
  });
25780
25845
 
@@ -25793,13 +25858,13 @@ function toCamelCase(input) {
25793
25858
  function noopCase(input) {
25794
25859
  return input;
25795
25860
  }
25796
- var _a126, CasingCache;
25861
+ var _a129, CasingCache;
25797
25862
  var init_casing = __esm({
25798
25863
  "../drizzle-orm/dist/casing.js"() {
25799
25864
  "use strict";
25800
25865
  init_entity();
25801
25866
  init_table();
25802
- _a126 = entityKind;
25867
+ _a129 = entityKind;
25803
25868
  CasingCache = class {
25804
25869
  constructor(casing2) {
25805
25870
  /** @internal */
@@ -25836,25 +25901,25 @@ var init_casing = __esm({
25836
25901
  this.cachedTables = {};
25837
25902
  }
25838
25903
  };
25839
- __publicField(CasingCache, _a126, "CasingCache");
25904
+ __publicField(CasingCache, _a129, "CasingCache");
25840
25905
  }
25841
25906
  });
25842
25907
 
25843
25908
  // ../drizzle-orm/dist/pg-core/view-base.js
25844
- var _a127, _b98, PgViewBase;
25909
+ var _a130, _b97, PgViewBase;
25845
25910
  var init_view_base = __esm({
25846
25911
  "../drizzle-orm/dist/pg-core/view-base.js"() {
25847
25912
  "use strict";
25848
25913
  init_entity();
25849
25914
  init_sql();
25850
- PgViewBase = class extends (_b98 = View3, _a127 = entityKind, _b98) {
25915
+ PgViewBase = class extends (_b97 = View3, _a130 = entityKind, _b97) {
25851
25916
  };
25852
- __publicField(PgViewBase, _a127, "PgViewBase");
25917
+ __publicField(PgViewBase, _a130, "PgViewBase");
25853
25918
  }
25854
25919
  });
25855
25920
 
25856
25921
  // ../drizzle-orm/dist/pg-core/dialect.js
25857
- var _a128, PgDialect;
25922
+ var _a131, PgDialect;
25858
25923
  var init_dialect = __esm({
25859
25924
  "../drizzle-orm/dist/pg-core/dialect.js"() {
25860
25925
  "use strict";
@@ -25873,7 +25938,7 @@ var init_dialect = __esm({
25873
25938
  init_utils2();
25874
25939
  init_view_common();
25875
25940
  init_view_base();
25876
- _a128 = entityKind;
25941
+ _a131 = entityKind;
25877
25942
  PgDialect = class {
25878
25943
  constructor(config) {
25879
25944
  /** @internal */
@@ -26965,24 +27030,24 @@ var init_dialect = __esm({
26965
27030
  };
26966
27031
  }
26967
27032
  };
26968
- __publicField(PgDialect, _a128, "PgDialect");
27033
+ __publicField(PgDialect, _a131, "PgDialect");
26969
27034
  }
26970
27035
  });
26971
27036
 
26972
27037
  // ../drizzle-orm/dist/query-builders/query-builder.js
26973
- var _a129, TypedQueryBuilder;
27038
+ var _a132, TypedQueryBuilder;
26974
27039
  var init_query_builder = __esm({
26975
27040
  "../drizzle-orm/dist/query-builders/query-builder.js"() {
26976
27041
  "use strict";
26977
27042
  init_entity();
26978
- _a129 = entityKind;
27043
+ _a132 = entityKind;
26979
27044
  TypedQueryBuilder = class {
26980
27045
  /** @internal */
26981
27046
  getSelectedFields() {
26982
27047
  return this._.selectedFields;
26983
27048
  }
26984
27049
  };
26985
- __publicField(TypedQueryBuilder, _a129, "TypedQueryBuilder");
27050
+ __publicField(TypedQueryBuilder, _a132, "TypedQueryBuilder");
26986
27051
  }
26987
27052
  });
26988
27053
 
@@ -27004,7 +27069,7 @@ function createSetOperator(type, isAll) {
27004
27069
  return leftSelect.addSetOperators(setOperators);
27005
27070
  };
27006
27071
  }
27007
- var _a130, PgSelectBuilder, _a131, _b99, PgSelectQueryBuilderBase, _a132, _b100, PgSelectBase, getPgSetOperators, union, unionAll, intersect, intersectAll, except, exceptAll;
27072
+ var _a133, PgSelectBuilder, _a134, _b98, PgSelectQueryBuilderBase, _a135, _b99, PgSelectBase, getPgSetOperators, union, unionAll, intersect, intersectAll, except, exceptAll;
27008
27073
  var init_select2 = __esm({
27009
27074
  "../drizzle-orm/dist/pg-core/query-builders/select.js"() {
27010
27075
  "use strict";
@@ -27020,7 +27085,8 @@ var init_select2 = __esm({
27020
27085
  init_utils2();
27021
27086
  init_utils2();
27022
27087
  init_view_common();
27023
- _a130 = entityKind;
27088
+ init_utils4();
27089
+ _a133 = entityKind;
27024
27090
  PgSelectBuilder = class {
27025
27091
  constructor(config) {
27026
27092
  __publicField(this, "fields");
@@ -27076,8 +27142,8 @@ var init_select2 = __esm({
27076
27142
  }).setToken(this.authToken);
27077
27143
  }
27078
27144
  };
27079
- __publicField(PgSelectBuilder, _a130, "PgSelectBuilder");
27080
- PgSelectQueryBuilderBase = class extends (_b99 = TypedQueryBuilder, _a131 = entityKind, _b99) {
27145
+ __publicField(PgSelectBuilder, _a133, "PgSelectBuilder");
27146
+ PgSelectQueryBuilderBase = class extends (_b98 = TypedQueryBuilder, _a134 = entityKind, _b98) {
27081
27147
  constructor({ table: table5, fields, isPartialSelect, session, dialect: dialect6, withList, distinct }) {
27082
27148
  super();
27083
27149
  __publicField(this, "_");
@@ -27087,6 +27153,8 @@ var init_select2 = __esm({
27087
27153
  __publicField(this, "isPartialSelect");
27088
27154
  __publicField(this, "session");
27089
27155
  __publicField(this, "dialect");
27156
+ __publicField(this, "cacheConfig");
27157
+ __publicField(this, "usedTables", /* @__PURE__ */ new Set());
27090
27158
  /**
27091
27159
  * Executes a `left join` operation by adding another table to the current query.
27092
27160
  *
@@ -27396,15 +27464,24 @@ var init_select2 = __esm({
27396
27464
  this.session = session;
27397
27465
  this.dialect = dialect6;
27398
27466
  this._ = {
27399
- selectedFields: fields
27467
+ selectedFields: fields,
27468
+ config: this.config
27400
27469
  };
27401
27470
  this.tableName = getTableLikeName(table5);
27402
27471
  this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
27472
+ for (const item of extractUsedTable(table5))
27473
+ this.usedTables.add(item);
27474
+ }
27475
+ /** @internal */
27476
+ getUsedTables() {
27477
+ return [...this.usedTables];
27403
27478
  }
27404
27479
  createJoin(joinType) {
27405
27480
  return (table5, on) => {
27406
27481
  const baseTableName = this.tableName;
27407
27482
  const tableName = getTableLikeName(table5);
27483
+ for (const item of extractUsedTable(table5))
27484
+ this.usedTables.add(item);
27408
27485
  if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) {
27409
27486
  throw new Error(`Alias "${tableName}" is already used in this query`);
27410
27487
  }
@@ -27661,8 +27738,14 @@ var init_select2 = __esm({
27661
27738
  return rest;
27662
27739
  }
27663
27740
  as(alias) {
27741
+ const usedTables = [];
27742
+ usedTables.push(...extractUsedTable(this.config.table));
27743
+ if (this.config.joins) {
27744
+ for (const it of this.config.joins)
27745
+ usedTables.push(...extractUsedTable(it.table));
27746
+ }
27664
27747
  return new Proxy(
27665
- new Subquery(this.getSQL(), this.config.fields, alias),
27748
+ new Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]),
27666
27749
  new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
27667
27750
  );
27668
27751
  }
@@ -27676,9 +27759,13 @@ var init_select2 = __esm({
27676
27759
  $dynamic() {
27677
27760
  return this;
27678
27761
  }
27762
+ $withCache(config) {
27763
+ this.cacheConfig = config === void 0 ? { config: {}, enable: true, autoInvalidate: true } : config === false ? { enable: false } : { enable: true, autoInvalidate: true, ...config };
27764
+ return this;
27765
+ }
27679
27766
  };
27680
- __publicField(PgSelectQueryBuilderBase, _a131, "PgSelectQueryBuilder");
27681
- PgSelectBase = class extends (_b100 = PgSelectQueryBuilderBase, _a132 = entityKind, _b100) {
27767
+ __publicField(PgSelectQueryBuilderBase, _a134, "PgSelectQueryBuilder");
27768
+ PgSelectBase = class extends (_b99 = PgSelectQueryBuilderBase, _a135 = entityKind, _b99) {
27682
27769
  constructor() {
27683
27770
  super(...arguments);
27684
27771
  __publicField(this, "authToken");
@@ -27690,13 +27777,17 @@ var init_select2 = __esm({
27690
27777
  }
27691
27778
  /** @internal */
27692
27779
  _prepare(name2) {
27693
- const { session, config, dialect: dialect6, joinsNotNullableMap, authToken } = this;
27780
+ const { session, config, dialect: dialect6, joinsNotNullableMap, authToken, cacheConfig, usedTables } = this;
27694
27781
  if (!session) {
27695
27782
  throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
27696
27783
  }
27784
+ const { fields } = config;
27697
27785
  return tracer.startActiveSpan("drizzle.prepareQuery", () => {
27698
- const fieldsList = orderSelectedFields(config.fields);
27699
- const query = session.prepareQuery(dialect6.sqlToQuery(this.getSQL()), fieldsList, name2, true);
27786
+ const fieldsList = orderSelectedFields(fields);
27787
+ const query = session.prepareQuery(dialect6.sqlToQuery(this.getSQL()), fieldsList, name2, true, void 0, {
27788
+ type: "select",
27789
+ tables: [...usedTables]
27790
+ }, cacheConfig);
27700
27791
  query.joinsNotNullableMap = joinsNotNullableMap;
27701
27792
  return query.setToken(authToken);
27702
27793
  });
@@ -27717,7 +27808,7 @@ var init_select2 = __esm({
27717
27808
  return this;
27718
27809
  }
27719
27810
  };
27720
- __publicField(PgSelectBase, _a132, "PgSelect");
27811
+ __publicField(PgSelectBase, _a135, "PgSelect");
27721
27812
  applyMixins(PgSelectBase, [QueryPromise]);
27722
27813
  getPgSetOperators = () => ({
27723
27814
  union,
@@ -27737,7 +27828,7 @@ var init_select2 = __esm({
27737
27828
  });
27738
27829
 
27739
27830
  // ../drizzle-orm/dist/pg-core/query-builders/query-builder.js
27740
- var _a133, QueryBuilder;
27831
+ var _a136, QueryBuilder;
27741
27832
  var init_query_builder2 = __esm({
27742
27833
  "../drizzle-orm/dist/pg-core/query-builders/query-builder.js"() {
27743
27834
  "use strict";
@@ -27746,7 +27837,7 @@ var init_query_builder2 = __esm({
27746
27837
  init_selection_proxy();
27747
27838
  init_subquery();
27748
27839
  init_select2();
27749
- _a133 = entityKind;
27840
+ _a136 = entityKind;
27750
27841
  QueryBuilder = class {
27751
27842
  constructor(dialect6) {
27752
27843
  __publicField(this, "dialect");
@@ -27831,226 +27922,374 @@ var init_query_builder2 = __esm({
27831
27922
  return this.dialect;
27832
27923
  }
27833
27924
  };
27834
- __publicField(QueryBuilder, _a133, "PgQueryBuilder");
27925
+ __publicField(QueryBuilder, _a136, "PgQueryBuilder");
27835
27926
  }
27836
27927
  });
27837
27928
 
27838
- // ../drizzle-orm/dist/pg-core/query-builders/insert.js
27839
- var _a134, PgInsertBuilder, _a135, _b101, PgInsertBase;
27840
- var init_insert = __esm({
27841
- "../drizzle-orm/dist/pg-core/query-builders/insert.js"() {
27929
+ // ../drizzle-orm/dist/pg-core/view.js
27930
+ function pgViewWithSchema(name2, selection, schema5) {
27931
+ if (selection) {
27932
+ return new ManualViewBuilder(name2, selection, schema5);
27933
+ }
27934
+ return new ViewBuilder(name2, schema5);
27935
+ }
27936
+ function pgMaterializedViewWithSchema(name2, selection, schema5) {
27937
+ if (selection) {
27938
+ return new ManualMaterializedViewBuilder(name2, selection, schema5);
27939
+ }
27940
+ return new MaterializedViewBuilder(name2, schema5);
27941
+ }
27942
+ function isPgView(obj) {
27943
+ return is(obj, PgView2);
27944
+ }
27945
+ function isPgMaterializedView(obj) {
27946
+ return is(obj, PgMaterializedView);
27947
+ }
27948
+ var _a137, DefaultViewBuilderCore, _a138, _b100, ViewBuilder, _a139, _b101, ManualViewBuilder, _a140, MaterializedViewBuilderCore, _a141, _b102, MaterializedViewBuilder, _a142, _b103, ManualMaterializedViewBuilder, _a143, _b104, _c4, PgView2, PgMaterializedViewConfig, _a144, _b105, _c5, PgMaterializedView;
27949
+ var init_view = __esm({
27950
+ "../drizzle-orm/dist/pg-core/view.js"() {
27842
27951
  "use strict";
27843
27952
  init_entity();
27844
- init_query_promise();
27845
27953
  init_selection_proxy();
27846
- init_sql();
27847
- init_table();
27848
- init_tracing();
27849
27954
  init_utils2();
27850
27955
  init_query_builder2();
27851
- _a134 = entityKind;
27852
- PgInsertBuilder = class {
27853
- constructor(table5, session, dialect6, withList, overridingSystemValue_) {
27854
- __publicField(this, "authToken");
27855
- this.table = table5;
27856
- this.session = session;
27857
- this.dialect = dialect6;
27858
- this.withList = withList;
27859
- this.overridingSystemValue_ = overridingSystemValue_;
27860
- }
27861
- /** @internal */
27862
- setToken(token) {
27863
- this.authToken = token;
27864
- return this;
27956
+ init_table2();
27957
+ init_view_base();
27958
+ init_view_common2();
27959
+ _a137 = entityKind;
27960
+ DefaultViewBuilderCore = class {
27961
+ constructor(name2, schema5) {
27962
+ __publicField(this, "config", {});
27963
+ this.name = name2;
27964
+ this.schema = schema5;
27865
27965
  }
27866
- overridingSystemValue() {
27867
- this.overridingSystemValue_ = true;
27966
+ with(config) {
27967
+ this.config.with = config;
27868
27968
  return this;
27869
27969
  }
27870
- values(values) {
27871
- values = Array.isArray(values) ? values : [values];
27872
- if (values.length === 0) {
27873
- throw new Error("values() must be called with at least one value");
27970
+ };
27971
+ __publicField(DefaultViewBuilderCore, _a137, "PgDefaultViewBuilderCore");
27972
+ ViewBuilder = class extends (_b100 = DefaultViewBuilderCore, _a138 = entityKind, _b100) {
27973
+ as(qb) {
27974
+ if (typeof qb === "function") {
27975
+ qb = qb(new QueryBuilder());
27874
27976
  }
27875
- const mappedValues = values.map((entry) => {
27876
- const result = {};
27877
- const cols = this.table[Table2.Symbol.Columns];
27878
- for (const colKey of Object.keys(entry)) {
27879
- const colValue = entry[colKey];
27880
- result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
27881
- }
27882
- return result;
27977
+ const selectionProxy = new SelectionProxyHandler({
27978
+ alias: this.name,
27979
+ sqlBehavior: "error",
27980
+ sqlAliasedBehavior: "alias",
27981
+ replaceOriginalName: true
27883
27982
  });
27884
- return new PgInsertBase(
27885
- this.table,
27886
- mappedValues,
27887
- this.session,
27888
- this.dialect,
27889
- this.withList,
27890
- false,
27891
- this.overridingSystemValue_
27892
- ).setToken(this.authToken);
27893
- }
27894
- select(selectQuery) {
27895
- const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder()) : selectQuery;
27896
- if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) {
27897
- throw new Error(
27898
- "Insert select error: selected fields are not the same or are in a different order compared to the table definition"
27899
- );
27900
- }
27901
- return new PgInsertBase(this.table, select, this.session, this.dialect, this.withList, true);
27983
+ const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);
27984
+ return new Proxy(
27985
+ new PgView2({
27986
+ pgConfig: this.config,
27987
+ config: {
27988
+ name: this.name,
27989
+ schema: this.schema,
27990
+ selectedFields: aliasedSelection,
27991
+ query: qb.getSQL().inlineParams()
27992
+ }
27993
+ }),
27994
+ selectionProxy
27995
+ );
27902
27996
  }
27903
27997
  };
27904
- __publicField(PgInsertBuilder, _a134, "PgInsertBuilder");
27905
- PgInsertBase = class extends (_b101 = QueryPromise, _a135 = entityKind, _b101) {
27906
- constructor(table5, values, session, dialect6, withList, select, overridingSystemValue_) {
27907
- super();
27908
- __publicField(this, "config");
27909
- __publicField(this, "authToken");
27910
- __publicField(this, "execute", (placeholderValues) => {
27911
- return tracer.startActiveSpan("drizzle.operation", () => {
27912
- return this._prepare().execute(placeholderValues, this.authToken);
27913
- });
27914
- });
27915
- this.session = session;
27916
- this.dialect = dialect6;
27917
- this.config = { table: table5, values, withList, select, overridingSystemValue_ };
27918
- }
27919
- returning(fields = this.config.table[Table2.Symbol.Columns]) {
27920
- this.config.returningFields = fields;
27921
- this.config.returning = orderSelectedFields(fields);
27922
- return this;
27923
- }
27924
- /**
27925
- * Adds an `on conflict do nothing` clause to the query.
27926
- *
27927
- * Calling this method simply avoids inserting a row as its alternative action.
27928
- *
27929
- * See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}
27930
- *
27931
- * @param config The `target` and `where` clauses.
27932
- *
27933
- * @example
27934
- * ```ts
27935
- * // Insert one row and cancel the insert if there's a conflict
27936
- * await db.insert(cars)
27937
- * .values({ id: 1, brand: 'BMW' })
27938
- * .onConflictDoNothing();
27939
- *
27940
- * // Explicitly specify conflict target
27941
- * await db.insert(cars)
27942
- * .values({ id: 1, brand: 'BMW' })
27943
- * .onConflictDoNothing({ target: cars.id });
27944
- * ```
27945
- */
27946
- onConflictDoNothing(config = {}) {
27947
- if (config.target === void 0) {
27948
- this.config.onConflict = sql`do nothing`;
27949
- } else {
27950
- let targetColumn = "";
27951
- 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));
27952
- const whereSql = config.where ? sql` where ${config.where}` : void 0;
27953
- this.config.onConflict = sql`(${sql.raw(targetColumn)})${whereSql} do nothing`;
27954
- }
27955
- return this;
27956
- }
27957
- /**
27958
- * Adds an `on conflict do update` clause to the query.
27959
- *
27960
- * Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.
27961
- *
27962
- * See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}
27963
- *
27964
- * @param config The `target`, `set` and `where` clauses.
27965
- *
27966
- * @example
27967
- * ```ts
27968
- * // Update the row if there's a conflict
27969
- * await db.insert(cars)
27970
- * .values({ id: 1, brand: 'BMW' })
27971
- * .onConflictDoUpdate({
27972
- * target: cars.id,
27973
- * set: { brand: 'Porsche' }
27974
- * });
27975
- *
27976
- * // Upsert with 'where' clause
27977
- * await db.insert(cars)
27978
- * .values({ id: 1, brand: 'BMW' })
27979
- * .onConflictDoUpdate({
27980
- * target: cars.id,
27981
- * set: { brand: 'newBMW' },
27982
- * targetWhere: sql`${cars.createdAt} > '2023-01-01'::date`,
27983
- * });
27984
- * ```
27985
- */
27986
- onConflictDoUpdate(config) {
27987
- if (config.where && (config.targetWhere || config.setWhere)) {
27988
- throw new Error(
27989
- 'You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.'
27990
- );
27991
- }
27992
- const whereSql = config.where ? sql` where ${config.where}` : void 0;
27993
- const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : void 0;
27994
- const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : void 0;
27995
- const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
27996
- let targetColumn = "";
27997
- 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));
27998
- this.config.onConflict = sql`(${sql.raw(targetColumn)})${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`;
27999
- return this;
27998
+ __publicField(ViewBuilder, _a138, "PgViewBuilder");
27999
+ ManualViewBuilder = class extends (_b101 = DefaultViewBuilderCore, _a139 = entityKind, _b101) {
28000
+ constructor(name2, columns, schema5) {
28001
+ super(name2, schema5);
28002
+ __publicField(this, "columns");
28003
+ this.columns = getTableColumns(pgTable(name2, columns));
28000
28004
  }
28001
- /** @internal */
28002
- getSQL() {
28003
- return this.dialect.buildInsertQuery(this.config);
28005
+ existing() {
28006
+ return new Proxy(
28007
+ new PgView2({
28008
+ pgConfig: void 0,
28009
+ config: {
28010
+ name: this.name,
28011
+ schema: this.schema,
28012
+ selectedFields: this.columns,
28013
+ query: void 0
28014
+ }
28015
+ }),
28016
+ new SelectionProxyHandler({
28017
+ alias: this.name,
28018
+ sqlBehavior: "error",
28019
+ sqlAliasedBehavior: "alias",
28020
+ replaceOriginalName: true
28021
+ })
28022
+ );
28004
28023
  }
28005
- toSQL() {
28006
- const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
28007
- return rest;
28024
+ as(query) {
28025
+ return new Proxy(
28026
+ new PgView2({
28027
+ pgConfig: this.config,
28028
+ config: {
28029
+ name: this.name,
28030
+ schema: this.schema,
28031
+ selectedFields: this.columns,
28032
+ query: query.inlineParams()
28033
+ }
28034
+ }),
28035
+ new SelectionProxyHandler({
28036
+ alias: this.name,
28037
+ sqlBehavior: "error",
28038
+ sqlAliasedBehavior: "alias",
28039
+ replaceOriginalName: true
28040
+ })
28041
+ );
28008
28042
  }
28009
- /** @internal */
28010
- _prepare(name2) {
28011
- return tracer.startActiveSpan("drizzle.prepareQuery", () => {
28012
- return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name2, true);
28013
- });
28043
+ };
28044
+ __publicField(ManualViewBuilder, _a139, "PgManualViewBuilder");
28045
+ _a140 = entityKind;
28046
+ MaterializedViewBuilderCore = class {
28047
+ constructor(name2, schema5) {
28048
+ __publicField(this, "config", {});
28049
+ this.name = name2;
28050
+ this.schema = schema5;
28014
28051
  }
28015
- prepare(name2) {
28016
- return this._prepare(name2);
28052
+ using(using) {
28053
+ this.config.using = using;
28054
+ return this;
28017
28055
  }
28018
- /** @internal */
28019
- setToken(token) {
28020
- this.authToken = token;
28056
+ with(config) {
28057
+ this.config.with = config;
28021
28058
  return this;
28022
28059
  }
28023
- /** @internal */
28024
- getSelectedFields() {
28025
- return this.config.returningFields ? new Proxy(
28026
- this.config.returningFields,
28027
- new SelectionProxyHandler({
28028
- alias: getTableName(this.config.table),
28029
- sqlAliasedBehavior: "alias",
28030
- sqlBehavior: "error"
28031
- })
28032
- ) : void 0;
28060
+ tablespace(tablespace) {
28061
+ this.config.tablespace = tablespace;
28062
+ return this;
28033
28063
  }
28034
- $dynamic() {
28064
+ withNoData() {
28065
+ this.config.withNoData = true;
28035
28066
  return this;
28036
28067
  }
28037
28068
  };
28038
- __publicField(PgInsertBase, _a135, "PgInsert");
28039
- }
28040
- });
28041
-
28042
- // ../drizzle-orm/dist/pg-core/query-builders/refresh-materialized-view.js
28043
- var _a136, _b102, PgRefreshMaterializedView;
28044
- var init_refresh_materialized_view = __esm({
28045
- "../drizzle-orm/dist/pg-core/query-builders/refresh-materialized-view.js"() {
28069
+ __publicField(MaterializedViewBuilderCore, _a140, "PgMaterializedViewBuilderCore");
28070
+ MaterializedViewBuilder = class extends (_b102 = MaterializedViewBuilderCore, _a141 = entityKind, _b102) {
28071
+ as(qb) {
28072
+ if (typeof qb === "function") {
28073
+ qb = qb(new QueryBuilder());
28074
+ }
28075
+ const selectionProxy = new SelectionProxyHandler({
28076
+ alias: this.name,
28077
+ sqlBehavior: "error",
28078
+ sqlAliasedBehavior: "alias",
28079
+ replaceOriginalName: true
28080
+ });
28081
+ const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);
28082
+ return new Proxy(
28083
+ new PgMaterializedView({
28084
+ pgConfig: {
28085
+ with: this.config.with,
28086
+ using: this.config.using,
28087
+ tablespace: this.config.tablespace,
28088
+ withNoData: this.config.withNoData
28089
+ },
28090
+ config: {
28091
+ name: this.name,
28092
+ schema: this.schema,
28093
+ selectedFields: aliasedSelection,
28094
+ query: qb.getSQL().inlineParams()
28095
+ }
28096
+ }),
28097
+ selectionProxy
28098
+ );
28099
+ }
28100
+ };
28101
+ __publicField(MaterializedViewBuilder, _a141, "PgMaterializedViewBuilder");
28102
+ ManualMaterializedViewBuilder = class extends (_b103 = MaterializedViewBuilderCore, _a142 = entityKind, _b103) {
28103
+ constructor(name2, columns, schema5) {
28104
+ super(name2, schema5);
28105
+ __publicField(this, "columns");
28106
+ this.columns = getTableColumns(pgTable(name2, columns));
28107
+ }
28108
+ existing() {
28109
+ return new Proxy(
28110
+ new PgMaterializedView({
28111
+ pgConfig: {
28112
+ tablespace: this.config.tablespace,
28113
+ using: this.config.using,
28114
+ with: this.config.with,
28115
+ withNoData: this.config.withNoData
28116
+ },
28117
+ config: {
28118
+ name: this.name,
28119
+ schema: this.schema,
28120
+ selectedFields: this.columns,
28121
+ query: void 0
28122
+ }
28123
+ }),
28124
+ new SelectionProxyHandler({
28125
+ alias: this.name,
28126
+ sqlBehavior: "error",
28127
+ sqlAliasedBehavior: "alias",
28128
+ replaceOriginalName: true
28129
+ })
28130
+ );
28131
+ }
28132
+ as(query) {
28133
+ return new Proxy(
28134
+ new PgMaterializedView({
28135
+ pgConfig: {
28136
+ tablespace: this.config.tablespace,
28137
+ using: this.config.using,
28138
+ with: this.config.with,
28139
+ withNoData: this.config.withNoData
28140
+ },
28141
+ config: {
28142
+ name: this.name,
28143
+ schema: this.schema,
28144
+ selectedFields: this.columns,
28145
+ query: query.inlineParams()
28146
+ }
28147
+ }),
28148
+ new SelectionProxyHandler({
28149
+ alias: this.name,
28150
+ sqlBehavior: "error",
28151
+ sqlAliasedBehavior: "alias",
28152
+ replaceOriginalName: true
28153
+ })
28154
+ );
28155
+ }
28156
+ };
28157
+ __publicField(ManualMaterializedViewBuilder, _a142, "PgManualMaterializedViewBuilder");
28158
+ PgView2 = class extends (_c4 = PgViewBase, _b104 = entityKind, _a143 = PgViewConfig, _c4) {
28159
+ constructor({ pgConfig, config }) {
28160
+ super(config);
28161
+ __publicField(this, _a143);
28162
+ if (pgConfig) {
28163
+ this[PgViewConfig] = {
28164
+ with: pgConfig.with
28165
+ };
28166
+ }
28167
+ }
28168
+ };
28169
+ __publicField(PgView2, _b104, "PgView");
28170
+ PgMaterializedViewConfig = Symbol.for("drizzle:PgMaterializedViewConfig");
28171
+ PgMaterializedView = class extends (_c5 = PgViewBase, _b105 = entityKind, _a144 = PgMaterializedViewConfig, _c5) {
28172
+ constructor({ pgConfig, config }) {
28173
+ super(config);
28174
+ __publicField(this, _a144);
28175
+ this[PgMaterializedViewConfig] = {
28176
+ with: pgConfig?.with,
28177
+ using: pgConfig?.using,
28178
+ tablespace: pgConfig?.tablespace,
28179
+ withNoData: pgConfig?.withNoData
28180
+ };
28181
+ }
28182
+ };
28183
+ __publicField(PgMaterializedView, _b105, "PgMaterializedView");
28184
+ }
28185
+ });
28186
+
28187
+ // ../drizzle-orm/dist/pg-core/utils.js
28188
+ function getTableConfig(table5) {
28189
+ const columns = Object.values(table5[Table2.Symbol.Columns]);
28190
+ const indexes = [];
28191
+ const checks = [];
28192
+ const primaryKeys = [];
28193
+ const foreignKeys = Object.values(table5[PgTable.Symbol.InlineForeignKeys]);
28194
+ const uniqueConstraints = [];
28195
+ const name2 = table5[Table2.Symbol.Name];
28196
+ const schema5 = table5[Table2.Symbol.Schema];
28197
+ const policies = [];
28198
+ const enableRLS = table5[PgTable.Symbol.EnableRLS];
28199
+ const extraConfigBuilder = table5[PgTable.Symbol.ExtraConfigBuilder];
28200
+ if (extraConfigBuilder !== void 0) {
28201
+ const extraConfig = extraConfigBuilder(table5[Table2.Symbol.ExtraConfigColumns]);
28202
+ const extraValues = Array.isArray(extraConfig) ? extraConfig.flat(1) : Object.values(extraConfig);
28203
+ for (const builder of extraValues) {
28204
+ if (is(builder, IndexBuilder)) {
28205
+ indexes.push(builder.build(table5));
28206
+ } else if (is(builder, CheckBuilder)) {
28207
+ checks.push(builder.build(table5));
28208
+ } else if (is(builder, UniqueConstraintBuilder)) {
28209
+ uniqueConstraints.push(builder.build(table5));
28210
+ } else if (is(builder, PrimaryKeyBuilder)) {
28211
+ primaryKeys.push(builder.build(table5));
28212
+ } else if (is(builder, ForeignKeyBuilder)) {
28213
+ foreignKeys.push(builder.build(table5));
28214
+ } else if (is(builder, PgPolicy)) {
28215
+ policies.push(builder);
28216
+ }
28217
+ }
28218
+ }
28219
+ return {
28220
+ columns,
28221
+ indexes,
28222
+ foreignKeys,
28223
+ checks,
28224
+ primaryKeys,
28225
+ uniqueConstraints,
28226
+ name: name2,
28227
+ schema: schema5,
28228
+ policies,
28229
+ enableRLS
28230
+ };
28231
+ }
28232
+ function extractUsedTable(table5) {
28233
+ if (is(table5, PgTable)) {
28234
+ return [`${table5[Schema] ?? "public"}.${table5[Table2.Symbol.BaseName]}`];
28235
+ }
28236
+ if (is(table5, Subquery)) {
28237
+ return table5._.usedTables ?? [];
28238
+ }
28239
+ if (is(table5, SQL)) {
28240
+ return table5.usedTables ?? [];
28241
+ }
28242
+ return [];
28243
+ }
28244
+ function getViewConfig(view4) {
28245
+ return {
28246
+ ...view4[ViewBaseConfig],
28247
+ ...view4[PgViewConfig]
28248
+ };
28249
+ }
28250
+ function getMaterializedViewConfig(view4) {
28251
+ return {
28252
+ ...view4[ViewBaseConfig],
28253
+ ...view4[PgMaterializedViewConfig]
28254
+ };
28255
+ }
28256
+ var init_utils4 = __esm({
28257
+ "../drizzle-orm/dist/pg-core/utils.js"() {
28258
+ "use strict";
28259
+ init_entity();
28260
+ init_table2();
28261
+ init_sql();
28262
+ init_subquery();
28263
+ init_table();
28264
+ init_view_common();
28265
+ init_checks();
28266
+ init_foreign_keys();
28267
+ init_indexes();
28268
+ init_policies();
28269
+ init_primary_keys();
28270
+ init_unique_constraint();
28271
+ init_view_common2();
28272
+ init_view();
28273
+ }
28274
+ });
28275
+
28276
+ // ../drizzle-orm/dist/pg-core/query-builders/delete.js
28277
+ var _a145, _b106, PgDeleteBase;
28278
+ var init_delete = __esm({
28279
+ "../drizzle-orm/dist/pg-core/query-builders/delete.js"() {
28046
28280
  "use strict";
28047
28281
  init_entity();
28048
28282
  init_query_promise();
28283
+ init_selection_proxy();
28284
+ init_table();
28049
28285
  init_tracing();
28050
- PgRefreshMaterializedView = class extends (_b102 = QueryPromise, _a136 = entityKind, _b102) {
28051
- constructor(view4, session, dialect6) {
28286
+ init_utils2();
28287
+ init_utils4();
28288
+ PgDeleteBase = class extends (_b106 = QueryPromise, _a145 = entityKind, _b106) {
28289
+ constructor(table5, session, dialect6, withList) {
28052
28290
  super();
28053
28291
  __publicField(this, "config");
28292
+ __publicField(this, "cacheConfig");
28054
28293
  __publicField(this, "authToken");
28055
28294
  __publicField(this, "execute", (placeholderValues) => {
28056
28295
  return tracer.startActiveSpan("drizzle.operation", () => {
@@ -28059,25 +28298,49 @@ var init_refresh_materialized_view = __esm({
28059
28298
  });
28060
28299
  this.session = session;
28061
28300
  this.dialect = dialect6;
28062
- this.config = { view: view4 };
28301
+ this.config = { table: table5, withList };
28063
28302
  }
28064
- concurrently() {
28065
- if (this.config.withNoData !== void 0) {
28066
- throw new Error("Cannot use concurrently and withNoData together");
28067
- }
28068
- this.config.concurrently = true;
28303
+ /**
28304
+ * Adds a `where` clause to the query.
28305
+ *
28306
+ * Calling this method will delete only those rows that fulfill a specified condition.
28307
+ *
28308
+ * See docs: {@link https://orm.drizzle.team/docs/delete}
28309
+ *
28310
+ * @param where the `where` clause.
28311
+ *
28312
+ * @example
28313
+ * You can use conditional operators and `sql function` to filter the rows to be deleted.
28314
+ *
28315
+ * ```ts
28316
+ * // Delete all cars with green color
28317
+ * await db.delete(cars).where(eq(cars.color, 'green'));
28318
+ * // or
28319
+ * await db.delete(cars).where(sql`${cars.color} = 'green'`)
28320
+ * ```
28321
+ *
28322
+ * You can logically combine conditional operators with `and()` and `or()` operators:
28323
+ *
28324
+ * ```ts
28325
+ * // Delete all BMW cars with a green color
28326
+ * await db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
28327
+ *
28328
+ * // Delete all cars with the green or blue color
28329
+ * await db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
28330
+ * ```
28331
+ */
28332
+ where(where) {
28333
+ this.config.where = where;
28069
28334
  return this;
28070
28335
  }
28071
- withNoData() {
28072
- if (this.config.concurrently !== void 0) {
28073
- throw new Error("Cannot use concurrently and withNoData together");
28074
- }
28075
- this.config.withNoData = true;
28336
+ returning(fields = this.config.table[Table2.Symbol.Columns]) {
28337
+ this.config.returningFields = fields;
28338
+ this.config.returning = orderSelectedFields(fields);
28076
28339
  return this;
28077
28340
  }
28078
28341
  /** @internal */
28079
28342
  getSQL() {
28080
- return this.dialect.buildRefreshMaterializedViewQuery(this.config);
28343
+ return this.dialect.buildDeleteQuery(this.config);
28081
28344
  }
28082
28345
  toSQL() {
28083
28346
  const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
@@ -28086,7 +28349,10 @@ var init_refresh_materialized_view = __esm({
28086
28349
  /** @internal */
28087
28350
  _prepare(name2) {
28088
28351
  return tracer.startActiveSpan("drizzle.prepareQuery", () => {
28089
- return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), void 0, name2, true);
28352
+ return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name2, true, void 0, {
28353
+ type: "delete",
28354
+ tables: extractUsedTable(this.config.table)
28355
+ }, this.cacheConfig);
28090
28356
  });
28091
28357
  }
28092
28358
  prepare(name2) {
@@ -28097,204 +28363,193 @@ var init_refresh_materialized_view = __esm({
28097
28363
  this.authToken = token;
28098
28364
  return this;
28099
28365
  }
28100
- };
28101
- __publicField(PgRefreshMaterializedView, _a136, "PgRefreshMaterializedView");
28102
- }
28103
- });
28104
-
28105
- // ../drizzle-orm/dist/pg-core/query-builders/select.types.js
28106
- var init_select_types = __esm({
28107
- "../drizzle-orm/dist/pg-core/query-builders/select.types.js"() {
28108
- "use strict";
28366
+ /** @internal */
28367
+ getSelectedFields() {
28368
+ return this.config.returningFields ? new Proxy(
28369
+ this.config.returningFields,
28370
+ new SelectionProxyHandler({
28371
+ alias: getTableName(this.config.table),
28372
+ sqlAliasedBehavior: "alias",
28373
+ sqlBehavior: "error"
28374
+ })
28375
+ ) : void 0;
28376
+ }
28377
+ $dynamic() {
28378
+ return this;
28379
+ }
28380
+ };
28381
+ __publicField(PgDeleteBase, _a145, "PgDelete");
28109
28382
  }
28110
28383
  });
28111
28384
 
28112
- // ../drizzle-orm/dist/pg-core/query-builders/update.js
28113
- var _a137, PgUpdateBuilder, _a138, _b103, PgUpdateBase;
28114
- var init_update = __esm({
28115
- "../drizzle-orm/dist/pg-core/query-builders/update.js"() {
28385
+ // ../drizzle-orm/dist/pg-core/query-builders/insert.js
28386
+ var _a146, PgInsertBuilder, _a147, _b107, PgInsertBase;
28387
+ var init_insert = __esm({
28388
+ "../drizzle-orm/dist/pg-core/query-builders/insert.js"() {
28116
28389
  "use strict";
28117
28390
  init_entity();
28118
- init_table2();
28119
28391
  init_query_promise();
28120
28392
  init_selection_proxy();
28121
28393
  init_sql();
28122
- init_subquery();
28123
28394
  init_table();
28395
+ init_tracing();
28124
28396
  init_utils2();
28125
- init_view_common();
28126
- _a137 = entityKind;
28127
- PgUpdateBuilder = class {
28128
- constructor(table5, session, dialect6, withList) {
28397
+ init_utils4();
28398
+ init_query_builder2();
28399
+ _a146 = entityKind;
28400
+ PgInsertBuilder = class {
28401
+ constructor(table5, session, dialect6, withList, overridingSystemValue_) {
28129
28402
  __publicField(this, "authToken");
28130
28403
  this.table = table5;
28131
28404
  this.session = session;
28132
28405
  this.dialect = dialect6;
28133
28406
  this.withList = withList;
28407
+ this.overridingSystemValue_ = overridingSystemValue_;
28134
28408
  }
28409
+ /** @internal */
28135
28410
  setToken(token) {
28136
28411
  this.authToken = token;
28137
28412
  return this;
28138
28413
  }
28139
- set(values) {
28140
- return new PgUpdateBase(
28414
+ overridingSystemValue() {
28415
+ this.overridingSystemValue_ = true;
28416
+ return this;
28417
+ }
28418
+ values(values) {
28419
+ values = Array.isArray(values) ? values : [values];
28420
+ if (values.length === 0) {
28421
+ throw new Error("values() must be called with at least one value");
28422
+ }
28423
+ const mappedValues = values.map((entry) => {
28424
+ const result = {};
28425
+ const cols = this.table[Table2.Symbol.Columns];
28426
+ for (const colKey of Object.keys(entry)) {
28427
+ const colValue = entry[colKey];
28428
+ result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
28429
+ }
28430
+ return result;
28431
+ });
28432
+ return new PgInsertBase(
28141
28433
  this.table,
28142
- mapUpdateSet(this.table, values),
28434
+ mappedValues,
28143
28435
  this.session,
28144
28436
  this.dialect,
28145
- this.withList
28437
+ this.withList,
28438
+ false,
28439
+ this.overridingSystemValue_
28146
28440
  ).setToken(this.authToken);
28147
28441
  }
28442
+ select(selectQuery) {
28443
+ const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder()) : selectQuery;
28444
+ if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) {
28445
+ throw new Error(
28446
+ "Insert select error: selected fields are not the same or are in a different order compared to the table definition"
28447
+ );
28448
+ }
28449
+ return new PgInsertBase(this.table, select, this.session, this.dialect, this.withList, true);
28450
+ }
28148
28451
  };
28149
- __publicField(PgUpdateBuilder, _a137, "PgUpdateBuilder");
28150
- PgUpdateBase = class extends (_b103 = QueryPromise, _a138 = entityKind, _b103) {
28151
- constructor(table5, set, session, dialect6, withList) {
28452
+ __publicField(PgInsertBuilder, _a146, "PgInsertBuilder");
28453
+ PgInsertBase = class extends (_b107 = QueryPromise, _a147 = entityKind, _b107) {
28454
+ constructor(table5, values, session, dialect6, withList, select, overridingSystemValue_) {
28152
28455
  super();
28153
28456
  __publicField(this, "config");
28154
- __publicField(this, "tableName");
28155
- __publicField(this, "joinsNotNullableMap");
28156
- __publicField(this, "leftJoin", this.createJoin("left"));
28157
- __publicField(this, "rightJoin", this.createJoin("right"));
28158
- __publicField(this, "innerJoin", this.createJoin("inner"));
28159
- __publicField(this, "fullJoin", this.createJoin("full"));
28457
+ __publicField(this, "cacheConfig");
28160
28458
  __publicField(this, "authToken");
28161
28459
  __publicField(this, "execute", (placeholderValues) => {
28162
- return this._prepare().execute(placeholderValues, this.authToken);
28460
+ return tracer.startActiveSpan("drizzle.operation", () => {
28461
+ return this._prepare().execute(placeholderValues, this.authToken);
28462
+ });
28163
28463
  });
28164
28464
  this.session = session;
28165
28465
  this.dialect = dialect6;
28166
- this.config = { set, table: table5, withList, joins: [] };
28167
- this.tableName = getTableLikeName(table5);
28168
- this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
28466
+ this.config = { table: table5, values, withList, select, overridingSystemValue_ };
28169
28467
  }
28170
- from(source) {
28171
- const src = source;
28172
- const tableName = getTableLikeName(src);
28173
- if (typeof tableName === "string") {
28174
- this.joinsNotNullableMap[tableName] = true;
28175
- }
28176
- this.config.from = src;
28468
+ returning(fields = this.config.table[Table2.Symbol.Columns]) {
28469
+ this.config.returningFields = fields;
28470
+ this.config.returning = orderSelectedFields(fields);
28177
28471
  return this;
28178
28472
  }
28179
- getTableLikeFields(table5) {
28180
- if (is(table5, PgTable)) {
28181
- return table5[Table2.Symbol.Columns];
28182
- } else if (is(table5, Subquery)) {
28183
- return table5._.selectedFields;
28184
- }
28185
- return table5[ViewBaseConfig].selectedFields;
28186
- }
28187
- createJoin(joinType) {
28188
- return (table5, on) => {
28189
- const tableName = getTableLikeName(table5);
28190
- if (typeof tableName === "string" && this.config.joins.some((join) => join.alias === tableName)) {
28191
- throw new Error(`Alias "${tableName}" is already used in this query`);
28192
- }
28193
- if (typeof on === "function") {
28194
- const from = this.config.from && !is(this.config.from, SQL) ? this.getTableLikeFields(this.config.from) : void 0;
28195
- on = on(
28196
- new Proxy(
28197
- this.config.table[Table2.Symbol.Columns],
28198
- new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
28199
- ),
28200
- from && new Proxy(
28201
- from,
28202
- new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
28203
- )
28204
- );
28205
- }
28206
- this.config.joins.push({ on, table: table5, joinType, alias: tableName });
28207
- if (typeof tableName === "string") {
28208
- switch (joinType) {
28209
- case "left": {
28210
- this.joinsNotNullableMap[tableName] = false;
28211
- break;
28212
- }
28213
- case "right": {
28214
- this.joinsNotNullableMap = Object.fromEntries(
28215
- Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
28216
- );
28217
- this.joinsNotNullableMap[tableName] = true;
28218
- break;
28219
- }
28220
- case "inner": {
28221
- this.joinsNotNullableMap[tableName] = true;
28222
- break;
28223
- }
28224
- case "full": {
28225
- this.joinsNotNullableMap = Object.fromEntries(
28226
- Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
28227
- );
28228
- this.joinsNotNullableMap[tableName] = false;
28229
- break;
28230
- }
28231
- }
28232
- }
28233
- return this;
28234
- };
28235
- }
28236
28473
  /**
28237
- * Adds a 'where' clause to the query.
28474
+ * Adds an `on conflict do nothing` clause to the query.
28238
28475
  *
28239
- * Calling this method will update only those rows that fulfill a specified condition.
28476
+ * Calling this method simply avoids inserting a row as its alternative action.
28240
28477
  *
28241
- * See docs: {@link https://orm.drizzle.team/docs/update}
28478
+ * See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}
28242
28479
  *
28243
- * @param where the 'where' clause.
28480
+ * @param config The `target` and `where` clauses.
28244
28481
  *
28245
28482
  * @example
28246
- * You can use conditional operators and `sql function` to filter the rows to be updated.
28247
- *
28248
28483
  * ```ts
28249
- * // Update all cars with green color
28250
- * await db.update(cars).set({ color: 'red' })
28251
- * .where(eq(cars.color, 'green'));
28252
- * // or
28253
- * await db.update(cars).set({ color: 'red' })
28254
- * .where(sql`${cars.color} = 'green'`)
28484
+ * // Insert one row and cancel the insert if there's a conflict
28485
+ * await db.insert(cars)
28486
+ * .values({ id: 1, brand: 'BMW' })
28487
+ * .onConflictDoNothing();
28488
+ *
28489
+ * // Explicitly specify conflict target
28490
+ * await db.insert(cars)
28491
+ * .values({ id: 1, brand: 'BMW' })
28492
+ * .onConflictDoNothing({ target: cars.id });
28255
28493
  * ```
28494
+ */
28495
+ onConflictDoNothing(config = {}) {
28496
+ if (config.target === void 0) {
28497
+ this.config.onConflict = sql`do nothing`;
28498
+ } else {
28499
+ let targetColumn = "";
28500
+ 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));
28501
+ const whereSql = config.where ? sql` where ${config.where}` : void 0;
28502
+ this.config.onConflict = sql`(${sql.raw(targetColumn)})${whereSql} do nothing`;
28503
+ }
28504
+ return this;
28505
+ }
28506
+ /**
28507
+ * Adds an `on conflict do update` clause to the query.
28256
28508
  *
28257
- * You can logically combine conditional operators with `and()` and `or()` operators:
28509
+ * Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.
28510
+ *
28511
+ * See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}
28512
+ *
28513
+ * @param config The `target`, `set` and `where` clauses.
28258
28514
  *
28515
+ * @example
28259
28516
  * ```ts
28260
- * // Update all BMW cars with a green color
28261
- * await db.update(cars).set({ color: 'red' })
28262
- * .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
28517
+ * // Update the row if there's a conflict
28518
+ * await db.insert(cars)
28519
+ * .values({ id: 1, brand: 'BMW' })
28520
+ * .onConflictDoUpdate({
28521
+ * target: cars.id,
28522
+ * set: { brand: 'Porsche' }
28523
+ * });
28263
28524
  *
28264
- * // Update all cars with the green or blue color
28265
- * await db.update(cars).set({ color: 'red' })
28266
- * .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
28525
+ * // Upsert with 'where' clause
28526
+ * await db.insert(cars)
28527
+ * .values({ id: 1, brand: 'BMW' })
28528
+ * .onConflictDoUpdate({
28529
+ * target: cars.id,
28530
+ * set: { brand: 'newBMW' },
28531
+ * targetWhere: sql`${cars.createdAt} > '2023-01-01'::date`,
28532
+ * });
28267
28533
  * ```
28268
28534
  */
28269
- where(where) {
28270
- this.config.where = where;
28271
- return this;
28272
- }
28273
- returning(fields) {
28274
- if (!fields) {
28275
- fields = Object.assign({}, this.config.table[Table2.Symbol.Columns]);
28276
- if (this.config.from) {
28277
- const tableName = getTableLikeName(this.config.from);
28278
- if (typeof tableName === "string" && this.config.from && !is(this.config.from, SQL)) {
28279
- const fromFields = this.getTableLikeFields(this.config.from);
28280
- fields[tableName] = fromFields;
28281
- }
28282
- for (const join of this.config.joins) {
28283
- const tableName2 = getTableLikeName(join.table);
28284
- if (typeof tableName2 === "string" && !is(join.table, SQL)) {
28285
- const fromFields = this.getTableLikeFields(join.table);
28286
- fields[tableName2] = fromFields;
28287
- }
28288
- }
28289
- }
28535
+ onConflictDoUpdate(config) {
28536
+ if (config.where && (config.targetWhere || config.setWhere)) {
28537
+ throw new Error(
28538
+ 'You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.'
28539
+ );
28290
28540
  }
28291
- this.config.returningFields = fields;
28292
- this.config.returning = orderSelectedFields(fields);
28541
+ const whereSql = config.where ? sql` where ${config.where}` : void 0;
28542
+ const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : void 0;
28543
+ const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : void 0;
28544
+ const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
28545
+ let targetColumn = "";
28546
+ 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));
28547
+ this.config.onConflict = sql`(${sql.raw(targetColumn)})${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`;
28293
28548
  return this;
28294
28549
  }
28295
28550
  /** @internal */
28296
28551
  getSQL() {
28297
- return this.dialect.buildUpdateQuery(this.config);
28552
+ return this.dialect.buildInsertQuery(this.config);
28298
28553
  }
28299
28554
  toSQL() {
28300
28555
  const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
@@ -28302,9 +28557,12 @@ var init_update = __esm({
28302
28557
  }
28303
28558
  /** @internal */
28304
28559
  _prepare(name2) {
28305
- const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name2, true);
28306
- query.joinsNotNullableMap = this.joinsNotNullableMap;
28307
- return query;
28560
+ return tracer.startActiveSpan("drizzle.prepareQuery", () => {
28561
+ return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name2, true, void 0, {
28562
+ type: "insert",
28563
+ tables: extractUsedTable(this.config.table)
28564
+ }, this.cacheConfig);
28565
+ });
28308
28566
  }
28309
28567
  prepare(name2) {
28310
28568
  return this._prepare(name2);
@@ -28329,1010 +28587,891 @@ var init_update = __esm({
28329
28587
  return this;
28330
28588
  }
28331
28589
  };
28332
- __publicField(PgUpdateBase, _a138, "PgUpdate");
28333
- }
28334
- });
28335
-
28336
- // ../drizzle-orm/dist/pg-core/query-builders/index.js
28337
- var init_query_builders = __esm({
28338
- "../drizzle-orm/dist/pg-core/query-builders/index.js"() {
28339
- "use strict";
28340
- init_delete();
28341
- init_insert();
28342
- init_query_builder2();
28343
- init_refresh_materialized_view();
28344
- init_select2();
28345
- init_select_types();
28346
- init_update();
28347
- }
28348
- });
28349
-
28350
- // ../drizzle-orm/dist/pg-core/query-builders/count.js
28351
- var _a139, _b104, _c4, _PgCountBuilder, PgCountBuilder;
28352
- var init_count = __esm({
28353
- "../drizzle-orm/dist/pg-core/query-builders/count.js"() {
28354
- "use strict";
28355
- init_entity();
28356
- init_sql();
28357
- _PgCountBuilder = class _PgCountBuilder extends (_c4 = SQL, _b104 = entityKind, _a139 = Symbol.toStringTag, _c4) {
28358
- constructor(params) {
28359
- super(_PgCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
28360
- __publicField(this, "sql");
28361
- __publicField(this, "token");
28362
- __publicField(this, _a139, "PgCountBuilder");
28363
- __publicField(this, "session");
28364
- this.params = params;
28365
- this.mapWith(Number);
28366
- this.session = params.session;
28367
- this.sql = _PgCountBuilder.buildCount(
28368
- params.source,
28369
- params.filters
28370
- );
28371
- }
28372
- static buildEmbeddedCount(source, filters) {
28373
- return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`;
28374
- }
28375
- static buildCount(source, filters) {
28376
- return sql`select count(*) as count from ${source}${sql.raw(" where ").if(filters)}${filters};`;
28377
- }
28378
- /** @intrnal */
28379
- setToken(token) {
28380
- this.token = token;
28381
- return this;
28382
- }
28383
- then(onfulfilled, onrejected) {
28384
- return Promise.resolve(this.session.count(this.sql, this.token)).then(
28385
- onfulfilled,
28386
- onrejected
28387
- );
28388
- }
28389
- catch(onRejected) {
28390
- return this.then(void 0, onRejected);
28391
- }
28392
- finally(onFinally) {
28393
- return this.then(
28394
- (value) => {
28395
- onFinally?.();
28396
- return value;
28397
- },
28398
- (reason) => {
28399
- onFinally?.();
28400
- throw reason;
28401
- }
28402
- );
28403
- }
28404
- };
28405
- __publicField(_PgCountBuilder, _b104, "PgCountBuilder");
28406
- PgCountBuilder = _PgCountBuilder;
28590
+ __publicField(PgInsertBase, _a147, "PgInsert");
28407
28591
  }
28408
28592
  });
28409
28593
 
28410
- // ../drizzle-orm/dist/pg-core/query-builders/query.js
28411
- var _a140, RelationalQueryBuilder, _a141, _b105, PgRelationalQuery;
28412
- var init_query = __esm({
28413
- "../drizzle-orm/dist/pg-core/query-builders/query.js"() {
28594
+ // ../drizzle-orm/dist/pg-core/query-builders/refresh-materialized-view.js
28595
+ var _a148, _b108, PgRefreshMaterializedView;
28596
+ var init_refresh_materialized_view = __esm({
28597
+ "../drizzle-orm/dist/pg-core/query-builders/refresh-materialized-view.js"() {
28414
28598
  "use strict";
28415
28599
  init_entity();
28416
28600
  init_query_promise();
28417
- init_relations();
28418
28601
  init_tracing();
28419
- _a140 = entityKind;
28420
- RelationalQueryBuilder = class {
28421
- constructor(fullSchema, schema5, tableNamesMap, table5, tableConfig, dialect6, session) {
28422
- this.fullSchema = fullSchema;
28423
- this.schema = schema5;
28424
- this.tableNamesMap = tableNamesMap;
28425
- this.table = table5;
28426
- this.tableConfig = tableConfig;
28427
- this.dialect = dialect6;
28602
+ PgRefreshMaterializedView = class extends (_b108 = QueryPromise, _a148 = entityKind, _b108) {
28603
+ constructor(view4, session, dialect6) {
28604
+ super();
28605
+ __publicField(this, "config");
28606
+ __publicField(this, "authToken");
28607
+ __publicField(this, "execute", (placeholderValues) => {
28608
+ return tracer.startActiveSpan("drizzle.operation", () => {
28609
+ return this._prepare().execute(placeholderValues, this.authToken);
28610
+ });
28611
+ });
28428
28612
  this.session = session;
28613
+ this.dialect = dialect6;
28614
+ this.config = { view: view4 };
28429
28615
  }
28430
- findMany(config) {
28431
- return new PgRelationalQuery(
28432
- this.fullSchema,
28433
- this.schema,
28434
- this.tableNamesMap,
28435
- this.table,
28436
- this.tableConfig,
28437
- this.dialect,
28438
- this.session,
28439
- config ? config : {},
28440
- "many"
28441
- );
28616
+ concurrently() {
28617
+ if (this.config.withNoData !== void 0) {
28618
+ throw new Error("Cannot use concurrently and withNoData together");
28619
+ }
28620
+ this.config.concurrently = true;
28621
+ return this;
28442
28622
  }
28443
- findFirst(config) {
28444
- return new PgRelationalQuery(
28445
- this.fullSchema,
28446
- this.schema,
28447
- this.tableNamesMap,
28448
- this.table,
28449
- this.tableConfig,
28450
- this.dialect,
28451
- this.session,
28452
- config ? { ...config, limit: 1 } : { limit: 1 },
28453
- "first"
28454
- );
28623
+ withNoData() {
28624
+ if (this.config.concurrently !== void 0) {
28625
+ throw new Error("Cannot use concurrently and withNoData together");
28626
+ }
28627
+ this.config.withNoData = true;
28628
+ return this;
28455
28629
  }
28456
- };
28457
- __publicField(RelationalQueryBuilder, _a140, "PgRelationalQueryBuilder");
28458
- PgRelationalQuery = class extends (_b105 = QueryPromise, _a141 = entityKind, _b105) {
28459
- constructor(fullSchema, schema5, tableNamesMap, table5, tableConfig, dialect6, session, config, mode) {
28460
- super();
28461
- __publicField(this, "authToken");
28462
- this.fullSchema = fullSchema;
28463
- this.schema = schema5;
28464
- this.tableNamesMap = tableNamesMap;
28465
- this.table = table5;
28466
- this.tableConfig = tableConfig;
28467
- this.dialect = dialect6;
28468
- this.session = session;
28469
- this.config = config;
28470
- this.mode = mode;
28630
+ /** @internal */
28631
+ getSQL() {
28632
+ return this.dialect.buildRefreshMaterializedViewQuery(this.config);
28633
+ }
28634
+ toSQL() {
28635
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
28636
+ return rest;
28471
28637
  }
28472
28638
  /** @internal */
28473
28639
  _prepare(name2) {
28474
28640
  return tracer.startActiveSpan("drizzle.prepareQuery", () => {
28475
- const { query, builtQuery } = this._toSQL();
28476
- return this.session.prepareQuery(
28477
- builtQuery,
28478
- void 0,
28479
- name2,
28480
- true,
28481
- (rawRows, mapColumnValue) => {
28482
- const rows = rawRows.map(
28483
- (row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue)
28484
- );
28485
- if (this.mode === "first") {
28486
- return rows[0];
28487
- }
28488
- return rows;
28489
- }
28490
- );
28641
+ return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), void 0, name2, true);
28491
28642
  });
28492
28643
  }
28493
28644
  prepare(name2) {
28494
28645
  return this._prepare(name2);
28495
28646
  }
28496
- _getQuery() {
28497
- return this.dialect.buildRelationalQueryWithoutPK({
28498
- fullSchema: this.fullSchema,
28499
- schema: this.schema,
28500
- tableNamesMap: this.tableNamesMap,
28501
- table: this.table,
28502
- tableConfig: this.tableConfig,
28503
- queryConfig: this.config,
28504
- tableAlias: this.tableConfig.tsName
28505
- });
28506
- }
28507
- /** @internal */
28508
- getSQL() {
28509
- return this._getQuery().sql;
28510
- }
28511
- _toSQL() {
28512
- const query = this._getQuery();
28513
- const builtQuery = this.dialect.sqlToQuery(query.sql);
28514
- return { query, builtQuery };
28515
- }
28516
- toSQL() {
28517
- return this._toSQL().builtQuery;
28518
- }
28519
28647
  /** @internal */
28520
28648
  setToken(token) {
28521
28649
  this.authToken = token;
28522
28650
  return this;
28523
28651
  }
28524
- execute() {
28525
- return tracer.startActiveSpan("drizzle.operation", () => {
28526
- return this._prepare().execute(void 0, this.authToken);
28527
- });
28528
- }
28529
28652
  };
28530
- __publicField(PgRelationalQuery, _a141, "PgRelationalQuery");
28653
+ __publicField(PgRefreshMaterializedView, _a148, "PgRefreshMaterializedView");
28531
28654
  }
28532
28655
  });
28533
28656
 
28534
- // ../drizzle-orm/dist/pg-core/query-builders/raw.js
28535
- var _a142, _b106, PgRaw;
28536
- var init_raw = __esm({
28537
- "../drizzle-orm/dist/pg-core/query-builders/raw.js"() {
28657
+ // ../drizzle-orm/dist/pg-core/query-builders/select.types.js
28658
+ var init_select_types = __esm({
28659
+ "../drizzle-orm/dist/pg-core/query-builders/select.types.js"() {
28538
28660
  "use strict";
28539
- init_entity();
28540
- init_query_promise();
28541
- PgRaw = class extends (_b106 = QueryPromise, _a142 = entityKind, _b106) {
28542
- constructor(execute, sql2, query, mapBatchResult) {
28543
- super();
28544
- this.execute = execute;
28545
- this.sql = sql2;
28546
- this.query = query;
28547
- this.mapBatchResult = mapBatchResult;
28548
- }
28549
- /** @internal */
28550
- getSQL() {
28551
- return this.sql;
28552
- }
28553
- getQuery() {
28554
- return this.query;
28555
- }
28556
- mapResult(result, isFromBatch) {
28557
- return isFromBatch ? this.mapBatchResult(result) : result;
28558
- }
28559
- _prepare() {
28560
- return this;
28561
- }
28562
- /** @internal */
28563
- isResponseInArrayMode() {
28564
- return false;
28565
- }
28566
- };
28567
- __publicField(PgRaw, _a142, "PgRaw");
28568
28661
  }
28569
28662
  });
28570
28663
 
28571
- // ../drizzle-orm/dist/pg-core/db.js
28572
- var _a143, PgDatabase;
28573
- var init_db = __esm({
28574
- "../drizzle-orm/dist/pg-core/db.js"() {
28664
+ // ../drizzle-orm/dist/pg-core/query-builders/update.js
28665
+ var _a149, PgUpdateBuilder, _a150, _b109, PgUpdateBase;
28666
+ var init_update = __esm({
28667
+ "../drizzle-orm/dist/pg-core/query-builders/update.js"() {
28575
28668
  "use strict";
28576
28669
  init_entity();
28577
- init_query_builders();
28670
+ init_table2();
28671
+ init_query_promise();
28578
28672
  init_selection_proxy();
28579
28673
  init_sql();
28580
28674
  init_subquery();
28581
- init_count();
28582
- init_query();
28583
- init_raw();
28584
- init_refresh_materialized_view();
28585
- _a143 = entityKind;
28586
- PgDatabase = class {
28587
- constructor(dialect6, session, schema5) {
28588
- __publicField(this, "query");
28589
- /**
28590
- * Creates a subquery that defines a temporary named result set as a CTE.
28591
- *
28592
- * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.
28593
- *
28594
- * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
28595
- *
28596
- * @param alias The alias for the subquery.
28597
- *
28598
- * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.
28599
- *
28600
- * @example
28601
- *
28602
- * ```ts
28603
- * // Create a subquery with alias 'sq' and use it in the select query
28604
- * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
28605
- *
28606
- * const result = await db.with(sq).select().from(sq);
28607
- * ```
28608
- *
28609
- * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:
28610
- *
28611
- * ```ts
28612
- * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query
28613
- * const sq = db.$with('sq').as(db.select({
28614
- * name: sql<string>`upper(${users.name})`.as('name'),
28615
- * })
28616
- * .from(users));
28617
- *
28618
- * const result = await db.with(sq).select({ name: sq.name }).from(sq);
28619
- * ```
28620
- */
28621
- __publicField(this, "$with", (alias, selection) => {
28622
- const self2 = this;
28623
- const as = (qb) => {
28624
- if (typeof qb === "function") {
28625
- qb = qb(new QueryBuilder(self2.dialect));
28626
- }
28627
- return new Proxy(
28628
- new WithSubquery(
28629
- qb.getSQL(),
28630
- selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}),
28631
- alias,
28632
- true
28633
- ),
28634
- new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
28635
- );
28636
- };
28637
- return { as };
28638
- });
28675
+ init_table();
28676
+ init_utils2();
28677
+ init_view_common();
28678
+ init_utils4();
28679
+ _a149 = entityKind;
28680
+ PgUpdateBuilder = class {
28681
+ constructor(table5, session, dialect6, withList) {
28639
28682
  __publicField(this, "authToken");
28683
+ this.table = table5;
28684
+ this.session = session;
28640
28685
  this.dialect = dialect6;
28686
+ this.withList = withList;
28687
+ }
28688
+ setToken(token) {
28689
+ this.authToken = token;
28690
+ return this;
28691
+ }
28692
+ set(values) {
28693
+ return new PgUpdateBase(
28694
+ this.table,
28695
+ mapUpdateSet(this.table, values),
28696
+ this.session,
28697
+ this.dialect,
28698
+ this.withList
28699
+ ).setToken(this.authToken);
28700
+ }
28701
+ };
28702
+ __publicField(PgUpdateBuilder, _a149, "PgUpdateBuilder");
28703
+ PgUpdateBase = class extends (_b109 = QueryPromise, _a150 = entityKind, _b109) {
28704
+ constructor(table5, set, session, dialect6, withList) {
28705
+ super();
28706
+ __publicField(this, "config");
28707
+ __publicField(this, "tableName");
28708
+ __publicField(this, "joinsNotNullableMap");
28709
+ __publicField(this, "cacheConfig");
28710
+ __publicField(this, "leftJoin", this.createJoin("left"));
28711
+ __publicField(this, "rightJoin", this.createJoin("right"));
28712
+ __publicField(this, "innerJoin", this.createJoin("inner"));
28713
+ __publicField(this, "fullJoin", this.createJoin("full"));
28714
+ __publicField(this, "authToken");
28715
+ __publicField(this, "execute", (placeholderValues) => {
28716
+ return this._prepare().execute(placeholderValues, this.authToken);
28717
+ });
28641
28718
  this.session = session;
28642
- this._ = schema5 ? {
28643
- schema: schema5.schema,
28644
- fullSchema: schema5.fullSchema,
28645
- tableNamesMap: schema5.tableNamesMap,
28646
- session
28647
- } : {
28648
- schema: void 0,
28649
- fullSchema: {},
28650
- tableNamesMap: {},
28651
- session
28652
- };
28653
- this.query = {};
28654
- if (this._.schema) {
28655
- for (const [tableName, columns] of Object.entries(this._.schema)) {
28656
- this.query[tableName] = new RelationalQueryBuilder(
28657
- schema5.fullSchema,
28658
- this._.schema,
28659
- this._.tableNamesMap,
28660
- schema5.fullSchema[tableName],
28661
- columns,
28662
- dialect6,
28663
- session
28664
- );
28665
- }
28719
+ this.dialect = dialect6;
28720
+ this.config = { set, table: table5, withList, joins: [] };
28721
+ this.tableName = getTableLikeName(table5);
28722
+ this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
28723
+ }
28724
+ from(source) {
28725
+ const src = source;
28726
+ const tableName = getTableLikeName(src);
28727
+ if (typeof tableName === "string") {
28728
+ this.joinsNotNullableMap[tableName] = true;
28666
28729
  }
28730
+ this.config.from = src;
28731
+ return this;
28667
28732
  }
28668
- $count(source, filters) {
28669
- return new PgCountBuilder({ source, filters, session: this.session });
28733
+ getTableLikeFields(table5) {
28734
+ if (is(table5, PgTable)) {
28735
+ return table5[Table2.Symbol.Columns];
28736
+ } else if (is(table5, Subquery)) {
28737
+ return table5._.selectedFields;
28738
+ }
28739
+ return table5[ViewBaseConfig].selectedFields;
28740
+ }
28741
+ createJoin(joinType) {
28742
+ return (table5, on) => {
28743
+ const tableName = getTableLikeName(table5);
28744
+ if (typeof tableName === "string" && this.config.joins.some((join) => join.alias === tableName)) {
28745
+ throw new Error(`Alias "${tableName}" is already used in this query`);
28746
+ }
28747
+ if (typeof on === "function") {
28748
+ const from = this.config.from && !is(this.config.from, SQL) ? this.getTableLikeFields(this.config.from) : void 0;
28749
+ on = on(
28750
+ new Proxy(
28751
+ this.config.table[Table2.Symbol.Columns],
28752
+ new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
28753
+ ),
28754
+ from && new Proxy(
28755
+ from,
28756
+ new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
28757
+ )
28758
+ );
28759
+ }
28760
+ this.config.joins.push({ on, table: table5, joinType, alias: tableName });
28761
+ if (typeof tableName === "string") {
28762
+ switch (joinType) {
28763
+ case "left": {
28764
+ this.joinsNotNullableMap[tableName] = false;
28765
+ break;
28766
+ }
28767
+ case "right": {
28768
+ this.joinsNotNullableMap = Object.fromEntries(
28769
+ Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
28770
+ );
28771
+ this.joinsNotNullableMap[tableName] = true;
28772
+ break;
28773
+ }
28774
+ case "inner": {
28775
+ this.joinsNotNullableMap[tableName] = true;
28776
+ break;
28777
+ }
28778
+ case "full": {
28779
+ this.joinsNotNullableMap = Object.fromEntries(
28780
+ Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
28781
+ );
28782
+ this.joinsNotNullableMap[tableName] = false;
28783
+ break;
28784
+ }
28785
+ }
28786
+ }
28787
+ return this;
28788
+ };
28670
28789
  }
28671
28790
  /**
28672
- * Incorporates a previously defined CTE (using `$with`) into the main query.
28791
+ * Adds a 'where' clause to the query.
28673
28792
  *
28674
- * This method allows the main query to reference a temporary named result set.
28793
+ * Calling this method will update only those rows that fulfill a specified condition.
28675
28794
  *
28676
- * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
28795
+ * See docs: {@link https://orm.drizzle.team/docs/update}
28677
28796
  *
28678
- * @param queries The CTEs to incorporate into the main query.
28797
+ * @param where the 'where' clause.
28679
28798
  *
28680
28799
  * @example
28800
+ * You can use conditional operators and `sql function` to filter the rows to be updated.
28681
28801
  *
28682
28802
  * ```ts
28683
- * // Define a subquery 'sq' as a CTE using $with
28684
- * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
28803
+ * // Update all cars with green color
28804
+ * await db.update(cars).set({ color: 'red' })
28805
+ * .where(eq(cars.color, 'green'));
28806
+ * // or
28807
+ * await db.update(cars).set({ color: 'red' })
28808
+ * .where(sql`${cars.color} = 'green'`)
28809
+ * ```
28685
28810
  *
28686
- * // Incorporate the CTE 'sq' into the main query and select from it
28687
- * const result = await db.with(sq).select().from(sq);
28811
+ * You can logically combine conditional operators with `and()` and `or()` operators:
28812
+ *
28813
+ * ```ts
28814
+ * // Update all BMW cars with a green color
28815
+ * await db.update(cars).set({ color: 'red' })
28816
+ * .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
28817
+ *
28818
+ * // Update all cars with the green or blue color
28819
+ * await db.update(cars).set({ color: 'red' })
28820
+ * .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
28688
28821
  * ```
28689
28822
  */
28690
- with(...queries) {
28691
- const self2 = this;
28692
- function select(fields) {
28693
- return new PgSelectBuilder({
28694
- fields: fields ?? void 0,
28695
- session: self2.session,
28696
- dialect: self2.dialect,
28697
- withList: queries
28698
- });
28699
- }
28700
- function selectDistinct(fields) {
28701
- return new PgSelectBuilder({
28702
- fields: fields ?? void 0,
28703
- session: self2.session,
28704
- dialect: self2.dialect,
28705
- withList: queries,
28706
- distinct: true
28707
- });
28708
- }
28709
- function selectDistinctOn(on, fields) {
28710
- return new PgSelectBuilder({
28711
- fields: fields ?? void 0,
28712
- session: self2.session,
28713
- dialect: self2.dialect,
28714
- withList: queries,
28715
- distinct: { on }
28716
- });
28717
- }
28718
- function update(table5) {
28719
- return new PgUpdateBuilder(table5, self2.session, self2.dialect, queries);
28720
- }
28721
- function insert(table5) {
28722
- return new PgInsertBuilder(table5, self2.session, self2.dialect, queries);
28723
- }
28724
- function delete_(table5) {
28725
- return new PgDeleteBase(table5, self2.session, self2.dialect, queries);
28726
- }
28727
- return { select, selectDistinct, selectDistinctOn, update, insert, delete: delete_ };
28823
+ where(where) {
28824
+ this.config.where = where;
28825
+ return this;
28728
28826
  }
28729
- select(fields) {
28730
- return new PgSelectBuilder({
28731
- fields: fields ?? void 0,
28732
- session: this.session,
28733
- dialect: this.dialect
28734
- });
28735
- }
28736
- selectDistinct(fields) {
28737
- return new PgSelectBuilder({
28738
- fields: fields ?? void 0,
28739
- session: this.session,
28740
- dialect: this.dialect,
28741
- distinct: true
28742
- });
28827
+ returning(fields) {
28828
+ if (!fields) {
28829
+ fields = Object.assign({}, this.config.table[Table2.Symbol.Columns]);
28830
+ if (this.config.from) {
28831
+ const tableName = getTableLikeName(this.config.from);
28832
+ if (typeof tableName === "string" && this.config.from && !is(this.config.from, SQL)) {
28833
+ const fromFields = this.getTableLikeFields(this.config.from);
28834
+ fields[tableName] = fromFields;
28835
+ }
28836
+ for (const join of this.config.joins) {
28837
+ const tableName2 = getTableLikeName(join.table);
28838
+ if (typeof tableName2 === "string" && !is(join.table, SQL)) {
28839
+ const fromFields = this.getTableLikeFields(join.table);
28840
+ fields[tableName2] = fromFields;
28841
+ }
28842
+ }
28843
+ }
28844
+ }
28845
+ this.config.returningFields = fields;
28846
+ this.config.returning = orderSelectedFields(fields);
28847
+ return this;
28743
28848
  }
28744
- selectDistinctOn(on, fields) {
28745
- return new PgSelectBuilder({
28746
- fields: fields ?? void 0,
28747
- session: this.session,
28748
- dialect: this.dialect,
28749
- distinct: { on }
28750
- });
28849
+ /** @internal */
28850
+ getSQL() {
28851
+ return this.dialect.buildUpdateQuery(this.config);
28751
28852
  }
28752
- /**
28753
- * Creates an update query.
28754
- *
28755
- * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.
28756
- *
28757
- * Use `.set()` method to specify which values to update.
28758
- *
28759
- * See docs: {@link https://orm.drizzle.team/docs/update}
28760
- *
28761
- * @param table The table to update.
28762
- *
28763
- * @example
28764
- *
28765
- * ```ts
28766
- * // Update all rows in the 'cars' table
28767
- * await db.update(cars).set({ color: 'red' });
28768
- *
28769
- * // Update rows with filters and conditions
28770
- * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));
28771
- *
28772
- * // Update with returning clause
28773
- * const updatedCar: Car[] = await db.update(cars)
28774
- * .set({ color: 'red' })
28775
- * .where(eq(cars.id, 1))
28776
- * .returning();
28777
- * ```
28778
- */
28779
- update(table5) {
28780
- return new PgUpdateBuilder(table5, this.session, this.dialect);
28853
+ toSQL() {
28854
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
28855
+ return rest;
28781
28856
  }
28782
- /**
28783
- * Creates an insert query.
28784
- *
28785
- * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.
28786
- *
28787
- * See docs: {@link https://orm.drizzle.team/docs/insert}
28788
- *
28789
- * @param table The table to insert into.
28790
- *
28791
- * @example
28792
- *
28793
- * ```ts
28794
- * // Insert one row
28795
- * await db.insert(cars).values({ brand: 'BMW' });
28796
- *
28797
- * // Insert multiple rows
28798
- * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);
28799
- *
28800
- * // Insert with returning clause
28801
- * const insertedCar: Car[] = await db.insert(cars)
28802
- * .values({ brand: 'BMW' })
28803
- * .returning();
28804
- * ```
28805
- */
28806
- insert(table5) {
28807
- return new PgInsertBuilder(table5, this.session, this.dialect);
28857
+ /** @internal */
28858
+ _prepare(name2) {
28859
+ const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name2, true, void 0, {
28860
+ type: "insert",
28861
+ tables: extractUsedTable(this.config.table)
28862
+ }, this.cacheConfig);
28863
+ query.joinsNotNullableMap = this.joinsNotNullableMap;
28864
+ return query;
28808
28865
  }
28809
- /**
28810
- * Creates a delete query.
28811
- *
28812
- * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.
28813
- *
28814
- * See docs: {@link https://orm.drizzle.team/docs/delete}
28815
- *
28816
- * @param table The table to delete from.
28817
- *
28818
- * @example
28819
- *
28820
- * ```ts
28821
- * // Delete all rows in the 'cars' table
28822
- * await db.delete(cars);
28823
- *
28824
- * // Delete rows with filters and conditions
28825
- * await db.delete(cars).where(eq(cars.color, 'green'));
28826
- *
28827
- * // Delete with returning clause
28828
- * const deletedCar: Car[] = await db.delete(cars)
28829
- * .where(eq(cars.id, 1))
28830
- * .returning();
28831
- * ```
28832
- */
28833
- delete(table5) {
28834
- return new PgDeleteBase(table5, this.session, this.dialect);
28866
+ prepare(name2) {
28867
+ return this._prepare(name2);
28835
28868
  }
28836
- refreshMaterializedView(view4) {
28837
- return new PgRefreshMaterializedView(view4, this.session, this.dialect);
28869
+ /** @internal */
28870
+ setToken(token) {
28871
+ this.authToken = token;
28872
+ return this;
28838
28873
  }
28839
- execute(query) {
28840
- const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
28841
- const builtQuery = this.dialect.sqlToQuery(sequel);
28842
- const prepared = this.session.prepareQuery(
28843
- builtQuery,
28844
- void 0,
28845
- void 0,
28846
- false
28847
- );
28848
- return new PgRaw(
28849
- () => prepared.execute(void 0, this.authToken),
28850
- sequel,
28851
- builtQuery,
28852
- (result) => prepared.mapResult(result, true)
28853
- );
28874
+ /** @internal */
28875
+ getSelectedFields() {
28876
+ return this.config.returningFields ? new Proxy(
28877
+ this.config.returningFields,
28878
+ new SelectionProxyHandler({
28879
+ alias: getTableName(this.config.table),
28880
+ sqlAliasedBehavior: "alias",
28881
+ sqlBehavior: "error"
28882
+ })
28883
+ ) : void 0;
28854
28884
  }
28855
- transaction(transaction, config) {
28856
- return this.session.transaction(transaction, config);
28885
+ $dynamic() {
28886
+ return this;
28857
28887
  }
28858
28888
  };
28859
- __publicField(PgDatabase, _a143, "PgDatabase");
28889
+ __publicField(PgUpdateBase, _a150, "PgUpdate");
28860
28890
  }
28861
28891
  });
28862
28892
 
28863
- // ../drizzle-orm/dist/pg-core/indexes.js
28864
- var _a144, IndexBuilderOn, _a145, IndexBuilder, _a146, Index2;
28865
- var init_indexes = __esm({
28866
- "../drizzle-orm/dist/pg-core/indexes.js"() {
28893
+ // ../drizzle-orm/dist/pg-core/query-builders/index.js
28894
+ var init_query_builders = __esm({
28895
+ "../drizzle-orm/dist/pg-core/query-builders/index.js"() {
28896
+ "use strict";
28897
+ init_delete();
28898
+ init_insert();
28899
+ init_query_builder2();
28900
+ init_refresh_materialized_view();
28901
+ init_select2();
28902
+ init_select_types();
28903
+ init_update();
28904
+ }
28905
+ });
28906
+
28907
+ // ../drizzle-orm/dist/pg-core/query-builders/count.js
28908
+ var _a151, _b110, _c6, _PgCountBuilder, PgCountBuilder;
28909
+ var init_count = __esm({
28910
+ "../drizzle-orm/dist/pg-core/query-builders/count.js"() {
28867
28911
  "use strict";
28868
- init_sql();
28869
28912
  init_entity();
28870
- init_columns();
28871
- _a144 = entityKind;
28872
- IndexBuilderOn = class {
28873
- constructor(unique, name2) {
28874
- this.unique = unique;
28875
- this.name = name2;
28876
- }
28877
- on(...columns) {
28878
- return new IndexBuilder(
28879
- columns.map((it) => {
28880
- if (is(it, SQL)) {
28881
- return it;
28882
- }
28883
- it = it;
28884
- const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);
28885
- it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig));
28886
- return clonedIndexedColumn;
28887
- }),
28888
- this.unique,
28889
- false,
28890
- this.name
28913
+ init_sql();
28914
+ _PgCountBuilder = class _PgCountBuilder extends (_c6 = SQL, _b110 = entityKind, _a151 = Symbol.toStringTag, _c6) {
28915
+ constructor(params) {
28916
+ super(_PgCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
28917
+ __publicField(this, "sql");
28918
+ __publicField(this, "token");
28919
+ __publicField(this, _a151, "PgCountBuilder");
28920
+ __publicField(this, "session");
28921
+ this.params = params;
28922
+ this.mapWith(Number);
28923
+ this.session = params.session;
28924
+ this.sql = _PgCountBuilder.buildCount(
28925
+ params.source,
28926
+ params.filters
28891
28927
  );
28892
28928
  }
28893
- onOnly(...columns) {
28894
- return new IndexBuilder(
28895
- columns.map((it) => {
28896
- if (is(it, SQL)) {
28897
- return it;
28898
- }
28899
- it = it;
28900
- const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);
28901
- it.indexConfig = it.defaultConfig;
28902
- return clonedIndexedColumn;
28903
- }),
28904
- this.unique,
28905
- true,
28906
- this.name
28929
+ static buildEmbeddedCount(source, filters) {
28930
+ return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`;
28931
+ }
28932
+ static buildCount(source, filters) {
28933
+ return sql`select count(*) as count from ${source}${sql.raw(" where ").if(filters)}${filters};`;
28934
+ }
28935
+ /** @intrnal */
28936
+ setToken(token) {
28937
+ this.token = token;
28938
+ return this;
28939
+ }
28940
+ then(onfulfilled, onrejected) {
28941
+ return Promise.resolve(this.session.count(this.sql, this.token)).then(
28942
+ onfulfilled,
28943
+ onrejected
28907
28944
  );
28908
28945
  }
28909
- /**
28910
- * Specify what index method to use. Choices are `btree`, `hash`, `gist`, `spgist`, `gin`, `brin`, or user-installed access methods like `bloom`. The default method is `btree.
28911
- *
28912
- * If you have the `pg_vector` extension installed in your database, you can use the `hnsw` and `ivfflat` options, which are predefined types.
28913
- *
28914
- * **You can always specify any string you want in the method, in case Drizzle doesn't have it natively in its types**
28915
- *
28916
- * @param method The name of the index method to be used
28917
- * @param columns
28918
- * @returns
28919
- */
28920
- using(method, ...columns) {
28921
- return new IndexBuilder(
28922
- columns.map((it) => {
28923
- if (is(it, SQL)) {
28924
- return it;
28925
- }
28926
- it = it;
28927
- const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);
28928
- it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig));
28929
- return clonedIndexedColumn;
28930
- }),
28931
- this.unique,
28932
- true,
28933
- this.name,
28934
- method
28946
+ catch(onRejected) {
28947
+ return this.then(void 0, onRejected);
28948
+ }
28949
+ finally(onFinally) {
28950
+ return this.then(
28951
+ (value) => {
28952
+ onFinally?.();
28953
+ return value;
28954
+ },
28955
+ (reason) => {
28956
+ onFinally?.();
28957
+ throw reason;
28958
+ }
28935
28959
  );
28936
28960
  }
28937
28961
  };
28938
- __publicField(IndexBuilderOn, _a144, "PgIndexBuilderOn");
28939
- _a145 = entityKind;
28940
- IndexBuilder = class {
28941
- constructor(columns, unique, only, name2, method = "btree") {
28942
- /** @internal */
28943
- __publicField(this, "config");
28944
- this.config = {
28945
- name: name2,
28946
- columns,
28947
- unique,
28948
- only,
28949
- method
28950
- };
28962
+ __publicField(_PgCountBuilder, _b110, "PgCountBuilder");
28963
+ PgCountBuilder = _PgCountBuilder;
28964
+ }
28965
+ });
28966
+
28967
+ // ../drizzle-orm/dist/pg-core/query-builders/query.js
28968
+ var _a152, RelationalQueryBuilder, _a153, _b111, PgRelationalQuery;
28969
+ var init_query = __esm({
28970
+ "../drizzle-orm/dist/pg-core/query-builders/query.js"() {
28971
+ "use strict";
28972
+ init_entity();
28973
+ init_query_promise();
28974
+ init_relations();
28975
+ init_tracing();
28976
+ _a152 = entityKind;
28977
+ RelationalQueryBuilder = class {
28978
+ constructor(fullSchema, schema5, tableNamesMap, table5, tableConfig, dialect6, session) {
28979
+ this.fullSchema = fullSchema;
28980
+ this.schema = schema5;
28981
+ this.tableNamesMap = tableNamesMap;
28982
+ this.table = table5;
28983
+ this.tableConfig = tableConfig;
28984
+ this.dialect = dialect6;
28985
+ this.session = session;
28951
28986
  }
28952
- concurrently() {
28953
- this.config.concurrently = true;
28954
- return this;
28987
+ findMany(config) {
28988
+ return new PgRelationalQuery(
28989
+ this.fullSchema,
28990
+ this.schema,
28991
+ this.tableNamesMap,
28992
+ this.table,
28993
+ this.tableConfig,
28994
+ this.dialect,
28995
+ this.session,
28996
+ config ? config : {},
28997
+ "many"
28998
+ );
28955
28999
  }
28956
- with(obj) {
28957
- this.config.with = obj;
28958
- return this;
29000
+ findFirst(config) {
29001
+ return new PgRelationalQuery(
29002
+ this.fullSchema,
29003
+ this.schema,
29004
+ this.tableNamesMap,
29005
+ this.table,
29006
+ this.tableConfig,
29007
+ this.dialect,
29008
+ this.session,
29009
+ config ? { ...config, limit: 1 } : { limit: 1 },
29010
+ "first"
29011
+ );
28959
29012
  }
28960
- where(condition) {
28961
- this.config.where = condition;
28962
- return this;
29013
+ };
29014
+ __publicField(RelationalQueryBuilder, _a152, "PgRelationalQueryBuilder");
29015
+ PgRelationalQuery = class extends (_b111 = QueryPromise, _a153 = entityKind, _b111) {
29016
+ constructor(fullSchema, schema5, tableNamesMap, table5, tableConfig, dialect6, session, config, mode) {
29017
+ super();
29018
+ __publicField(this, "authToken");
29019
+ this.fullSchema = fullSchema;
29020
+ this.schema = schema5;
29021
+ this.tableNamesMap = tableNamesMap;
29022
+ this.table = table5;
29023
+ this.tableConfig = tableConfig;
29024
+ this.dialect = dialect6;
29025
+ this.session = session;
29026
+ this.config = config;
29027
+ this.mode = mode;
28963
29028
  }
28964
29029
  /** @internal */
28965
- build(table5) {
28966
- return new Index2(this.config, table5);
29030
+ _prepare(name2) {
29031
+ return tracer.startActiveSpan("drizzle.prepareQuery", () => {
29032
+ const { query, builtQuery } = this._toSQL();
29033
+ return this.session.prepareQuery(
29034
+ builtQuery,
29035
+ void 0,
29036
+ name2,
29037
+ true,
29038
+ (rawRows, mapColumnValue) => {
29039
+ const rows = rawRows.map(
29040
+ (row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue)
29041
+ );
29042
+ if (this.mode === "first") {
29043
+ return rows[0];
29044
+ }
29045
+ return rows;
29046
+ }
29047
+ );
29048
+ });
28967
29049
  }
28968
- };
28969
- __publicField(IndexBuilder, _a145, "PgIndexBuilder");
28970
- _a146 = entityKind;
28971
- Index2 = class {
28972
- constructor(config, table5) {
28973
- __publicField(this, "config");
28974
- this.config = { ...config, table: table5 };
29050
+ prepare(name2) {
29051
+ return this._prepare(name2);
28975
29052
  }
28976
- };
28977
- __publicField(Index2, _a146, "PgIndex");
28978
- }
28979
- });
28980
-
28981
- // ../drizzle-orm/dist/pg-core/policies.js
28982
- var _a147, PgPolicy;
28983
- var init_policies = __esm({
28984
- "../drizzle-orm/dist/pg-core/policies.js"() {
28985
- "use strict";
28986
- init_entity();
28987
- _a147 = entityKind;
28988
- PgPolicy = class {
28989
- constructor(name2, config) {
28990
- __publicField(this, "as");
28991
- __publicField(this, "for");
28992
- __publicField(this, "to");
28993
- __publicField(this, "using");
28994
- __publicField(this, "withCheck");
28995
- /** @internal */
28996
- __publicField(this, "_linkedTable");
28997
- this.name = name2;
28998
- if (config) {
28999
- this.as = config.as;
29000
- this.for = config.for;
29001
- this.to = config.to;
29002
- this.using = config.using;
29003
- this.withCheck = config.withCheck;
29004
- }
29053
+ _getQuery() {
29054
+ return this.dialect.buildRelationalQueryWithoutPK({
29055
+ fullSchema: this.fullSchema,
29056
+ schema: this.schema,
29057
+ tableNamesMap: this.tableNamesMap,
29058
+ table: this.table,
29059
+ tableConfig: this.tableConfig,
29060
+ queryConfig: this.config,
29061
+ tableAlias: this.tableConfig.tsName
29062
+ });
29005
29063
  }
29006
- link(table5) {
29007
- this._linkedTable = table5;
29064
+ /** @internal */
29065
+ getSQL() {
29066
+ return this._getQuery().sql;
29067
+ }
29068
+ _toSQL() {
29069
+ const query = this._getQuery();
29070
+ const builtQuery = this.dialect.sqlToQuery(query.sql);
29071
+ return { query, builtQuery };
29072
+ }
29073
+ toSQL() {
29074
+ return this._toSQL().builtQuery;
29075
+ }
29076
+ /** @internal */
29077
+ setToken(token) {
29078
+ this.authToken = token;
29008
29079
  return this;
29009
29080
  }
29081
+ execute() {
29082
+ return tracer.startActiveSpan("drizzle.operation", () => {
29083
+ return this._prepare().execute(void 0, this.authToken);
29084
+ });
29085
+ }
29010
29086
  };
29011
- __publicField(PgPolicy, _a147, "PgPolicy");
29087
+ __publicField(PgRelationalQuery, _a153, "PgRelationalQuery");
29012
29088
  }
29013
29089
  });
29014
29090
 
29015
- // ../drizzle-orm/dist/pg-core/roles.js
29016
- var _a148, PgRole;
29017
- var init_roles = __esm({
29018
- "../drizzle-orm/dist/pg-core/roles.js"() {
29091
+ // ../drizzle-orm/dist/pg-core/query-builders/raw.js
29092
+ var _a154, _b112, PgRaw;
29093
+ var init_raw = __esm({
29094
+ "../drizzle-orm/dist/pg-core/query-builders/raw.js"() {
29019
29095
  "use strict";
29020
29096
  init_entity();
29021
- _a148 = entityKind;
29022
- PgRole = class {
29023
- constructor(name2, config) {
29024
- /** @internal */
29025
- __publicField(this, "_existing");
29026
- /** @internal */
29027
- __publicField(this, "createDb");
29028
- /** @internal */
29029
- __publicField(this, "createRole");
29030
- /** @internal */
29031
- __publicField(this, "inherit");
29032
- this.name = name2;
29033
- if (config) {
29034
- this.createDb = config.createDb;
29035
- this.createRole = config.createRole;
29036
- this.inherit = config.inherit;
29037
- }
29097
+ init_query_promise();
29098
+ PgRaw = class extends (_b112 = QueryPromise, _a154 = entityKind, _b112) {
29099
+ constructor(execute, sql2, query, mapBatchResult) {
29100
+ super();
29101
+ this.execute = execute;
29102
+ this.sql = sql2;
29103
+ this.query = query;
29104
+ this.mapBatchResult = mapBatchResult;
29038
29105
  }
29039
- existing() {
29040
- this._existing = true;
29106
+ /** @internal */
29107
+ getSQL() {
29108
+ return this.sql;
29109
+ }
29110
+ getQuery() {
29111
+ return this.query;
29112
+ }
29113
+ mapResult(result, isFromBatch) {
29114
+ return isFromBatch ? this.mapBatchResult(result) : result;
29115
+ }
29116
+ _prepare() {
29041
29117
  return this;
29042
29118
  }
29119
+ /** @internal */
29120
+ isResponseInArrayMode() {
29121
+ return false;
29122
+ }
29043
29123
  };
29044
- __publicField(PgRole, _a148, "PgRole");
29124
+ __publicField(PgRaw, _a154, "PgRaw");
29045
29125
  }
29046
29126
  });
29047
29127
 
29048
- // ../drizzle-orm/dist/pg-core/sequence.js
29049
- function pgSequenceWithSchema(name2, options, schema5) {
29050
- return new PgSequence(name2, options, schema5);
29051
- }
29052
- function isPgSequence(obj) {
29053
- return is(obj, PgSequence);
29054
- }
29055
- var _a149, PgSequence;
29056
- var init_sequence = __esm({
29057
- "../drizzle-orm/dist/pg-core/sequence.js"() {
29058
- "use strict";
29059
- init_entity();
29060
- _a149 = entityKind;
29061
- PgSequence = class {
29062
- constructor(seqName, seqOptions, schema5) {
29063
- this.seqName = seqName;
29064
- this.seqOptions = seqOptions;
29065
- this.schema = schema5;
29066
- }
29067
- };
29068
- __publicField(PgSequence, _a149, "PgSequence");
29069
- }
29070
- });
29071
-
29072
- // ../drizzle-orm/dist/pg-core/view-common.js
29073
- var PgViewConfig;
29074
- var init_view_common2 = __esm({
29075
- "../drizzle-orm/dist/pg-core/view-common.js"() {
29076
- "use strict";
29077
- PgViewConfig = Symbol.for("drizzle:PgViewConfig");
29078
- }
29079
- });
29080
-
29081
- // ../drizzle-orm/dist/pg-core/view.js
29082
- function pgViewWithSchema(name2, selection, schema5) {
29083
- if (selection) {
29084
- return new ManualViewBuilder(name2, selection, schema5);
29085
- }
29086
- return new ViewBuilder(name2, schema5);
29087
- }
29088
- function pgMaterializedViewWithSchema(name2, selection, schema5) {
29089
- if (selection) {
29090
- return new ManualMaterializedViewBuilder(name2, selection, schema5);
29091
- }
29092
- return new MaterializedViewBuilder(name2, schema5);
29093
- }
29094
- function isPgView(obj) {
29095
- return is(obj, PgView2);
29096
- }
29097
- function isPgMaterializedView(obj) {
29098
- return is(obj, PgMaterializedView);
29099
- }
29100
- var _a150, DefaultViewBuilderCore, _a151, _b107, ViewBuilder, _a152, _b108, ManualViewBuilder, _a153, MaterializedViewBuilderCore, _a154, _b109, MaterializedViewBuilder, _a155, _b110, ManualMaterializedViewBuilder, _a156, _b111, _c5, PgView2, PgMaterializedViewConfig, _a157, _b112, _c6, PgMaterializedView;
29101
- var init_view = __esm({
29102
- "../drizzle-orm/dist/pg-core/view.js"() {
29128
+ // ../drizzle-orm/dist/pg-core/db.js
29129
+ var _a155, PgDatabase;
29130
+ var init_db = __esm({
29131
+ "../drizzle-orm/dist/pg-core/db.js"() {
29103
29132
  "use strict";
29104
29133
  init_entity();
29134
+ init_query_builders();
29105
29135
  init_selection_proxy();
29106
- init_utils2();
29107
- init_query_builder2();
29108
- init_table2();
29109
- init_view_base();
29110
- init_view_common2();
29111
- _a150 = entityKind;
29112
- DefaultViewBuilderCore = class {
29113
- constructor(name2, schema5) {
29114
- __publicField(this, "config", {});
29115
- this.name = name2;
29116
- this.schema = schema5;
29136
+ init_sql();
29137
+ init_subquery();
29138
+ init_count();
29139
+ init_query();
29140
+ init_raw();
29141
+ init_refresh_materialized_view();
29142
+ _a155 = entityKind;
29143
+ PgDatabase = class {
29144
+ constructor(dialect6, session, schema5) {
29145
+ __publicField(this, "query");
29146
+ /**
29147
+ * Creates a subquery that defines a temporary named result set as a CTE.
29148
+ *
29149
+ * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.
29150
+ *
29151
+ * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
29152
+ *
29153
+ * @param alias The alias for the subquery.
29154
+ *
29155
+ * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.
29156
+ *
29157
+ * @example
29158
+ *
29159
+ * ```ts
29160
+ * // Create a subquery with alias 'sq' and use it in the select query
29161
+ * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
29162
+ *
29163
+ * const result = await db.with(sq).select().from(sq);
29164
+ * ```
29165
+ *
29166
+ * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:
29167
+ *
29168
+ * ```ts
29169
+ * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query
29170
+ * const sq = db.$with('sq').as(db.select({
29171
+ * name: sql<string>`upper(${users.name})`.as('name'),
29172
+ * })
29173
+ * .from(users));
29174
+ *
29175
+ * const result = await db.with(sq).select({ name: sq.name }).from(sq);
29176
+ * ```
29177
+ */
29178
+ __publicField(this, "$with", (alias, selection) => {
29179
+ const self2 = this;
29180
+ const as = (qb) => {
29181
+ if (typeof qb === "function") {
29182
+ qb = qb(new QueryBuilder(self2.dialect));
29183
+ }
29184
+ return new Proxy(
29185
+ new WithSubquery(
29186
+ qb.getSQL(),
29187
+ selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}),
29188
+ alias,
29189
+ true
29190
+ ),
29191
+ new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
29192
+ );
29193
+ };
29194
+ return { as };
29195
+ });
29196
+ __publicField(this, "$cache");
29197
+ __publicField(this, "authToken");
29198
+ this.dialect = dialect6;
29199
+ this.session = session;
29200
+ this._ = schema5 ? {
29201
+ schema: schema5.schema,
29202
+ fullSchema: schema5.fullSchema,
29203
+ tableNamesMap: schema5.tableNamesMap,
29204
+ session
29205
+ } : {
29206
+ schema: void 0,
29207
+ fullSchema: {},
29208
+ tableNamesMap: {},
29209
+ session
29210
+ };
29211
+ this.query = {};
29212
+ if (this._.schema) {
29213
+ for (const [tableName, columns] of Object.entries(this._.schema)) {
29214
+ this.query[tableName] = new RelationalQueryBuilder(
29215
+ schema5.fullSchema,
29216
+ this._.schema,
29217
+ this._.tableNamesMap,
29218
+ schema5.fullSchema[tableName],
29219
+ columns,
29220
+ dialect6,
29221
+ session
29222
+ );
29223
+ }
29224
+ }
29117
29225
  }
29118
- with(config) {
29119
- this.config.with = config;
29120
- return this;
29226
+ $count(source, filters) {
29227
+ return new PgCountBuilder({ source, filters, session: this.session });
29121
29228
  }
29122
- };
29123
- __publicField(DefaultViewBuilderCore, _a150, "PgDefaultViewBuilderCore");
29124
- ViewBuilder = class extends (_b107 = DefaultViewBuilderCore, _a151 = entityKind, _b107) {
29125
- as(qb) {
29126
- if (typeof qb === "function") {
29127
- qb = qb(new QueryBuilder());
29229
+ /**
29230
+ * Incorporates a previously defined CTE (using `$with`) into the main query.
29231
+ *
29232
+ * This method allows the main query to reference a temporary named result set.
29233
+ *
29234
+ * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
29235
+ *
29236
+ * @param queries The CTEs to incorporate into the main query.
29237
+ *
29238
+ * @example
29239
+ *
29240
+ * ```ts
29241
+ * // Define a subquery 'sq' as a CTE using $with
29242
+ * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
29243
+ *
29244
+ * // Incorporate the CTE 'sq' into the main query and select from it
29245
+ * const result = await db.with(sq).select().from(sq);
29246
+ * ```
29247
+ */
29248
+ with(...queries) {
29249
+ const self2 = this;
29250
+ function select(fields) {
29251
+ return new PgSelectBuilder({
29252
+ fields: fields ?? void 0,
29253
+ session: self2.session,
29254
+ dialect: self2.dialect,
29255
+ withList: queries
29256
+ });
29128
29257
  }
29129
- const selectionProxy = new SelectionProxyHandler({
29130
- alias: this.name,
29131
- sqlBehavior: "error",
29132
- sqlAliasedBehavior: "alias",
29133
- replaceOriginalName: true
29134
- });
29135
- const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);
29136
- return new Proxy(
29137
- new PgView2({
29138
- pgConfig: this.config,
29139
- config: {
29140
- name: this.name,
29141
- schema: this.schema,
29142
- selectedFields: aliasedSelection,
29143
- query: qb.getSQL().inlineParams()
29144
- }
29145
- }),
29146
- selectionProxy
29147
- );
29148
- }
29149
- };
29150
- __publicField(ViewBuilder, _a151, "PgViewBuilder");
29151
- ManualViewBuilder = class extends (_b108 = DefaultViewBuilderCore, _a152 = entityKind, _b108) {
29152
- constructor(name2, columns, schema5) {
29153
- super(name2, schema5);
29154
- __publicField(this, "columns");
29155
- this.columns = getTableColumns(pgTable(name2, columns));
29258
+ function selectDistinct(fields) {
29259
+ return new PgSelectBuilder({
29260
+ fields: fields ?? void 0,
29261
+ session: self2.session,
29262
+ dialect: self2.dialect,
29263
+ withList: queries,
29264
+ distinct: true
29265
+ });
29266
+ }
29267
+ function selectDistinctOn(on, fields) {
29268
+ return new PgSelectBuilder({
29269
+ fields: fields ?? void 0,
29270
+ session: self2.session,
29271
+ dialect: self2.dialect,
29272
+ withList: queries,
29273
+ distinct: { on }
29274
+ });
29275
+ }
29276
+ function update(table5) {
29277
+ return new PgUpdateBuilder(table5, self2.session, self2.dialect, queries);
29278
+ }
29279
+ function insert(table5) {
29280
+ return new PgInsertBuilder(table5, self2.session, self2.dialect, queries);
29281
+ }
29282
+ function delete_(table5) {
29283
+ return new PgDeleteBase(table5, self2.session, self2.dialect, queries);
29284
+ }
29285
+ return { select, selectDistinct, selectDistinctOn, update, insert, delete: delete_ };
29156
29286
  }
29157
- existing() {
29158
- return new Proxy(
29159
- new PgView2({
29160
- pgConfig: void 0,
29161
- config: {
29162
- name: this.name,
29163
- schema: this.schema,
29164
- selectedFields: this.columns,
29165
- query: void 0
29166
- }
29167
- }),
29168
- new SelectionProxyHandler({
29169
- alias: this.name,
29170
- sqlBehavior: "error",
29171
- sqlAliasedBehavior: "alias",
29172
- replaceOriginalName: true
29173
- })
29174
- );
29287
+ select(fields) {
29288
+ return new PgSelectBuilder({
29289
+ fields: fields ?? void 0,
29290
+ session: this.session,
29291
+ dialect: this.dialect
29292
+ });
29175
29293
  }
29176
- as(query) {
29177
- return new Proxy(
29178
- new PgView2({
29179
- pgConfig: this.config,
29180
- config: {
29181
- name: this.name,
29182
- schema: this.schema,
29183
- selectedFields: this.columns,
29184
- query: query.inlineParams()
29185
- }
29186
- }),
29187
- new SelectionProxyHandler({
29188
- alias: this.name,
29189
- sqlBehavior: "error",
29190
- sqlAliasedBehavior: "alias",
29191
- replaceOriginalName: true
29192
- })
29193
- );
29294
+ selectDistinct(fields) {
29295
+ return new PgSelectBuilder({
29296
+ fields: fields ?? void 0,
29297
+ session: this.session,
29298
+ dialect: this.dialect,
29299
+ distinct: true
29300
+ });
29194
29301
  }
29195
- };
29196
- __publicField(ManualViewBuilder, _a152, "PgManualViewBuilder");
29197
- _a153 = entityKind;
29198
- MaterializedViewBuilderCore = class {
29199
- constructor(name2, schema5) {
29200
- __publicField(this, "config", {});
29201
- this.name = name2;
29202
- this.schema = schema5;
29302
+ selectDistinctOn(on, fields) {
29303
+ return new PgSelectBuilder({
29304
+ fields: fields ?? void 0,
29305
+ session: this.session,
29306
+ dialect: this.dialect,
29307
+ distinct: { on }
29308
+ });
29203
29309
  }
29204
- using(using) {
29205
- this.config.using = using;
29206
- return this;
29310
+ /**
29311
+ * Creates an update query.
29312
+ *
29313
+ * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.
29314
+ *
29315
+ * Use `.set()` method to specify which values to update.
29316
+ *
29317
+ * See docs: {@link https://orm.drizzle.team/docs/update}
29318
+ *
29319
+ * @param table The table to update.
29320
+ *
29321
+ * @example
29322
+ *
29323
+ * ```ts
29324
+ * // Update all rows in the 'cars' table
29325
+ * await db.update(cars).set({ color: 'red' });
29326
+ *
29327
+ * // Update rows with filters and conditions
29328
+ * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));
29329
+ *
29330
+ * // Update with returning clause
29331
+ * const updatedCar: Car[] = await db.update(cars)
29332
+ * .set({ color: 'red' })
29333
+ * .where(eq(cars.id, 1))
29334
+ * .returning();
29335
+ * ```
29336
+ */
29337
+ update(table5) {
29338
+ return new PgUpdateBuilder(table5, this.session, this.dialect);
29207
29339
  }
29208
- with(config) {
29209
- this.config.with = config;
29210
- return this;
29340
+ /**
29341
+ * Creates an insert query.
29342
+ *
29343
+ * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.
29344
+ *
29345
+ * See docs: {@link https://orm.drizzle.team/docs/insert}
29346
+ *
29347
+ * @param table The table to insert into.
29348
+ *
29349
+ * @example
29350
+ *
29351
+ * ```ts
29352
+ * // Insert one row
29353
+ * await db.insert(cars).values({ brand: 'BMW' });
29354
+ *
29355
+ * // Insert multiple rows
29356
+ * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);
29357
+ *
29358
+ * // Insert with returning clause
29359
+ * const insertedCar: Car[] = await db.insert(cars)
29360
+ * .values({ brand: 'BMW' })
29361
+ * .returning();
29362
+ * ```
29363
+ */
29364
+ insert(table5) {
29365
+ return new PgInsertBuilder(table5, this.session, this.dialect);
29211
29366
  }
29212
- tablespace(tablespace) {
29213
- this.config.tablespace = tablespace;
29214
- return this;
29367
+ /**
29368
+ * Creates a delete query.
29369
+ *
29370
+ * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.
29371
+ *
29372
+ * See docs: {@link https://orm.drizzle.team/docs/delete}
29373
+ *
29374
+ * @param table The table to delete from.
29375
+ *
29376
+ * @example
29377
+ *
29378
+ * ```ts
29379
+ * // Delete all rows in the 'cars' table
29380
+ * await db.delete(cars);
29381
+ *
29382
+ * // Delete rows with filters and conditions
29383
+ * await db.delete(cars).where(eq(cars.color, 'green'));
29384
+ *
29385
+ * // Delete with returning clause
29386
+ * const deletedCar: Car[] = await db.delete(cars)
29387
+ * .where(eq(cars.id, 1))
29388
+ * .returning();
29389
+ * ```
29390
+ */
29391
+ delete(table5) {
29392
+ return new PgDeleteBase(table5, this.session, this.dialect);
29215
29393
  }
29216
- withNoData() {
29217
- this.config.withNoData = true;
29218
- return this;
29394
+ refreshMaterializedView(view4) {
29395
+ return new PgRefreshMaterializedView(view4, this.session, this.dialect);
29219
29396
  }
29220
- };
29221
- __publicField(MaterializedViewBuilderCore, _a153, "PgMaterializedViewBuilderCore");
29222
- MaterializedViewBuilder = class extends (_b109 = MaterializedViewBuilderCore, _a154 = entityKind, _b109) {
29223
- as(qb) {
29224
- if (typeof qb === "function") {
29225
- qb = qb(new QueryBuilder());
29226
- }
29227
- const selectionProxy = new SelectionProxyHandler({
29228
- alias: this.name,
29229
- sqlBehavior: "error",
29230
- sqlAliasedBehavior: "alias",
29231
- replaceOriginalName: true
29232
- });
29233
- const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);
29234
- return new Proxy(
29235
- new PgMaterializedView({
29236
- pgConfig: {
29237
- with: this.config.with,
29238
- using: this.config.using,
29239
- tablespace: this.config.tablespace,
29240
- withNoData: this.config.withNoData
29241
- },
29242
- config: {
29243
- name: this.name,
29244
- schema: this.schema,
29245
- selectedFields: aliasedSelection,
29246
- query: qb.getSQL().inlineParams()
29247
- }
29248
- }),
29249
- selectionProxy
29397
+ execute(query) {
29398
+ const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
29399
+ const builtQuery = this.dialect.sqlToQuery(sequel);
29400
+ const prepared = this.session.prepareQuery(
29401
+ builtQuery,
29402
+ void 0,
29403
+ void 0,
29404
+ false
29250
29405
  );
29251
- }
29252
- };
29253
- __publicField(MaterializedViewBuilder, _a154, "PgMaterializedViewBuilder");
29254
- ManualMaterializedViewBuilder = class extends (_b110 = MaterializedViewBuilderCore, _a155 = entityKind, _b110) {
29255
- constructor(name2, columns, schema5) {
29256
- super(name2, schema5);
29257
- __publicField(this, "columns");
29258
- this.columns = getTableColumns(pgTable(name2, columns));
29259
- }
29260
- existing() {
29261
- return new Proxy(
29262
- new PgMaterializedView({
29263
- pgConfig: {
29264
- tablespace: this.config.tablespace,
29265
- using: this.config.using,
29266
- with: this.config.with,
29267
- withNoData: this.config.withNoData
29268
- },
29269
- config: {
29270
- name: this.name,
29271
- schema: this.schema,
29272
- selectedFields: this.columns,
29273
- query: void 0
29274
- }
29275
- }),
29276
- new SelectionProxyHandler({
29277
- alias: this.name,
29278
- sqlBehavior: "error",
29279
- sqlAliasedBehavior: "alias",
29280
- replaceOriginalName: true
29281
- })
29406
+ return new PgRaw(
29407
+ () => prepared.execute(void 0, this.authToken),
29408
+ sequel,
29409
+ builtQuery,
29410
+ (result) => prepared.mapResult(result, true)
29282
29411
  );
29283
29412
  }
29284
- as(query) {
29285
- return new Proxy(
29286
- new PgMaterializedView({
29287
- pgConfig: {
29288
- tablespace: this.config.tablespace,
29289
- using: this.config.using,
29290
- with: this.config.with,
29291
- withNoData: this.config.withNoData
29292
- },
29293
- config: {
29294
- name: this.name,
29295
- schema: this.schema,
29296
- selectedFields: this.columns,
29297
- query: query.inlineParams()
29298
- }
29299
- }),
29300
- new SelectionProxyHandler({
29301
- alias: this.name,
29302
- sqlBehavior: "error",
29303
- sqlAliasedBehavior: "alias",
29304
- replaceOriginalName: true
29305
- })
29306
- );
29413
+ transaction(transaction, config) {
29414
+ return this.session.transaction(transaction, config);
29307
29415
  }
29308
29416
  };
29309
- __publicField(ManualMaterializedViewBuilder, _a155, "PgManualMaterializedViewBuilder");
29310
- PgView2 = class extends (_c5 = PgViewBase, _b111 = entityKind, _a156 = PgViewConfig, _c5) {
29311
- constructor({ pgConfig, config }) {
29312
- super(config);
29313
- __publicField(this, _a156);
29314
- if (pgConfig) {
29315
- this[PgViewConfig] = {
29316
- with: pgConfig.with
29317
- };
29417
+ __publicField(PgDatabase, _a155, "PgDatabase");
29418
+ }
29419
+ });
29420
+
29421
+ // ../drizzle-orm/dist/pg-core/roles.js
29422
+ var _a156, PgRole;
29423
+ var init_roles = __esm({
29424
+ "../drizzle-orm/dist/pg-core/roles.js"() {
29425
+ "use strict";
29426
+ init_entity();
29427
+ _a156 = entityKind;
29428
+ PgRole = class {
29429
+ constructor(name2, config) {
29430
+ /** @internal */
29431
+ __publicField(this, "_existing");
29432
+ /** @internal */
29433
+ __publicField(this, "createDb");
29434
+ /** @internal */
29435
+ __publicField(this, "createRole");
29436
+ /** @internal */
29437
+ __publicField(this, "inherit");
29438
+ this.name = name2;
29439
+ if (config) {
29440
+ this.createDb = config.createDb;
29441
+ this.createRole = config.createRole;
29442
+ this.inherit = config.inherit;
29318
29443
  }
29319
29444
  }
29445
+ existing() {
29446
+ this._existing = true;
29447
+ return this;
29448
+ }
29320
29449
  };
29321
- __publicField(PgView2, _b111, "PgView");
29322
- PgMaterializedViewConfig = Symbol.for("drizzle:PgMaterializedViewConfig");
29323
- PgMaterializedView = class extends (_c6 = PgViewBase, _b112 = entityKind, _a157 = PgMaterializedViewConfig, _c6) {
29324
- constructor({ pgConfig, config }) {
29325
- super(config);
29326
- __publicField(this, _a157);
29327
- this[PgMaterializedViewConfig] = {
29328
- with: pgConfig?.with,
29329
- using: pgConfig?.using,
29330
- tablespace: pgConfig?.tablespace,
29331
- withNoData: pgConfig?.withNoData
29332
- };
29450
+ __publicField(PgRole, _a156, "PgRole");
29451
+ }
29452
+ });
29453
+
29454
+ // ../drizzle-orm/dist/pg-core/sequence.js
29455
+ function pgSequenceWithSchema(name2, options, schema5) {
29456
+ return new PgSequence(name2, options, schema5);
29457
+ }
29458
+ function isPgSequence(obj) {
29459
+ return is(obj, PgSequence);
29460
+ }
29461
+ var _a157, PgSequence;
29462
+ var init_sequence = __esm({
29463
+ "../drizzle-orm/dist/pg-core/sequence.js"() {
29464
+ "use strict";
29465
+ init_entity();
29466
+ _a157 = entityKind;
29467
+ PgSequence = class {
29468
+ constructor(seqName, seqOptions, schema5) {
29469
+ this.seqName = seqName;
29470
+ this.seqOptions = seqOptions;
29471
+ this.schema = schema5;
29333
29472
  }
29334
29473
  };
29335
- __publicField(PgMaterializedView, _b112, "PgMaterializedView");
29474
+ __publicField(PgSequence, _a157, "PgSequence");
29336
29475
  }
29337
29476
  });
29338
29477
 
@@ -29390,11 +29529,20 @@ var init_session = __esm({
29390
29529
  init_db();
29391
29530
  _a159 = entityKind;
29392
29531
  PgPreparedQuery = class {
29393
- constructor(query) {
29532
+ constructor(query, cache, queryMetadata, cacheConfig) {
29394
29533
  __publicField(this, "authToken");
29395
29534
  /** @internal */
29396
29535
  __publicField(this, "joinsNotNullableMap");
29397
29536
  this.query = query;
29537
+ this.cache = cache;
29538
+ this.queryMetadata = queryMetadata;
29539
+ this.cacheConfig = cacheConfig;
29540
+ if (cache && cache.strategy() === "all" && cacheConfig === void 0) {
29541
+ this.cacheConfig = { enable: true, autoInvalidate: true };
29542
+ }
29543
+ if (!this.cacheConfig?.enable) {
29544
+ this.cacheConfig = void 0;
29545
+ }
29398
29546
  }
29399
29547
  getQuery() {
29400
29548
  return this.query;
@@ -29407,6 +29555,49 @@ var init_session = __esm({
29407
29555
  this.authToken = token;
29408
29556
  return this;
29409
29557
  }
29558
+ async hashQuery(sql2, params) {
29559
+ const dataToHash = `${sql2}-${JSON.stringify(params)}`;
29560
+ const encoder = new TextEncoder();
29561
+ const data = encoder.encode(dataToHash);
29562
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
29563
+ const hashArray = [...new Uint8Array(hashBuffer)];
29564
+ const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
29565
+ return hashHex;
29566
+ }
29567
+ /** @internal */
29568
+ async queryWithCache(queryString, params, query) {
29569
+ if (this.cache === void 0 || this.queryMetadata === void 0) {
29570
+ return await query();
29571
+ }
29572
+ if (this.cacheConfig && !this.cacheConfig.enable) {
29573
+ return await query();
29574
+ }
29575
+ if ((this.queryMetadata.type === "insert" || this.queryMetadata.type === "update" || this.queryMetadata.type === "delete") && this.queryMetadata.tables.length > 0) {
29576
+ await this.cache.onMutate({ tables: this.queryMetadata.tables });
29577
+ }
29578
+ if (!this.cacheConfig) {
29579
+ return await query();
29580
+ }
29581
+ if (this.queryMetadata.type === "select") {
29582
+ const fromCache = await this.cache.get(
29583
+ this.cacheConfig.tag ?? await this.hashQuery(queryString, params)
29584
+ );
29585
+ if (fromCache === void 0) {
29586
+ console.log("Cache empty. Querying database", queryString);
29587
+ const result = await query();
29588
+ await this.cache.put(
29589
+ this.cacheConfig.tag ?? await this.hashQuery(queryString, params),
29590
+ result,
29591
+ // make sure we send tables that were used in a query only if user wants to invalidate it on each write
29592
+ this.cacheConfig.autoInvalidate ? this.queryMetadata.tables : [],
29593
+ this.cacheConfig.config
29594
+ );
29595
+ return result;
29596
+ }
29597
+ return fromCache;
29598
+ }
29599
+ return await query();
29600
+ }
29410
29601
  };
29411
29602
  __publicField(PgPreparedQuery, _a159, "PgPreparedQuery");
29412
29603
  _a160 = entityKind;
@@ -29483,81 +29674,6 @@ var init_subquery2 = __esm({
29483
29674
  }
29484
29675
  });
29485
29676
 
29486
- // ../drizzle-orm/dist/pg-core/utils.js
29487
- function getTableConfig(table5) {
29488
- const columns = Object.values(table5[Table2.Symbol.Columns]);
29489
- const indexes = [];
29490
- const checks = [];
29491
- const primaryKeys = [];
29492
- const foreignKeys = Object.values(table5[PgTable.Symbol.InlineForeignKeys]);
29493
- const uniqueConstraints = [];
29494
- const name2 = table5[Table2.Symbol.Name];
29495
- const schema5 = table5[Table2.Symbol.Schema];
29496
- const policies = [];
29497
- const enableRLS = table5[PgTable.Symbol.EnableRLS];
29498
- const extraConfigBuilder = table5[PgTable.Symbol.ExtraConfigBuilder];
29499
- if (extraConfigBuilder !== void 0) {
29500
- const extraConfig = extraConfigBuilder(table5[Table2.Symbol.ExtraConfigColumns]);
29501
- const extraValues = Array.isArray(extraConfig) ? extraConfig.flat(1) : Object.values(extraConfig);
29502
- for (const builder of extraValues) {
29503
- if (is(builder, IndexBuilder)) {
29504
- indexes.push(builder.build(table5));
29505
- } else if (is(builder, CheckBuilder)) {
29506
- checks.push(builder.build(table5));
29507
- } else if (is(builder, UniqueConstraintBuilder)) {
29508
- uniqueConstraints.push(builder.build(table5));
29509
- } else if (is(builder, PrimaryKeyBuilder)) {
29510
- primaryKeys.push(builder.build(table5));
29511
- } else if (is(builder, ForeignKeyBuilder)) {
29512
- foreignKeys.push(builder.build(table5));
29513
- } else if (is(builder, PgPolicy)) {
29514
- policies.push(builder);
29515
- }
29516
- }
29517
- }
29518
- return {
29519
- columns,
29520
- indexes,
29521
- foreignKeys,
29522
- checks,
29523
- primaryKeys,
29524
- uniqueConstraints,
29525
- name: name2,
29526
- schema: schema5,
29527
- policies,
29528
- enableRLS
29529
- };
29530
- }
29531
- function getViewConfig(view4) {
29532
- return {
29533
- ...view4[ViewBaseConfig],
29534
- ...view4[PgViewConfig]
29535
- };
29536
- }
29537
- function getMaterializedViewConfig(view4) {
29538
- return {
29539
- ...view4[ViewBaseConfig],
29540
- ...view4[PgMaterializedViewConfig]
29541
- };
29542
- }
29543
- var init_utils4 = __esm({
29544
- "../drizzle-orm/dist/pg-core/utils.js"() {
29545
- "use strict";
29546
- init_entity();
29547
- init_table2();
29548
- init_table();
29549
- init_view_common();
29550
- init_checks();
29551
- init_foreign_keys();
29552
- init_indexes();
29553
- init_policies();
29554
- init_primary_keys();
29555
- init_unique_constraint();
29556
- init_view_common2();
29557
- init_view();
29558
- }
29559
- });
29560
-
29561
29677
  // ../drizzle-orm/dist/pg-core/utils/index.js
29562
29678
  var init_utils5 = __esm({
29563
29679
  "../drizzle-orm/dist/pg-core/utils/index.js"() {
@@ -32468,7 +32584,7 @@ var init_dialect2 = __esm({
32468
32584
  const withSql = this.buildWithCTE(withList);
32469
32585
  const valuesSql = sql.join(valuesSqlList);
32470
32586
  const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
32471
- const onConflictSql = onConflict ? sql` on conflict ${onConflict}` : void 0;
32587
+ const onConflictSql = onConflict?.length ? sql.join(onConflict) : void 0;
32472
32588
  return sql`${withSql}insert into ${table5} ${insertOrder} ${valuesSql}${onConflictSql}${returningSql}`;
32473
32589
  }
32474
32590
  sqlToQuery(sql2, invokeSource) {
@@ -33575,12 +33691,14 @@ var init_insert2 = __esm({
33575
33691
  * ```
33576
33692
  */
33577
33693
  onConflictDoNothing(config = {}) {
33694
+ if (!this.config.onConflict)
33695
+ this.config.onConflict = [];
33578
33696
  if (config.target === void 0) {
33579
- this.config.onConflict = sql`do nothing`;
33697
+ this.config.onConflict.push(sql` on conflict do nothing`);
33580
33698
  } else {
33581
33699
  const targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;
33582
33700
  const whereSql = config.where ? sql` where ${config.where}` : sql``;
33583
- this.config.onConflict = sql`${targetSql} do nothing${whereSql}`;
33701
+ this.config.onConflict.push(sql` on conflict ${targetSql} do nothing${whereSql}`);
33584
33702
  }
33585
33703
  return this;
33586
33704
  }
@@ -33619,12 +33737,16 @@ var init_insert2 = __esm({
33619
33737
  'You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.'
33620
33738
  );
33621
33739
  }
33740
+ if (!this.config.onConflict)
33741
+ this.config.onConflict = [];
33622
33742
  const whereSql = config.where ? sql` where ${config.where}` : void 0;
33623
33743
  const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : void 0;
33624
33744
  const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : void 0;
33625
33745
  const targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;
33626
33746
  const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
33627
- this.config.onConflict = sql`${targetSql}${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`;
33747
+ this.config.onConflict.push(
33748
+ sql` on conflict ${targetSql}${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`
33749
+ );
33628
33750
  return this;
33629
33751
  }
33630
33752
  /** @internal */