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