pqb 0.27.7 → 0.29.0

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.
package/dist/index.mjs CHANGED
@@ -99,10 +99,23 @@ const countSelect = [new RawSQL("count(*)")];
99
99
  function sqlQueryArgsToExpression(args) {
100
100
  return Array.isArray(args[0]) ? new RawSQL(args) : args[0];
101
101
  }
102
+ const sqlFn = (...args) => {
103
+ const arg = args[0];
104
+ if (Array.isArray(arg)) {
105
+ return new RawSQL(args);
106
+ }
107
+ if (typeof args[0] === "string") {
108
+ return new RawSQL(args[0]);
109
+ }
110
+ if (args[1] !== void 0) {
111
+ return new RawSQL(args[1], arg);
112
+ }
113
+ return (...args2) => new RawSQL(args2, arg);
114
+ };
102
115
 
103
116
  var __defProp$h = Object.defineProperty;
104
- var __defProps$b = Object.defineProperties;
105
- var __getOwnPropDescs$b = Object.getOwnPropertyDescriptors;
117
+ var __defProps$9 = Object.defineProperties;
118
+ var __getOwnPropDescs$9 = Object.getOwnPropertyDescriptors;
106
119
  var __getOwnPropSymbols$i = Object.getOwnPropertySymbols;
107
120
  var __hasOwnProp$i = Object.prototype.hasOwnProperty;
108
121
  var __propIsEnum$i = Object.prototype.propertyIsEnumerable;
@@ -118,7 +131,7 @@ var __spreadValues$h = (a, b) => {
118
131
  }
119
132
  return a;
120
133
  };
121
- var __spreadProps$b = (a, b) => __defProps$b(a, __getOwnPropDescs$b(b));
134
+ var __spreadProps$9 = (a, b) => __defProps$9(a, __getOwnPropDescs$9(b));
122
135
  class ColumnType extends ColumnTypeBase {
123
136
  /**
124
137
  * Mark the column as a primary key.
@@ -133,6 +146,8 @@ class ColumnType extends ColumnTypeBase {
133
146
  * readonly table = 'table';
134
147
  * columns = this.setColumns((t) => ({
135
148
  * id: t.uuid().primaryKey(),
149
+ * // database-level name can be passed:
150
+ * id: t.uuid().primaryKey('primary_key_name'),
136
151
  * }));
137
152
  * }
138
153
  *
@@ -140,21 +155,76 @@ class ColumnType extends ColumnTypeBase {
140
155
  * db.table.find('97ba9e78-7510-415a-9c03-23d440aec443');
141
156
  * ```
142
157
  *
143
- * @param options - to specify a constraint name
158
+ * @param name - to specify a constraint name
144
159
  */
145
- primaryKey(options) {
146
- var _a;
147
- return setColumnData(this, "primaryKey", (_a = options == null ? void 0 : options.name) != null ? _a : true);
160
+ primaryKey(name) {
161
+ return setColumnData(this, "primaryKey", name != null ? name : true);
148
162
  }
149
163
  foreignKey(fnOrTable, column, options = emptyObject) {
150
- const item = typeof fnOrTable === "string" ? __spreadValues$h({ table: fnOrTable, columns: [column] }, options) : __spreadValues$h({ fn: fnOrTable, columns: [column] }, options);
151
- return pushColumnData(this, "foreignKeys", item);
164
+ return pushColumnData(this, "foreignKeys", {
165
+ fnOrTable,
166
+ foreignColumns: [column],
167
+ options
168
+ });
152
169
  }
153
170
  toSQL() {
154
171
  return this.dataType;
155
172
  }
156
- index(options = {}) {
157
- return pushColumnData(this, "indexes", options);
173
+ /**
174
+ * Add an index to the column.
175
+ *
176
+ * ```ts
177
+ * import { change } from '../dbScript';
178
+ *
179
+ * change(async (db) => {
180
+ * await db.createTable('table', (t) => ({
181
+ * // add an index to the name column with default settings:
182
+ * name: t.text().index(),
183
+ * // options are described below:
184
+ * name: t.text().index({ ...options }),
185
+ * // with a database-level name:
186
+ * name: t.text().index('custom_index_name'),
187
+ * // with name and options:
188
+ * name: t.text().index('custom_index_name', { ...options }),
189
+ * }));
190
+ * });
191
+ * ```
192
+ *
193
+ * Possible options are:
194
+ *
195
+ * ```ts
196
+ * type IndexOptions = {
197
+ * // NULLS NOT DISTINCT: availabe in Postgres 15+, makes sense only for unique index
198
+ * nullsNotDistinct?: true;
199
+ * // index algorithm to use such as GIST, GIN
200
+ * using?: string;
201
+ * // specify collation:
202
+ * collate?: string;
203
+ * // see `opclass` in the Postgres document for creating the index
204
+ * opclass?: string;
205
+ * // specify index order such as ASC NULLS FIRST, DESC NULLS LAST
206
+ * order?: string;
207
+ * // include columns to an index to optimize specific queries
208
+ * include?: MaybeArray<string>;
209
+ * // see "storage parameters" in the Postgres document for creating an index, for example, 'fillfactor = 70'
210
+ * with?: string;
211
+ * // The tablespace in which to create the index. If not specified, default_tablespace is consulted, or temp_tablespaces for indexes on temporary tables.
212
+ * tablespace?: string;
213
+ * // WHERE clause to filter records for the index
214
+ * where?: string;
215
+ * // mode is for dropping the index
216
+ * mode?: 'CASCADE' | 'RESTRICT';
217
+ * };
218
+ * ```
219
+ *
220
+ * @param args
221
+ */
222
+ index(...args) {
223
+ var _a;
224
+ return pushColumnData(this, "indexes", {
225
+ options: (_a = typeof args[0] === "string" ? args[1] : args[0]) != null ? _a : emptyObject,
226
+ name: typeof args[0] === "string" ? args[0] : void 0
227
+ });
158
228
  }
159
229
  /**
160
230
  * `searchIndex` is designed for [full text search](/guide/text-search).
@@ -258,11 +328,19 @@ class ColumnType extends ColumnTypeBase {
258
328
  *
259
329
  * @param options - index options
260
330
  */
261
- searchIndex(options) {
262
- return pushColumnData(this, "indexes", __spreadValues$h(__spreadValues$h({}, options), this.dataType === "tsvector" ? { using: "GIN" } : { tsVector: true }));
331
+ searchIndex(...args) {
332
+ return pushColumnData(this, "indexes", {
333
+ options: __spreadValues$h(__spreadValues$h({}, typeof args[0] === "string" ? args[1] : args[0]), this.dataType === "tsvector" ? { using: "GIN" } : { tsVector: true }),
334
+ name: typeof args[0] === "string" ? args[0] : void 0
335
+ });
263
336
  }
264
- unique(options = {}) {
265
- return pushColumnData(this, "indexes", __spreadProps$b(__spreadValues$h({}, options), { unique: true }));
337
+ unique(...args) {
338
+ return pushColumnData(this, "indexes", {
339
+ options: __spreadProps$9(__spreadValues$h({}, typeof args[0] === "string" ? args[1] : args[0]), {
340
+ unique: true
341
+ }),
342
+ name: typeof args[0] === "string" ? args[0] : void 0
343
+ });
266
344
  }
267
345
  comment(comment) {
268
346
  return setColumnData(this, "comment", comment);
@@ -301,8 +379,8 @@ class ColumnType extends ColumnTypeBase {
301
379
  }
302
380
 
303
381
  var __defProp$g = Object.defineProperty;
304
- var __defProps$a = Object.defineProperties;
305
- var __getOwnPropDescs$a = Object.getOwnPropertyDescriptors;
382
+ var __defProps$8 = Object.defineProperties;
383
+ var __getOwnPropDescs$8 = Object.getOwnPropertyDescriptors;
306
384
  var __getOwnPropSymbols$h = Object.getOwnPropertySymbols;
307
385
  var __hasOwnProp$h = Object.prototype.hasOwnProperty;
308
386
  var __propIsEnum$h = Object.prototype.propertyIsEnumerable;
@@ -318,7 +396,7 @@ var __spreadValues$g = (a, b) => {
318
396
  }
319
397
  return a;
320
398
  };
321
- var __spreadProps$a = (a, b) => __defProps$a(a, __getOwnPropDescs$a(b));
399
+ var __spreadProps$8 = (a, b) => __defProps$8(a, __getOwnPropDescs$8(b));
322
400
  const knownDefaults = {
323
401
  current_timestamp: "now()",
324
402
  "transaction_timestamp()": "now()"
@@ -334,7 +412,7 @@ const simplifyColumnDefault = (value) => {
334
412
  const instantiateColumn = (typeFn, params) => {
335
413
  const column = typeFn();
336
414
  const { dateTimePrecision } = params;
337
- Object.assign(column.data, __spreadProps$a(__spreadValues$g({}, params), {
415
+ Object.assign(column.data, __spreadProps$8(__spreadValues$g({}, params), {
338
416
  dateTimePrecision: (
339
417
  // 0 is default for date, 6 is default for timestamp
340
418
  dateTimePrecision && dateTimePrecision !== 6 ? dateTimePrecision : void 0
@@ -344,15 +422,6 @@ const instantiateColumn = (typeFn, params) => {
344
422
  }));
345
423
  return column;
346
424
  };
347
- const getConstraintKind = (it) => {
348
- let num = 0;
349
- for (const key in it) {
350
- if ((key === "references" || key === "check") && it[key] !== void 0) {
351
- num++;
352
- }
353
- }
354
- return num === 1 ? it.references ? "foreignKey" : "check" : "constraint";
355
- };
356
425
 
357
426
  const isDefaultTimeStamp = (item) => {
358
427
  if (item.dataType !== "timestamptz")
@@ -380,7 +449,7 @@ const combineCodeElements = (input) => {
380
449
  }
381
450
  return output;
382
451
  };
383
- const columnsShapeToCode = (shape, tableData, t, m) => {
452
+ const columnsShapeToCode = (shape, t) => {
384
453
  const hasTimestamps = "createdAt" in shape && isDefaultTimeStamp(shape.createdAt) && "updatedAt" in shape && isDefaultTimeStamp(shape.updatedAt);
385
454
  const code = [];
386
455
  for (const key in shape) {
@@ -397,33 +466,40 @@ const columnsShapeToCode = (shape, tableData, t, m) => {
397
466
  if (hasTimestamps) {
398
467
  code.push(`...${t}.timestamps(),`);
399
468
  }
400
- const { primaryKey, indexes, constraints } = tableData;
401
- if (primaryKey) {
402
- code.push(primaryKeyToCode(primaryKey, t));
469
+ return code;
470
+ };
471
+ const pushTableDataCode = (code, ast) => {
472
+ const lines = [];
473
+ if (ast.primaryKey) {
474
+ lines.push([primaryKeyInnerToCode(ast.primaryKey, "t") + ","]);
403
475
  }
404
- if (indexes) {
405
- for (const index of indexes) {
406
- code.push(...indexToCode(index, t));
476
+ if (ast.indexes) {
477
+ for (const index of ast.indexes) {
478
+ lines.push(indexToCode(index, "t"));
407
479
  }
408
480
  }
409
- if (constraints) {
410
- for (const item of constraints) {
411
- code.push(...constraintToCode(item, t, m));
481
+ if (ast.constraints) {
482
+ for (const constraint of ast.constraints) {
483
+ lines.push(constraintToCode(constraint, "t", true));
412
484
  }
413
485
  }
486
+ if (lines.length > 1) {
487
+ code.push("(t) => [", ...lines, "],");
488
+ } else if (lines[0].length === 1 && typeof lines[0][0] === "string") {
489
+ code.push("(t) => " + lines[0][0]);
490
+ } else {
491
+ code.push("(t) => ", lines[0]);
492
+ }
414
493
  return code;
415
494
  };
416
- const primaryKeyToCode = (primaryKey, t) => {
417
- return `...${primaryKeyInnerToCode(primaryKey, t)},`;
418
- };
419
495
  const primaryKeyInnerToCode = (primaryKey, t) => {
420
- var _a;
421
- const name = (_a = primaryKey.options) == null ? void 0 : _a.name;
422
- return `${t}.primaryKey([${primaryKey.columns.map(singleQuote).join(", ")}]${name ? `, { name: ${singleQuote(name)} }` : ""})`;
496
+ const name = primaryKey.name;
497
+ return `${t}.primaryKey([${primaryKey.columns.map(singleQuote).join(", ")}]${name ? `, ${singleQuote(name)}` : ""})`;
423
498
  };
424
- const indexToCode = (index, t) => {
499
+ const indexToCode = (index, t, prefix) => {
425
500
  const code = indexInnerToCode(index, t);
426
- code[0] = `...${code[0]}`;
501
+ if (prefix)
502
+ code[0] = prefix + code[0];
427
503
  const last = code[code.length - 1];
428
504
  if (typeof last === "string" && !last.endsWith(","))
429
505
  addCode(code, ",");
@@ -435,6 +511,19 @@ const indexInnerToCode = (index, t) => {
435
511
  `${t}.${index.options.tsVector ? "searchIndex" : index.options.unique ? "unique" : "index"}(`
436
512
  );
437
513
  const columnOptions = ["collate", "opclass", "order", "weight"];
514
+ const indexOptionsKeys = [
515
+ index.options.tsVector ? "unique" : void 0,
516
+ "using",
517
+ "nullsNotDistinct",
518
+ "include",
519
+ "with",
520
+ "tablespace",
521
+ "where",
522
+ "language",
523
+ "languageColumn",
524
+ "dropMode"
525
+ ];
526
+ const hasOptions = indexOptionsKeys.some((key) => key && index.options[key]);
438
527
  const columnsMultiline = index.columns.some((column) => {
439
528
  for (const key in column) {
440
529
  if (key !== "column" && column[key] !== void 0)
@@ -446,13 +535,13 @@ const indexInnerToCode = (index, t) => {
446
535
  const objects = [];
447
536
  for (const column of index.columns) {
448
537
  const expr = "column" in column ? column.column : column.expression;
449
- let hasOptions = false;
538
+ let hasOptions2 = false;
450
539
  for (const key in column) {
451
540
  if (key !== "column") {
452
- hasOptions = true;
541
+ hasOptions2 = true;
453
542
  }
454
543
  }
455
- if (!hasOptions) {
544
+ if (!hasOptions2) {
456
545
  objects.push(`${singleQuote(expr)},`);
457
546
  } else {
458
547
  const props = [
@@ -469,38 +558,29 @@ const indexInnerToCode = (index, t) => {
469
558
  objects.push("{", props, "},");
470
559
  }
471
560
  }
472
- code.push(["[", objects, "]"]);
561
+ code.push(["[", objects, hasOptions || index.name ? "]," : "]"]);
562
+ if (index.name) {
563
+ addCode(code, ` ${singleQuote(index.name)},`);
564
+ }
473
565
  } else {
474
566
  addCode(
475
567
  code,
476
568
  `[${index.columns.map((it) => singleQuote(it.column)).join(", ")}]`
477
569
  );
570
+ if (index.name) {
571
+ addCode(code, `, ${singleQuote(index.name)}`);
572
+ }
478
573
  }
479
- const indexOptionsKeys = [
480
- "name",
481
- "using",
482
- "nullsNotDistinct",
483
- "include",
484
- "with",
485
- "tablespace",
486
- "where",
487
- "language",
488
- "languageColumn",
489
- "dropMode"
490
- ];
491
- if (index.options.tsVector && index.options.unique) {
492
- indexOptionsKeys.unshift("unique");
493
- }
494
- if (indexOptionsKeys.some((key) => index.options[key])) {
574
+ if (hasOptions) {
495
575
  if (columnsMultiline) {
496
- const columns = code[code.length - 1];
497
- columns[columns.length - 1] += ",";
498
576
  code.push(["{"]);
499
577
  } else {
500
578
  addCode(code, ", {");
501
579
  }
502
580
  const options = [];
503
581
  for (const key of indexOptionsKeys) {
582
+ if (!key)
583
+ continue;
504
584
  const value = index.options[key];
505
585
  if (value === null || value === void 0)
506
586
  continue;
@@ -522,46 +602,26 @@ const indexInnerToCode = (index, t) => {
522
602
  }
523
603
  return code;
524
604
  };
525
- const constraintToCode = (item, t, m) => {
605
+ const constraintToCode = (item, t, m, prefix) => {
526
606
  const code = constraintInnerToCode(item, t, m);
527
- code[0] = `...${code[0]}`;
607
+ if (prefix)
608
+ code[0] = prefix + code[0];
528
609
  const last = code[code.length - 1];
529
610
  if (typeof last === "string" && !last.endsWith(","))
530
611
  code[code.length - 1] += ",";
531
612
  return code;
532
613
  };
533
614
  const constraintInnerToCode = (item, t, m) => {
534
- const kind = getConstraintKind(item);
535
- if (kind === "foreignKey" && item.references) {
615
+ if (item.references) {
536
616
  return [
537
617
  `${t}.foreignKey(`,
538
618
  referencesArgsToCode(item.references, item.name, m),
539
619
  "),"
540
620
  ];
541
- } else if (kind === "check" && item.check) {
542
- return [
543
- `${t}.check(${item.check.toCode(t)}${item.name ? `, { name: '${item.name}' }` : ""})`
544
- ];
545
- } else {
546
- return [`${t}.constraint({`, constraintPropsToCode(t, item, m), "}),"];
547
- }
548
- };
549
- const constraintPropsToCode = (t, item, m) => {
550
- const props = [];
551
- if (item.name) {
552
- props.push(`name: ${singleQuote(item.name)},`);
553
- }
554
- if (item.references) {
555
- props.push(
556
- `references: [`,
557
- referencesArgsToCode(item.references, false, m),
558
- "],"
559
- );
560
- }
561
- if (item.check) {
562
- props.push(`check: ${item.check.toCode(t)},`);
563
621
  }
564
- return props;
622
+ return [
623
+ `${t}.check(${item.check.toCode(t)}${item.name ? `, ${singleQuote(item.name)}` : ""})`
624
+ ];
565
625
  };
566
626
  const referencesArgsToCode = ({
567
627
  columns,
@@ -605,9 +665,12 @@ const columnForeignKeysToCode = (foreignKeys, migration) => {
605
665
  }
606
666
  return code;
607
667
  };
608
- const foreignKeyArgumentToCode = (foreignKey, migration) => {
668
+ const foreignKeyArgumentToCode = ({
669
+ fnOrTable,
670
+ foreignColumns,
671
+ options = emptyObject
672
+ }, migration) => {
609
673
  const code = [];
610
- let fnOrTable = "fn" in foreignKey ? foreignKey.fn : foreignKey.table;
611
674
  if (migration && typeof fnOrTable !== "string") {
612
675
  const { schema, table } = new (fnOrTable())();
613
676
  fnOrTable = schema ? `${schema}.${table}` : table;
@@ -615,18 +678,18 @@ const foreignKeyArgumentToCode = (foreignKey, migration) => {
615
678
  code.push(
616
679
  typeof fnOrTable === "string" ? singleQuote(fnOrTable) : fnOrTable.toString()
617
680
  );
618
- addCode(code, `, ${singleQuote(foreignKey.columns[0])}`);
619
- const hasOptions = foreignKey.name || foreignKey.match || foreignKey.onUpdate || foreignKey.onDelete;
681
+ addCode(code, `, ${singleQuote(foreignColumns[0])}`);
682
+ const hasOptions = options.name || options.match || options.onUpdate || options.onDelete;
620
683
  if (hasOptions) {
621
684
  const arr = [];
622
- if (foreignKey.name)
623
- arr.push(`name: ${singleQuote(foreignKey.name)},`);
624
- if (foreignKey.match)
625
- arr.push(`match: ${singleQuote(foreignKey.match)},`);
626
- if (foreignKey.onUpdate)
627
- arr.push(`onUpdate: ${singleQuote(foreignKey.onUpdate)},`);
628
- if (foreignKey.onDelete)
629
- arr.push(`onDelete: ${singleQuote(foreignKey.onDelete)},`);
685
+ if (options.name)
686
+ arr.push(`name: ${singleQuote(options.name)},`);
687
+ if (options.match)
688
+ arr.push(`match: ${singleQuote(options.match)},`);
689
+ if (options.onUpdate)
690
+ arr.push(`onUpdate: ${singleQuote(options.onUpdate)},`);
691
+ if (options.onDelete)
692
+ arr.push(`onDelete: ${singleQuote(options.onDelete)},`);
630
693
  addCode(code, ", {");
631
694
  code.push(arr);
632
695
  addCode(code, "}");
@@ -635,31 +698,31 @@ const foreignKeyArgumentToCode = (foreignKey, migration) => {
635
698
  };
636
699
  const columnIndexesToCode = (indexes) => {
637
700
  const code = [];
638
- for (const index of indexes) {
639
- addCode(code, `.${index.unique ? "unique" : "index"}(`);
701
+ for (const { options, name } of indexes) {
702
+ addCode(code, `.${options.unique ? "unique" : "index"}(`);
640
703
  const arr = [];
641
- if (index.collate)
642
- arr.push(`collate: ${singleQuote(index.collate)},`);
643
- if (index.opclass)
644
- arr.push(`opclass: ${singleQuote(index.opclass)},`);
645
- if (index.order)
646
- arr.push(`order: ${singleQuote(index.order)},`);
647
- if (index.name)
648
- arr.push(`name: ${singleQuote(index.name)},`);
649
- if (index.using)
650
- arr.push(`using: ${singleQuote(index.using)},`);
651
- if (index.include)
704
+ if (options.collate)
705
+ arr.push(`collate: ${singleQuote(options.collate)},`);
706
+ if (options.opclass)
707
+ arr.push(`opclass: ${singleQuote(options.opclass)},`);
708
+ if (options.order)
709
+ arr.push(`order: ${singleQuote(options.order)},`);
710
+ if (name)
711
+ arr.push(`name: ${singleQuote(name)},`);
712
+ if (options.using)
713
+ arr.push(`using: ${singleQuote(options.using)},`);
714
+ if (options.include)
652
715
  arr.push(
653
- `include: ${typeof index.include === "string" ? singleQuote(index.include) : `[${index.include.map(singleQuote).join(", ")}]`},`
716
+ `include: ${typeof options.include === "string" ? singleQuote(options.include) : `[${options.include.map(singleQuote).join(", ")}]`},`
654
717
  );
655
- if (index.nullsNotDistinct)
718
+ if (options.nullsNotDistinct)
656
719
  arr.push(`nullsNotDistinct: true,`);
657
- if (index.with)
658
- arr.push(`with: ${singleQuote(index.with)},`);
659
- if (index.tablespace)
660
- arr.push(`tablespace: ${singleQuote(index.tablespace)},`);
661
- if (index.where)
662
- arr.push(`where: ${singleQuote(index.where)},`);
720
+ if (options.with)
721
+ arr.push(`with: ${singleQuote(options.with)},`);
722
+ if (options.tablespace)
723
+ arr.push(`tablespace: ${singleQuote(options.tablespace)},`);
724
+ if (options.where)
725
+ arr.push(`where: ${singleQuote(options.where)},`);
663
726
  if (arr.length) {
664
727
  addCode(code, "{");
665
728
  addCode(code, arr);
@@ -669,8 +732,8 @@ const columnIndexesToCode = (indexes) => {
669
732
  }
670
733
  return code;
671
734
  };
672
- const columnCheckToCode = (t, { sql, options }) => {
673
- return `.check(${sql.toCode(t)}${(options == null ? void 0 : options.name) ? `, { name: '${options.name}' }` : ""})`;
735
+ const columnCheckToCode = (t, { sql, name }) => {
736
+ return `.check(${sql.toCode(t)}${name ? `, { name: '${name}' }` : ""})`;
674
737
  };
675
738
  const identityToCode = (identity, dataType) => {
676
739
  const code = [];
@@ -715,7 +778,7 @@ const columnCode = (type, t, code, migration, data = type.data, skip) => {
715
778
  if (data.primaryKey) {
716
779
  addCode(
717
780
  code,
718
- `.primaryKey(${data.primaryKey === true ? "" : `{ name: '${data.primaryKey}' }`})`
781
+ `.primaryKey(${data.primaryKey === true ? "" : singleQuote(data.primaryKey)})`
719
782
  );
720
783
  }
721
784
  if (data.foreignKeys) {
@@ -1203,8 +1266,8 @@ const pushIn = (ctx, query, ands, quotedAs, arg) => {
1203
1266
  };
1204
1267
 
1205
1268
  var __defProp$f = Object.defineProperty;
1206
- var __defProps$9 = Object.defineProperties;
1207
- var __getOwnPropDescs$9 = Object.getOwnPropertyDescriptors;
1269
+ var __defProps$7 = Object.defineProperties;
1270
+ var __getOwnPropDescs$7 = Object.getOwnPropertyDescriptors;
1208
1271
  var __getOwnPropSymbols$g = Object.getOwnPropertySymbols;
1209
1272
  var __hasOwnProp$g = Object.prototype.hasOwnProperty;
1210
1273
  var __propIsEnum$g = Object.prototype.propertyIsEnumerable;
@@ -1220,7 +1283,7 @@ var __spreadValues$f = (a, b) => {
1220
1283
  }
1221
1284
  return a;
1222
1285
  };
1223
- var __spreadProps$9 = (a, b) => __defProps$9(a, __getOwnPropDescs$9(b));
1286
+ var __spreadProps$7 = (a, b) => __defProps$7(a, __getOwnPropDescs$7(b));
1224
1287
  const processJoinItem = (ctx, table, query, args, quotedAs) => {
1225
1288
  let target;
1226
1289
  let on;
@@ -1282,8 +1345,8 @@ const processJoinItem = (ctx, table, query, args, quotedAs) => {
1282
1345
  const whereSql = whereToSql(
1283
1346
  ctx,
1284
1347
  q,
1285
- __spreadProps$9(__spreadValues$f({}, q.q), {
1286
- joinedShapes: __spreadProps$9(__spreadValues$f(__spreadValues$f({}, query.joinedShapes), q.q.joinedShapes), {
1348
+ __spreadProps$7(__spreadValues$f({}, q.q), {
1349
+ joinedShapes: __spreadProps$7(__spreadValues$f(__spreadValues$f({}, query.joinedShapes), q.q.joinedShapes), {
1287
1350
  [table.q.as || table.table]: table.q.shape
1288
1351
  })
1289
1352
  }),
@@ -1440,8 +1503,8 @@ const getIsJoinSubQuery = (query) => {
1440
1503
  };
1441
1504
 
1442
1505
  var __defProp$e = Object.defineProperty;
1443
- var __defProps$8 = Object.defineProperties;
1444
- var __getOwnPropDescs$8 = Object.getOwnPropertyDescriptors;
1506
+ var __defProps$6 = Object.defineProperties;
1507
+ var __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors;
1445
1508
  var __getOwnPropSymbols$f = Object.getOwnPropertySymbols;
1446
1509
  var __hasOwnProp$f = Object.prototype.hasOwnProperty;
1447
1510
  var __propIsEnum$f = Object.prototype.propertyIsEnumerable;
@@ -1457,7 +1520,7 @@ var __spreadValues$e = (a, b) => {
1457
1520
  }
1458
1521
  return a;
1459
1522
  };
1460
- var __spreadProps$8 = (a, b) => __defProps$8(a, __getOwnPropDescs$8(b));
1523
+ var __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b));
1461
1524
  const processJoinArgs = (joinTo, first, args, joinSubQuery) => {
1462
1525
  var _a;
1463
1526
  if (typeof first === "string") {
@@ -1489,7 +1552,7 @@ const processJoinArgs = (joinTo, first, args, joinSubQuery) => {
1489
1552
  logger: joinToQ.logger
1490
1553
  };
1491
1554
  j.baseQuery = j;
1492
- const joinedShapes = __spreadProps$8(__spreadValues$e({}, joinToQ.joinedShapes), {
1555
+ const joinedShapes = __spreadProps$6(__spreadValues$e({}, joinToQ.joinedShapes), {
1493
1556
  [joinToQ.as || joinTo.table]: joinTo.shape
1494
1557
  });
1495
1558
  const r = args[0](
@@ -1516,7 +1579,7 @@ const processJoinArgs = (joinTo, first, args, joinSubQuery) => {
1516
1579
  pushQueryArray(q, "or", query.or);
1517
1580
  }
1518
1581
  }
1519
- const joinedShapes = __spreadProps$8(__spreadValues$e({}, joinTo.q.joinedShapes), {
1582
+ const joinedShapes = __spreadProps$6(__spreadValues$e({}, joinTo.q.joinedShapes), {
1520
1583
  [joinTo.q.as || joinTo.table]: joinTo.shape
1521
1584
  });
1522
1585
  const r = args[0](
@@ -1545,8 +1608,8 @@ const makeJoinQueryBuilder = (joinedQuery, joinedShapes, joinTo) => {
1545
1608
  };
1546
1609
 
1547
1610
  var __defProp$d = Object.defineProperty;
1548
- var __defProps$7 = Object.defineProperties;
1549
- var __getOwnPropDescs$7 = Object.getOwnPropertyDescriptors;
1611
+ var __defProps$5 = Object.defineProperties;
1612
+ var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
1550
1613
  var __getOwnPropSymbols$e = Object.getOwnPropertySymbols;
1551
1614
  var __hasOwnProp$e = Object.prototype.hasOwnProperty;
1552
1615
  var __propIsEnum$e = Object.prototype.propertyIsEnumerable;
@@ -1562,7 +1625,7 @@ var __spreadValues$d = (a, b) => {
1562
1625
  }
1563
1626
  return a;
1564
1627
  };
1565
- var __spreadProps$7 = (a, b) => __defProps$7(a, __getOwnPropDescs$7(b));
1628
+ var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
1566
1629
  const _join = (q, require2, type, first, args) => {
1567
1630
  var _a, _b;
1568
1631
  let joinKey;
@@ -1663,7 +1726,7 @@ const _joinLateral = (self, type, arg, cb, as) => {
1663
1726
  const t = Object.create(q.queryBuilder);
1664
1727
  t.table = arg;
1665
1728
  t.shape = shape;
1666
- t.q = __spreadProps$7(__spreadValues$d({}, t.q), {
1729
+ t.q = __spreadProps$5(__spreadValues$d({}, t.q), {
1667
1730
  shape
1668
1731
  });
1669
1732
  t.baseQuery = t;
@@ -3300,13 +3363,13 @@ const pushInsertSql = (ctx, q, query, quotedAs) => {
3300
3363
  }
3301
3364
  if (query.onConflict) {
3302
3365
  ctx.sql.push("ON CONFLICT");
3303
- const { expr, type } = query.onConflict;
3304
- if (expr) {
3305
- if (typeof expr === "string") {
3306
- ctx.sql.push(`("${((_b = shape[expr]) == null ? void 0 : _b.data.name) || expr}")`);
3307
- } else if (Array.isArray(expr)) {
3366
+ const { target } = query.onConflict;
3367
+ if (target) {
3368
+ if (typeof target === "string") {
3369
+ ctx.sql.push(`("${((_b = shape[target]) == null ? void 0 : _b.data.name) || target}")`);
3370
+ } else if (Array.isArray(target)) {
3308
3371
  ctx.sql.push(
3309
- `(${expr.reduce(
3372
+ `(${target.reduce(
3310
3373
  (sql, item, i) => {
3311
3374
  var _a2;
3312
3375
  return sql + (i ? ", " : "") + `"${((_a2 = shape[item]) == null ? void 0 : _a2.data.name) || item}"`;
@@ -3314,68 +3377,67 @@ const pushInsertSql = (ctx, q, query, quotedAs) => {
3314
3377
  ""
3315
3378
  )})`
3316
3379
  );
3380
+ } else if ("toSQL" in target) {
3381
+ ctx.sql.push(target.toSQL(ctx, quotedAs));
3317
3382
  } else {
3318
- ctx.sql.push(expr.toSQL(ctx, quotedAs));
3383
+ ctx.sql.push(`ON CONSTRAINT "${target.constraint}"`);
3319
3384
  }
3320
- } else if (type === "merge") {
3321
- const { indexes } = q.internal;
3322
- const quotedUniques = columns.reduce((arr, key, i) => {
3323
- var _a2, _b2;
3324
- const unique = (
3325
- // check column index
3326
- ((_b2 = ((_a2 = shape[key]) == null ? void 0 : _a2.data).indexes) == null ? void 0 : _b2.some(
3327
- (index) => index.unique
3328
- )) || // check table composite indexes
3329
- (indexes == null ? void 0 : indexes.some(
3330
- (index) => index.columns.some(
3331
- (item) => "column" in item && item.column === key
3332
- )
3333
- ))
3334
- );
3335
- if (unique)
3336
- arr.push(quotedColumns[i]);
3337
- return arr;
3338
- }, []);
3339
- ctx.sql.push(`(${quotedUniques.join(", ")})`);
3340
3385
  }
3341
- if (type === "ignore") {
3342
- ctx.sql.push("DO NOTHING");
3343
- } else if (type === "merge") {
3344
- let set;
3345
- const { update } = query.onConflict;
3346
- if (update) {
3347
- if (typeof update === "string") {
3348
- const name = ((_c = shape[update]) == null ? void 0 : _c.data.name) || update;
3349
- set = `"${name}" = excluded."${name}"`;
3350
- } else if (Array.isArray(update)) {
3351
- set = update.reduce((sql, item, i) => {
3386
+ if ("merge" in query.onConflict) {
3387
+ let sql;
3388
+ const { merge } = query.onConflict;
3389
+ if (merge) {
3390
+ if (typeof merge === "string") {
3391
+ const name = ((_c = shape[merge]) == null ? void 0 : _c.data.name) || merge;
3392
+ sql = `"${name}" = excluded."${name}"`;
3393
+ } else if ("except" in merge) {
3394
+ const notExcluded = [];
3395
+ const except = toArray(merge.except);
3396
+ for (let i = 0; i < columns.length; i++) {
3397
+ if (!except.includes(columns[i])) {
3398
+ notExcluded.push(quotedColumns[i]);
3399
+ }
3400
+ }
3401
+ sql = mergeColumnsSql(notExcluded);
3402
+ } else {
3403
+ sql = merge.reduce((sql2, item, i) => {
3352
3404
  var _a2;
3353
3405
  const name = ((_a2 = shape[item]) == null ? void 0 : _a2.data.name) || item;
3354
- return sql + (i ? ", " : "") + `"${name}" = excluded."${name}"`;
3406
+ return sql2 + (i ? ", " : "") + `"${name}" = excluded."${name}"`;
3355
3407
  }, "");
3356
- } else if (isExpression(update)) {
3357
- set = update.toSQL(ctx, quotedAs);
3358
- } else {
3359
- const arr = [];
3360
- for (const key in update) {
3361
- arr.push(
3362
- `"${((_d = shape[key]) == null ? void 0 : _d.data.name) || key}" = ${addValue(
3363
- ctx.values,
3364
- update[key]
3365
- )}`
3366
- );
3367
- }
3368
- set = arr.join(", ");
3369
3408
  }
3370
3409
  } else {
3371
- set = quotedColumns.map((column) => `${column} = excluded.${column}`).join(", ");
3410
+ sql = mergeColumnsSql(quotedColumns);
3372
3411
  }
3373
- ctx.sql.push("DO UPDATE SET", set);
3412
+ ctx.sql.push("DO UPDATE SET", sql);
3413
+ } else if (query.onConflict.set) {
3414
+ let sql;
3415
+ const { set } = query.onConflict;
3416
+ if (isExpression(set)) {
3417
+ sql = set.toSQL(ctx, quotedAs);
3418
+ } else {
3419
+ const arr = [];
3420
+ for (const key in set) {
3421
+ arr.push(
3422
+ `"${((_d = shape[key]) == null ? void 0 : _d.data.name) || key}" = ${addValue(
3423
+ ctx.values,
3424
+ set[key]
3425
+ )}`
3426
+ );
3427
+ }
3428
+ sql = arr.join(", ");
3429
+ }
3430
+ ctx.sql.push("DO UPDATE SET", sql);
3431
+ } else {
3432
+ ctx.sql.push("DO NOTHING");
3374
3433
  }
3375
3434
  }
3376
3435
  pushWhereStatementSql(ctx, q, query, quotedAs);
3377
3436
  return pushReturningSql(ctx, q, query, quotedAs, query.afterCreateSelect);
3378
3437
  };
3438
+ const mergeColumnsSql = (quotedColumns2) => {
3439
+ return quotedColumns2.map((column) => `${column} = excluded.${column}`).join(", ");
3440
+ };
3379
3441
  const encodeRow = (ctx, q, QueryClass, row, runtimeDefaults, quotedAs) => {
3380
3442
  const arr = row.map((value) => {
3381
3443
  if (typeof value === "function") {
@@ -4010,10 +4072,27 @@ const extendQuery = (q, methods) => {
4010
4072
  cloned.q = getClonedQueryData(q.q);
4011
4073
  return cloned;
4012
4074
  };
4075
+ const getPrimaryKeys = (q) => {
4076
+ var _a, _b;
4077
+ return (_b = (_a = q.internal).primaryKeys) != null ? _b : _a.primaryKeys = collectPrimaryKeys(q);
4078
+ };
4079
+ const collectPrimaryKeys = (q) => {
4080
+ const primaryKeys = [];
4081
+ const { shape } = q.q;
4082
+ for (const key in shape) {
4083
+ if (shape[key].data.primaryKey) {
4084
+ primaryKeys.push(key);
4085
+ }
4086
+ }
4087
+ if (q.internal.primaryKeys) {
4088
+ primaryKeys.push(...q.internal.primaryKeys);
4089
+ }
4090
+ return primaryKeys;
4091
+ };
4013
4092
 
4014
4093
  var __defProp$a = Object.defineProperty;
4015
- var __defProps$6 = Object.defineProperties;
4016
- var __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors;
4094
+ var __defProps$4 = Object.defineProperties;
4095
+ var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
4017
4096
  var __getOwnPropSymbols$b = Object.getOwnPropertySymbols;
4018
4097
  var __hasOwnProp$b = Object.prototype.hasOwnProperty;
4019
4098
  var __propIsEnum$b = Object.prototype.propertyIsEnumerable;
@@ -4029,7 +4108,7 @@ var __spreadValues$a = (a, b) => {
4029
4108
  }
4030
4109
  return a;
4031
4110
  };
4032
- var __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b));
4111
+ var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
4033
4112
  function setQueryOperators(query, operators) {
4034
4113
  const q = query.q;
4035
4114
  if (q.operators) {
@@ -4088,7 +4167,7 @@ const base = {
4088
4167
  (key, value, ctx, quotedAs) => `NOT ${key} IN ${quoteValue(value, ctx, quotedAs)}`
4089
4168
  )
4090
4169
  };
4091
- const boolean = __spreadProps$6(__spreadValues$a({}, base), {
4170
+ const boolean = __spreadProps$4(__spreadValues$a({}, base), {
4092
4171
  and: make(
4093
4172
  (key, value, ctx, quotedAs) => `${key} AND ${value.q.expr.toSQL(ctx, quotedAs)}`
4094
4173
  ),
@@ -4096,7 +4175,7 @@ const boolean = __spreadProps$6(__spreadValues$a({}, base), {
4096
4175
  (key, value, ctx, quotedAs) => `(${key}) OR (${value.q.expr.toSQL(ctx, quotedAs)})`
4097
4176
  )
4098
4177
  });
4099
- const numeric = __spreadProps$6(__spreadValues$a({}, base), {
4178
+ const numeric = __spreadProps$4(__spreadValues$a({}, base), {
4100
4179
  lt: make(
4101
4180
  (key, value, ctx, quotedAs) => `${key} < ${quoteValue(value, ctx, quotedAs)}`
4102
4181
  ),
@@ -4117,7 +4196,7 @@ const numeric = __spreadProps$6(__spreadValues$a({}, base), {
4117
4196
  )}`
4118
4197
  )
4119
4198
  });
4120
- const text = __spreadProps$6(__spreadValues$a({}, base), {
4199
+ const text = __spreadProps$4(__spreadValues$a({}, base), {
4121
4200
  contains: make(
4122
4201
  (key, value, ctx, quotedAs) => `${key} ILIKE '%' || ${quoteValue(value, ctx, quotedAs)} || '%'`
4123
4202
  ),
@@ -4137,7 +4216,7 @@ const text = __spreadProps$6(__spreadValues$a({}, base), {
4137
4216
  (key, value, ctx, quotedAs) => `${key} LIKE '%' || ${quoteValue(value, ctx, quotedAs)}`
4138
4217
  )
4139
4218
  });
4140
- const json = __spreadProps$6(__spreadValues$a({}, base), {
4219
+ const json = __spreadProps$4(__spreadValues$a({}, base), {
4141
4220
  jsonPath: make(
4142
4221
  (key, [path, op, value], ctx, quotedAs) => `jsonb_path_query_first(${key}, '${path}') #>> '{}' ${op} ${value === null ? "null" : quoteValue(value, ctx, quotedAs, true)}`
4143
4222
  ),
@@ -4331,8 +4410,8 @@ class BigSerialColumn extends NumberAsStringBaseColumn {
4331
4410
  }
4332
4411
 
4333
4412
  var __defProp$9 = Object.defineProperty;
4334
- var __defProps$5 = Object.defineProperties;
4335
- var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
4413
+ var __defProps$3 = Object.defineProperties;
4414
+ var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
4336
4415
  var __getOwnPropSymbols$a = Object.getOwnPropertySymbols;
4337
4416
  var __hasOwnProp$a = Object.prototype.hasOwnProperty;
4338
4417
  var __propIsEnum$a = Object.prototype.propertyIsEnumerable;
@@ -4348,7 +4427,7 @@ var __spreadValues$9 = (a, b) => {
4348
4427
  }
4349
4428
  return a;
4350
4429
  };
4351
- var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
4430
+ var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
4352
4431
  class TextBaseColumn extends ColumnType {
4353
4432
  constructor(schema, schemaType = schema.stringSchema()) {
4354
4433
  super(schema, schemaType);
@@ -4707,8 +4786,11 @@ class UUIDColumn extends ColumnType {
4707
4786
  this.dataType = "uuid";
4708
4787
  this.operators = Operators.text;
4709
4788
  }
4710
- primaryKey() {
4711
- const column = super.primaryKey();
4789
+ /**
4790
+ * see {@link ColumnType.primaryKey}
4791
+ */
4792
+ primaryKey(name) {
4793
+ const column = super.primaryKey(name);
4712
4794
  if (!column.data.default)
4713
4795
  column.data.default = uuidDefault;
4714
4796
  return column;
@@ -4721,7 +4803,7 @@ class UUIDColumn extends ColumnType {
4721
4803
  `uuid()`,
4722
4804
  m,
4723
4805
  // don't output the default default
4724
- data.default instanceof RawSQLBase && data.default._sql === uuidDefaultSQL ? __spreadProps$5(__spreadValues$9({}, data), { default: void 0 }) : data
4806
+ data.default instanceof RawSQLBase && data.default._sql === uuidDefaultSQL ? __spreadProps$3(__spreadValues$9({}, data), { default: void 0 }) : data
4725
4807
  );
4726
4808
  }
4727
4809
  }
@@ -4793,8 +4875,6 @@ class DomainColumn extends CustomTypeColumn {
4793
4875
  }
4794
4876
 
4795
4877
  var __defProp$8 = Object.defineProperty;
4796
- var __defProps$4 = Object.defineProperties;
4797
- var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
4798
4878
  var __getOwnPropSymbols$9 = Object.getOwnPropertySymbols;
4799
4879
  var __hasOwnProp$9 = Object.prototype.hasOwnProperty;
4800
4880
  var __propIsEnum$9 = Object.prototype.propertyIsEnumerable;
@@ -4810,19 +4890,11 @@ var __spreadValues$8 = (a, b) => {
4810
4890
  }
4811
4891
  return a;
4812
4892
  };
4813
- var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
4814
- const newTableData = () => ({});
4815
- let tableData = newTableData();
4816
- const getTableData = () => tableData;
4817
- const resetTableData = (data = newTableData()) => {
4818
- tableData = data;
4819
- };
4820
- const getColumnTypes = (types, fn, nowSQL, language, data = newTableData()) => {
4893
+ const getColumnTypes = (types, fn, nowSQL, language) => {
4821
4894
  if (nowSQL)
4822
4895
  setDefaultNowFn(nowSQL);
4823
4896
  if (language)
4824
4897
  setDefaultLanguage(language);
4825
- resetTableData(data);
4826
4898
  return fn(types);
4827
4899
  };
4828
4900
  const makeColumnTypes = (schema) => {
@@ -4834,20 +4906,7 @@ const makeColumnTypes = (schema) => {
4834
4906
  setCurrentColumnName(name);
4835
4907
  return this;
4836
4908
  },
4837
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
4838
- sql(...args) {
4839
- const arg = args[0];
4840
- if (Array.isArray(arg)) {
4841
- return new RawSQL(args);
4842
- }
4843
- if (typeof args[0] === "string") {
4844
- return new RawSQL(args[0]);
4845
- }
4846
- if (args[1] !== void 0) {
4847
- return new RawSQL(args[1], arg);
4848
- }
4849
- return (...args2) => new RawSQL(args2, arg);
4850
- },
4909
+ sql: sqlFn,
4851
4910
  smallint: schema.smallint,
4852
4911
  integer: schema.integer,
4853
4912
  bigint: schema.bigint,
@@ -4944,66 +5003,6 @@ const makeColumnTypes = (schema) => {
4944
5003
  },
4945
5004
  domain(dataType) {
4946
5005
  return new DomainColumn(schema, dataType);
4947
- },
4948
- primaryKey(columns, options) {
4949
- tableData.primaryKey = { columns, options };
4950
- return emptyObject;
4951
- },
4952
- index(columns, options = {}) {
4953
- var _a;
4954
- const index = {
4955
- columns: toArray(columns).map(
4956
- (column) => typeof column === "string" ? { column } : column
4957
- ),
4958
- options
4959
- };
4960
- ((_a = tableData.indexes) != null ? _a : tableData.indexes = []).push(index);
4961
- return emptyObject;
4962
- },
4963
- unique(columns, options) {
4964
- return this.index(columns, __spreadProps$4(__spreadValues$8({}, options), { unique: true }));
4965
- },
4966
- /**
4967
- * See {@link ColumnType.searchIndex}
4968
- */
4969
- searchIndex(columns, options) {
4970
- return this.index(columns, __spreadProps$4(__spreadValues$8({ using: "gin" }, options), { tsVector: true }));
4971
- },
4972
- constraint({ name, references, check, dropMode }) {
4973
- var _a;
4974
- ((_a = tableData.constraints) != null ? _a : tableData.constraints = []).push({
4975
- name,
4976
- references: references ? {
4977
- columns: references[0],
4978
- fnOrTable: references[1],
4979
- foreignColumns: references[2],
4980
- options: references[3]
4981
- } : void 0,
4982
- check,
4983
- dropMode
4984
- });
4985
- return emptyObject;
4986
- },
4987
- foreignKey(columns, fnOrTable, foreignColumns, options) {
4988
- var _a;
4989
- ((_a = tableData.constraints) != null ? _a : tableData.constraints = []).push({
4990
- name: options == null ? void 0 : options.name,
4991
- references: {
4992
- columns,
4993
- fnOrTable,
4994
- foreignColumns,
4995
- options
4996
- },
4997
- dropMode: options == null ? void 0 : options.dropMode
4998
- });
4999
- return emptyObject;
5000
- },
5001
- check(check, options) {
5002
- var _a;
5003
- ((_a = tableData.constraints) != null ? _a : tableData.constraints = []).push(__spreadProps$4(__spreadValues$8({}, options), {
5004
- check
5005
- }));
5006
- return emptyObject;
5007
5006
  }
5008
5007
  }, makeTimestampsHelpers(makeRegexToFindInSql));
5009
5008
  };
@@ -5250,8 +5249,8 @@ class TransactionAdapter {
5250
5249
  }
5251
5250
 
5252
5251
  var __defProp$7 = Object.defineProperty;
5253
- var __defProps$3 = Object.defineProperties;
5254
- var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
5252
+ var __defProps$2 = Object.defineProperties;
5253
+ var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
5255
5254
  var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
5256
5255
  var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
5257
5256
  var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
@@ -5267,7 +5266,7 @@ var __spreadValues$7 = (a, b) => {
5267
5266
  }
5268
5267
  return a;
5269
5268
  };
5270
- var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
5269
+ var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
5271
5270
  class FnExpression extends Expression {
5272
5271
  /**
5273
5272
  * @param q - query object.
@@ -5324,7 +5323,7 @@ class FnExpression extends Expression {
5324
5323
  sql.push(" ");
5325
5324
  if (options.order) {
5326
5325
  pushOrderBySql(
5327
- __spreadProps$3(__spreadValues$7({}, ctx), { sql }),
5326
+ __spreadProps$2(__spreadValues$7({}, ctx), { sql }),
5328
5327
  this.q.q,
5329
5328
  quotedAs,
5330
5329
  toArray(options.order)
@@ -6255,9 +6254,9 @@ class Create {
6255
6254
  * password: '1234',
6256
6255
  * });
6257
6256
  *
6258
- * // When using `.onConflict().ignore()`,
6257
+ * // When using `.onConflictDoNothing()`,
6259
6258
  * // the record may be not created and the `createdCount` will be 0.
6260
- * const createdCount = await db.table.insert(data).onConflict().ignore();
6259
+ * const createdCount = await db.table.insert(data).onConflictDoNothing();
6261
6260
  *
6262
6261
  * await db.table.create({
6263
6262
  * // raw SQL
@@ -6450,7 +6449,7 @@ class Create {
6450
6449
  *
6451
6450
  * Columns provided in `defaults` are marked as optional in the following `create`.
6452
6451
  *
6453
- * Default data is the same as in [create](#create) and [createMany](#createMany),
6452
+ * Default data is the same as in {@link create} and {@link createMany},
6454
6453
  * so you can provide a raw SQL, or a query with a query.
6455
6454
  *
6456
6455
  * ```ts
@@ -6471,32 +6470,45 @@ class Create {
6471
6470
  return _queryDefaults(this.clone(), data);
6472
6471
  }
6473
6472
  /**
6474
- * A modifier for creating queries that specify alternative behavior in the case of a conflict.
6475
- * A conflict occurs when a table has a `PRIMARY KEY` or a `UNIQUE` index on a column
6476
- * (or a composite index on a set of columns) and a row being created has the same value as a row
6477
- * that already exists in the table in this column(s).
6478
- * The default behavior in case of conflict is to raise an error and abort the query.
6473
+ * By default, violating unique constraint will cause the creative query to throw,
6474
+ * you can define what to do on a conflict: to ignore it, or to merge the existing record with a new data.
6475
+ *
6476
+ * A conflict occurs when a table has a primary key or a unique index on a column,
6477
+ * or a composite primary key unique index on a set of columns,
6478
+ * and a row being created has the same value as a row that already exists in the table in this column(s).
6479
+ *
6480
+ * Use {@link onConflictDoNothing} to suppress the error and continue without updating the record,
6481
+ * or the `merge` to update the record with new values automatically,
6482
+ * or the `set` to specify own values for the update.
6479
6483
  *
6480
- * Use `onConflict` to either ignore the error by using `.onConflict().ignore()`,
6481
- * or to update the existing row with new data (perform an "UPSERT") by using `.onConflict().merge()`.
6484
+ * `onConflict` only accepts column names that are defined in `primaryKey` or `unique` in the table definition.
6485
+ * To specify a constraint, its name also must be explicitly set in `primaryKey` or `unique` in the table code.
6486
+ *
6487
+ * Postgres has a limitation that a single `INSERT` query can have only a single `ON CONFLICT` clause that can target only a single unique constraint
6488
+ * for updating the record.
6489
+ *
6490
+ * If your table has multiple potential reasons for unique constraint violation, such as username and email columns in a user table,
6491
+ * consider using `upsert` instead.
6482
6492
  *
6483
6493
  * ```ts
6484
6494
  * // leave `onConflict` without argument to ignore or merge on any conflict
6485
- * db.table.create(data).onConflict().ignore();
6495
+ * db.table.create(data).onConflictDoNothing();
6486
6496
  *
6487
6497
  * // single column:
6488
- * db.table.create(data).onConfict('email');
6498
+ * db.table.create(data).onConfict('email').merge();
6489
6499
  *
6490
6500
  * // array of columns:
6491
- * db.table.create(data).onConfict(['email', 'name']);
6501
+ * db.table.create(data).onConfict(['email', 'name']).merge();
6492
6502
  *
6493
- * // raw expression:
6494
- * db.table.create(data).onConfict(db.table.sql`(email) where condition`);
6495
- * ```
6503
+ * // constraint name
6504
+ * db.table.create(data).onConfict({ constraint: 'unique_index_name' }).merge();
6496
6505
  *
6497
- * ::: info
6498
- * The column(s) given to the `onConflict` must either be the table's PRIMARY KEY or have a UNIQUE index on them, or the query will fail to execute.
6499
- * When specifying multiple columns, they must be a composite PRIMARY KEY or have a composite UNIQUE index.
6506
+ * // raw SQL expression:
6507
+ * db.table
6508
+ * .create(data)
6509
+ * .onConfict(db.table.sql`(email) where condition`)
6510
+ * .merge();
6511
+ * ```
6500
6512
  *
6501
6513
  * You can use the db.table.sql function in onConflict.
6502
6514
  * It can be useful to specify a condition when you have a partial index:
@@ -6513,29 +6525,32 @@ class Create {
6513
6525
  * .ignore();
6514
6526
  * ```
6515
6527
  *
6516
- * :::
6528
+ * For `merge` and `set`, you can append `where` to update data only for the matching rows:
6517
6529
  *
6518
- * See the documentation on the .ignore() and .merge() methods for more details.
6530
+ * ```ts
6531
+ * const timestamp = Date.now();
6532
+ *
6533
+ * db.table
6534
+ * .create(data)
6535
+ * .onConflict('email')
6536
+ * .set({
6537
+ * name: 'John Doe',
6538
+ * updatedAt: timestamp,
6539
+ * })
6540
+ * .where({ updatedAt: { lt: timestamp } });
6541
+ * ```
6519
6542
  *
6520
6543
  * @param arg - optionally provide an array of columns
6521
6544
  */
6522
6545
  onConflict(arg) {
6523
6546
  return new OnConflictQueryBuilder(this, arg);
6524
6547
  }
6525
- }
6526
- class OnConflictQueryBuilder {
6527
- constructor(query, onConflict) {
6528
- this.query = query;
6529
- this.onConflict = onConflict;
6530
- }
6531
6548
  /**
6532
- * Available only after `onConflict`.
6533
- *
6534
- * `ignore` modifies a create query, and causes it to be silently dropped without an error if a conflict occurs.
6549
+ * Use `onConflictDoNothing` to suppress unique constraint violation error when creating a record.
6535
6550
  *
6536
- * Adds the `ON CONFLICT (columns) DO NOTHING` clause to the insert statement.
6551
+ * Adds `ON CONFLICT (columns) DO NOTHING` clause to the insert statement, columns are optional.
6537
6552
  *
6538
- * It produces `ON CONFLICT DO NOTHING` when no `onConflict` argument provided.
6553
+ * Can also accept a constraint name.
6539
6554
  *
6540
6555
  * ```ts
6541
6556
  * db.table
@@ -6543,40 +6558,38 @@ class OnConflictQueryBuilder {
6543
6558
  * email: 'ignore@example.com',
6544
6559
  * name: 'John Doe',
6545
6560
  * })
6546
- * .onConflict('email')
6547
- * .ignore();
6561
+ * // on any conflict:
6562
+ * .onConflictDoNothing()
6563
+ * // or, for a specific column:
6564
+ * .onConflictDoNothing('email')
6565
+ * // or, for a specific constraint:
6566
+ * .onConflictDoNothing({ constraint: 'unique_index_name' });
6548
6567
  * ```
6549
6568
  *
6550
- *
6551
- * When there is a conflict, nothing can be returned from the database, that's why `ignore` has to add `| undefined` part to the response type.
6552
- *
6553
- * `create` returns a full record by default, it becomes `RecordType | undefined` after applying `ignore`.
6569
+ * When there is a conflict, nothing can be returned from the database, so `onConflictDoNothing` adds `| undefined` part to the response type.
6554
6570
  *
6555
6571
  * ```ts
6556
6572
  * const maybeRecord: RecordType | undefined = await db.table
6557
6573
  * .create(data)
6558
- * .onConflict()
6559
- * .ignore();
6574
+ * .onConflictDoNothing();
6560
6575
  *
6561
6576
  * const maybeId: number | undefined = await db.table
6562
6577
  * .get('id')
6563
6578
  * .create(data)
6564
- * .onConflict()
6565
- * .ignore();
6579
+ * .onConflictDoNothing();
6566
6580
  * ```
6567
6581
  *
6568
- * When creating many records, only the created records will be returned. If no records were created, array will be empty:
6582
+ * When creating multiple records, only created records will be returned. If no records were created, array will be empty:
6569
6583
  *
6570
6584
  * ```ts
6571
6585
  * // array can be empty
6572
- * const arr = await db.table.createMany([data, data, data]).onConflict().ignore();
6586
+ * const arr = await db.table.createMany([data, data, data]).onConflictDoNothing();
6573
6587
  * ```
6574
6588
  */
6575
- ignore() {
6576
- const q = this.query;
6589
+ onConflictDoNothing(arg) {
6590
+ const q = this.clone();
6577
6591
  q.q.onConflict = {
6578
- type: "ignore",
6579
- expr: this.onConflict
6592
+ target: arg
6580
6593
  };
6581
6594
  if (q.q.returnType === "oneOrThrow") {
6582
6595
  q.q.returnType = "one";
@@ -6585,115 +6598,90 @@ class OnConflictQueryBuilder {
6585
6598
  }
6586
6599
  return q;
6587
6600
  }
6601
+ }
6602
+ class OnConflictQueryBuilder {
6603
+ constructor(query, onConflict) {
6604
+ this.query = query;
6605
+ this.onConflict = onConflict;
6606
+ }
6588
6607
  /**
6589
6608
  * Available only after `onConflict`.
6590
6609
  *
6591
- * Modifies a create query, to turn it into an 'upsert' operation.
6592
- *
6593
- * Adds an `ON CONFLICT (columns) DO UPDATE` clause to the insert statement.
6594
- *
6595
- * When no `onConflict` argument provided,
6596
- * it will automatically collect all table columns that have unique index and use them as a conflict target.
6610
+ * Updates the record with a given data when conflict occurs.
6597
6611
  *
6598
6612
  * ```ts
6599
- * db.table
6600
- * .create({
6601
- * email: 'ignore@example.com',
6602
- * name: 'John Doe',
6603
- * })
6604
- * .onConflict('email')
6605
- * .merge();
6613
+ * db.table.create(data).onConflict('column').set({
6614
+ * description: 'setting different data on conflict',
6615
+ * });
6606
6616
  * ```
6607
6617
  *
6608
- * This also works with batch creates:
6618
+ * The `set` can take a raw SQL expression:
6609
6619
  *
6610
6620
  * ```ts
6611
6621
  * db.table
6612
- * .createMany([
6613
- * { email: 'john@example.com', name: 'John Doe' },
6614
- * { email: 'jane@example.com', name: 'Jane Doe' },
6615
- * { email: 'alex@example.com', name: 'Alex Doe' },
6616
- * ])
6617
- * .onConflict('email')
6618
- * .merge();
6619
- * ```
6620
- *
6621
- * It is also possible to specify a subset of the columns to merge when a conflict occurs.
6622
- * For example, you may want to set a `createdAt` column when creating but would prefer not to update it if the row already exists:
6623
- *
6624
- * ```ts
6625
- * const timestamp = Date.now();
6622
+ * .create(data)
6623
+ * .onConflict()
6624
+ * .set(db.table.sql`raw SQL expression`);
6626
6625
  *
6626
+ * // update records only on certain conditions
6627
6627
  * db.table
6628
- * .create({
6629
- * email: 'ignore@example.com',
6630
- * name: 'John Doe',
6631
- * createdAt: timestamp,
6632
- * updatedAt: timestamp,
6633
- * })
6628
+ * .create(data)
6634
6629
  * .onConflict('email')
6635
- * // string argument for a single column:
6636
- * .merge('email')
6637
- * // array of strings for multiple columns:
6638
- * .merge(['email', 'name', 'updatedAt']);
6630
+ * .set({ key: 'value' })
6631
+ * .where({ ...certainConditions });
6639
6632
  * ```
6640
6633
  *
6641
- * It is also possible to specify data to update separately from the data to create.
6642
- * This is useful if you want to make an update with different data than in creating.
6643
- * For example, you may want to change a value if the row already exists:
6634
+ * @param set - object containing new column values, or raw SQL
6635
+ */
6636
+ set(set) {
6637
+ this.query.q.onConflict = {
6638
+ target: this.onConflict,
6639
+ set
6640
+ };
6641
+ return this.query;
6642
+ }
6643
+ /**
6644
+ * Available only after `onConflict`.
6644
6645
  *
6645
- * ```ts
6646
- * const timestamp = Date.now();
6646
+ * Use this method to merge all the data you have passed into `create` to update the existing record on conflict.
6647
6647
  *
6648
- * db.table
6649
- * .create({
6650
- * email: 'ignore@example.com',
6651
- * name: 'John Doe',
6652
- * createdAt: timestamp,
6653
- * updatedAt: timestamp,
6654
- * })
6655
- * .onConflict('email')
6656
- * .merge({
6657
- * name: 'John Doe The Second',
6658
- * });
6659
- * ```
6648
+ * If the table has columns with **dynamic** default values, such values will be applied as well.
6660
6649
  *
6661
- * It is also possible to add a WHERE clause to conditionally update only the matching rows:
6650
+ * You can exclude certain columns from being merged by passing the `exclude` option.
6662
6651
  *
6663
6652
  * ```ts
6664
- * const timestamp = Date.now();
6653
+ * // merge the full data
6654
+ * db.table.create(data).onConflict('email').merge();
6655
+ *
6656
+ * // merge only a single column
6657
+ * db.table.create(data).onConflict('email').merge('name');
6658
+ *
6659
+ * // merge multiple columns
6660
+ * db.table.create(data).onConflict('email').merge(['name', 'quantity']);
6665
6661
  *
6662
+ * // merge all columns except some
6666
6663
  * db.table
6667
- * .create({
6668
- * email: 'ignore@example.com',
6669
- * name: 'John Doe',
6670
- * createdAt: timestamp,
6671
- * updatedAt: timestamp,
6672
- * })
6664
+ * .create(data)
6673
6665
  * .onConflict('email')
6674
- * .merge({
6675
- * name: 'John Doe',
6676
- * updatedAt: timestamp,
6677
- * })
6678
- * .where({ updatedAt: { lt: timestamp } });
6679
- * ```
6666
+ * .merge({ except: ['name', 'quantity'] });
6680
6667
  *
6681
- * `merge` also accepts raw expression:
6668
+ * // merge can be applied also for batch creates
6669
+ * db.table.createMany([data1, data2, data2]).onConflict('email').merge();
6682
6670
  *
6683
- * ```ts
6671
+ * // update records only on certain conditions
6684
6672
  * db.table
6685
6673
  * .create(data)
6686
- * .onConflict()
6687
- * .merge(db.table.sql`raw SQL expression`);
6674
+ * .onConflict('email')
6675
+ * .merge()
6676
+ * .where({ ...certainConditions });
6688
6677
  * ```
6689
6678
  *
6690
- * @param update - column, or array of columns, or object for new column values, or raw SQL
6679
+ * @param merge - no argument will merge all data, or provide a column(s) to merge, or provide `except` to update all except some.
6691
6680
  */
6692
- merge(update) {
6681
+ merge(merge) {
6693
6682
  this.query.q.onConflict = {
6694
- type: "merge",
6695
- expr: this.onConflict,
6696
- update
6683
+ target: this.onConflict,
6684
+ merge
6697
6685
  };
6698
6686
  return this.query;
6699
6687
  }
@@ -7914,10 +7902,7 @@ class JsonModifiers {
7914
7902
  options
7915
7903
  ]
7916
7904
  };
7917
- return Object.assign(
7918
- pushQueryValue(q, "select", json),
7919
- json
7920
- );
7905
+ return Object.assign(pushQueryValue(q, "select", json), json);
7921
7906
  }
7922
7907
  /**
7923
7908
  * Return a JSON value/object/array where a given value is inserted at the given JSON path. Value can be a single value or JSON object. If a value exists at the given path, the value is not replaced.
@@ -7965,10 +7950,7 @@ class JsonModifiers {
7965
7950
  options
7966
7951
  ]
7967
7952
  };
7968
- return Object.assign(
7969
- pushQueryValue(q, "select", json),
7970
- json
7971
- );
7953
+ return Object.assign(pushQueryValue(q, "select", json), json);
7972
7954
  }
7973
7955
  /**
7974
7956
  * Return a JSON value/object/array where a given value is removed at the given JSON path.
@@ -8007,10 +7989,7 @@ class JsonModifiers {
8007
7989
  path
8008
7990
  ]
8009
7991
  };
8010
- return Object.assign(
8011
- pushQueryValue(q, "select", json),
8012
- json
8013
- );
7992
+ return Object.assign(pushQueryValue(q, "select", json), json);
8014
7993
  }
8015
7994
  /**
8016
7995
  * Selects a value from JSON data using a JSON path.
@@ -8056,10 +8035,7 @@ class JsonModifiers {
8056
8035
  const json = {
8057
8036
  __json: ["pathQuery", as, type, column, path, options]
8058
8037
  };
8059
- return Object.assign(
8060
- pushQueryValue(q, "select", json),
8061
- json
8062
- );
8038
+ return Object.assign(pushQueryValue(q, "select", json), json);
8063
8039
  }
8064
8040
  }
8065
8041
  class JsonMethods {
@@ -8076,10 +8052,7 @@ class JsonMethods {
8076
8052
  * @param coalesce
8077
8053
  */
8078
8054
  json(coalesce) {
8079
- return queryJson(
8080
- this.clone(),
8081
- coalesce
8082
- );
8055
+ return queryJson(this.clone(), coalesce);
8083
8056
  }
8084
8057
  }
8085
8058
 
@@ -8206,8 +8179,8 @@ class MergeQueryMethods {
8206
8179
  }
8207
8180
 
8208
8181
  var __defProp$4 = Object.defineProperty;
8209
- var __defProps$2 = Object.defineProperties;
8210
- var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
8182
+ var __defProps$1 = Object.defineProperties;
8183
+ var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
8211
8184
  var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
8212
8185
  var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
8213
8186
  var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
@@ -8223,7 +8196,7 @@ var __spreadValues$4 = (a, b) => {
8223
8196
  }
8224
8197
  return a;
8225
8198
  };
8226
- var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
8199
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
8227
8200
  class With {
8228
8201
  /**
8229
8202
  * Add Common Table Expression (CTE) to the query.
@@ -8298,7 +8271,7 @@ class With {
8298
8271
  const query = typeof last === "function" ? last(q.queryBuilder) : last;
8299
8272
  const shape = args.length === 4 ? args[2] : isExpression(query) ? args[1] : query.q.shape;
8300
8273
  if ((options == null ? void 0 : options.columns) === true) {
8301
- options = __spreadProps$2(__spreadValues$4({}, options), {
8274
+ options = __spreadProps$1(__spreadValues$4({}, options), {
8302
8275
  columns: Object.keys(shape)
8303
8276
  });
8304
8277
  }
@@ -9240,9 +9213,9 @@ const _queryUpdate = (query, arg) => {
9240
9213
  if (queries) {
9241
9214
  q.patchResult = async (_, queryResult) => {
9242
9215
  await Promise.all(queries.map(callWithThis, queryResult));
9243
- if (ctx.updateData) {
9216
+ if (ctx.collect) {
9244
9217
  const t = query.baseQuery.clone();
9245
- const keys = query.primaryKeys;
9218
+ const { keys } = ctx.collect;
9246
9219
  _queryWhereIn(
9247
9220
  t,
9248
9221
  keys,
@@ -9250,10 +9223,10 @@ const _queryUpdate = (query, arg) => {
9250
9223
  );
9251
9224
  _queryUpdate(
9252
9225
  t,
9253
- ctx.updateData
9226
+ ctx.collect.data
9254
9227
  );
9255
9228
  for (const row of queryResult.rows) {
9256
- Object.assign(row, ctx.updateData);
9229
+ Object.assign(row, ctx.collect.data);
9257
9230
  }
9258
9231
  }
9259
9232
  };
@@ -9686,8 +9659,8 @@ class Transaction {
9686
9659
  }
9687
9660
 
9688
9661
  var __defProp$2 = Object.defineProperty;
9689
- var __defProps$1 = Object.defineProperties;
9690
- var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
9662
+ var __defProps = Object.defineProperties;
9663
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
9691
9664
  var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
9692
9665
  var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
9693
9666
  var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
@@ -9703,7 +9676,7 @@ var __spreadValues$2 = (a, b) => {
9703
9676
  }
9704
9677
  return a;
9705
9678
  };
9706
- var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
9679
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
9707
9680
  class Headline extends Expression {
9708
9681
  constructor(q, source, params) {
9709
9682
  super();
@@ -9925,7 +9898,7 @@ class SearchMethods {
9925
9898
  const q = this.clone();
9926
9899
  if (!arg.as) {
9927
9900
  const as = saveSearchAlias(q, "@q", "joinedShapes");
9928
- arg = __spreadProps$1(__spreadValues$2({}, arg), {
9901
+ arg = __spreadProps(__spreadValues$2({}, arg), {
9929
9902
  as
9930
9903
  });
9931
9904
  }
@@ -10514,20 +10487,11 @@ class QueryMethods {
10514
10487
  );
10515
10488
  }
10516
10489
  /**
10517
- * The `find` method is available only for tables which has exactly one primary key.
10518
- * And also it can accept raw SQL template literal, then the primary key is not required.
10519
- *
10520
- * Finds a record by id, throws {@link NotFoundError} if not found:
10490
+ * Finds a single record by the primary key (id), throws [NotFoundError](/guide/error-handling.html) if not found.
10491
+ * Not available if the table has no or multiple primary keys.
10521
10492
  *
10522
10493
  * ```ts
10523
- * await db.table.find(1);
10524
- * ```
10525
- *
10526
- * ```ts
10527
- * await db.user.find`
10528
- * age = ${age} AND
10529
- * name = ${name}
10530
- * `;
10494
+ * const result: TableType = await db.table.find(1);
10531
10495
  * ```
10532
10496
  *
10533
10497
  * @param value - primary key value to find by
@@ -10543,7 +10507,7 @@ class QueryMethods {
10543
10507
  return _queryTake(
10544
10508
  _queryWhere(q, [
10545
10509
  {
10546
- [q.singlePrimaryKey]: value
10510
+ [q.internal.singlePrimaryKey]: value
10547
10511
  }
10548
10512
  ])
10549
10513
  );
@@ -10565,8 +10529,8 @@ class QueryMethods {
10565
10529
  return _queryTake(_queryWhereSql(q, args));
10566
10530
  }
10567
10531
  /**
10568
- * Find a single record by the primary key (id), adds `LIMIT 1`.
10569
- * Returns `undefined` when not found.
10532
+ * Finds a single record by the primary key (id), returns `undefined` when not found.
10533
+ * Not available if the table has no or multiple primary keys.
10570
10534
  *
10571
10535
  * ```ts
10572
10536
  * const result: TableType | undefined = await db.table.find(123);
@@ -10596,40 +10560,40 @@ class QueryMethods {
10596
10560
  );
10597
10561
  }
10598
10562
  /**
10599
- * The same as `where(conditions).take()`, takes the same arguments as {@link Where.where}, it will filter records and add a `LIMIT 1`.
10600
- * Throws `NotFoundError` if not found.
10563
+ * Finds a single unique record, throws [NotFoundError](/guide/error-handling.html) if not found.
10564
+ * It accepts values of primary keys or unique indexes defined on the table.
10565
+ * `findBy`'s argument type is a union of all possible sets of unique conditions.
10566
+ *
10567
+ * You can use `where(...).take()` for non-unique conditions.
10601
10568
  *
10602
10569
  * ```ts
10603
- * const result: TableType = await db.table.findBy({ key: 'value' });
10604
- * // is equivalent to:
10605
- * db.table.where({ key: 'value' }).take()
10570
+ * await db.table.findBy({ key: 'value' });
10606
10571
  * ```
10607
10572
  *
10608
- * @param args - `where` conditions
10573
+ * @param uniqueColumnValues - is derived from primary keys and unique indexes in the table
10609
10574
  */
10610
- findBy(...args) {
10611
- return _queryFindBy(
10612
- this.clone(),
10613
- args
10614
- );
10575
+ findBy(uniqueColumnValues) {
10576
+ return _queryFindBy(this.clone(), [
10577
+ uniqueColumnValues
10578
+ ]);
10615
10579
  }
10616
10580
  /**
10617
- * The same as `where(conditions).takeOptional()`, it will filter records and add a `LIMIT 1`.
10618
- * Returns `undefined` when not found.
10581
+ * Finds a single unique record, returns `undefined` if not found.
10582
+ * It accepts values of primary keys or unique indexes defined on the table.
10583
+ * `findBy`'s argument type is a union of all possible sets of unique conditions.
10584
+ *
10585
+ * You can use `where(...).takeOptional()` for non-unique conditions.
10619
10586
  *
10620
10587
  * ```ts
10621
- * const result: TableType | undefined = await db.table.findByOptional({
10622
- * key: 'value',
10623
- * });
10588
+ * await db.table.findByOptional({ key: 'value' });
10624
10589
  * ```
10625
10590
  *
10626
- * @param args - `where` conditions
10591
+ * @param uniqueColumnValues - is derived from primary keys and unique indexes in the table
10627
10592
  */
10628
- findByOptional(...args) {
10629
- return _queryFindByOptional(
10630
- this.clone(),
10631
- args
10632
- );
10593
+ findByOptional(uniqueColumnValues) {
10594
+ return _queryFindByOptional(this.clone(), [
10595
+ uniqueColumnValues
10596
+ ]);
10633
10597
  }
10634
10598
  /**
10635
10599
  * Specifies the schema to be used as a prefix of a table name.
@@ -10775,9 +10739,9 @@ class QueryMethods {
10775
10739
  * Order by raw SQL expression.
10776
10740
  *
10777
10741
  * ```ts
10778
- * db.table.order`raw sql`;
10742
+ * db.table.orderSql`raw sql`;
10779
10743
  * // or
10780
- * db.table.order(db.table.sql`raw sql`);
10744
+ * db.table.orderSql(db.table.sql`raw sql`);
10781
10745
  * ```
10782
10746
  *
10783
10747
  * @param args - SQL expression
@@ -11019,9 +10983,86 @@ applyMixins(QueryMethods, [
11019
10983
  SoftDeleteMethods
11020
10984
  ]);
11021
10985
 
10986
+ const makeIndex = (columns, first, second) => {
10987
+ if (typeof first === "string") {
10988
+ const options = second != null ? second : {};
10989
+ return {
10990
+ index: { columns, options, name: first }
10991
+ };
10992
+ } else {
10993
+ const options = first != null ? first : {};
10994
+ return {
10995
+ index: { columns, options }
10996
+ };
10997
+ }
10998
+ };
10999
+ const tableDataMethods = {
11000
+ primaryKey(columns, name) {
11001
+ return { primaryKey: { columns, name } };
11002
+ },
11003
+ unique(columns, ...[first, second]) {
11004
+ const input = makeIndex(columns, first, second);
11005
+ input.index.options.unique = true;
11006
+ return input;
11007
+ },
11008
+ index: makeIndex,
11009
+ searchIndex(columns, ...[first, second]) {
11010
+ var _a, _b;
11011
+ const input = makeIndex(columns, first, second);
11012
+ (_b = (_a = input.index.options).using) != null ? _b : _a.using = "gin";
11013
+ input.index.options.tsVector = true;
11014
+ return input;
11015
+ },
11016
+ foreignKey(columns, fnOrTable, foreignColumns, options) {
11017
+ return {
11018
+ constraint: {
11019
+ name: options == null ? void 0 : options.name,
11020
+ references: { columns, fnOrTable, foreignColumns, options }
11021
+ }
11022
+ };
11023
+ },
11024
+ check(check, name) {
11025
+ return { constraint: { check, name } };
11026
+ },
11027
+ sql: sqlFn
11028
+ };
11029
+ const parseTableData = (dataFn) => {
11030
+ const tableData = {};
11031
+ if (dataFn) {
11032
+ const input = dataFn(tableDataMethods);
11033
+ if (Array.isArray(input)) {
11034
+ for (const item of input) {
11035
+ parseTableDataInput(tableData, item);
11036
+ }
11037
+ } else {
11038
+ parseTableDataInput(tableData, input);
11039
+ }
11040
+ }
11041
+ return tableData;
11042
+ };
11043
+ const parseTableDataInput = (tableData, item) => {
11044
+ var _a, _b, _c, _d;
11045
+ if (item.primaryKey) {
11046
+ tableData.primaryKey = item.primaryKey;
11047
+ } else if (item.index) {
11048
+ const index = item.index;
11049
+ for (let i = index.columns.length - 1; i >= 0; i--) {
11050
+ if (typeof index.columns[i] === "string") {
11051
+ index.columns[i] = {
11052
+ column: index.columns[i]
11053
+ };
11054
+ }
11055
+ }
11056
+ ((_a = tableData.indexes) != null ? _a : tableData.indexes = []).push(item.index);
11057
+ } else if (item.constraint) {
11058
+ ((_b = tableData.constraints) != null ? _b : tableData.constraints = []).push(item.constraint);
11059
+ if ((_d = (_c = item.constraint.references) == null ? void 0 : _c.options) == null ? void 0 : _d.dropMode) {
11060
+ item.constraint.dropMode = item.constraint.references.options.dropMode;
11061
+ }
11062
+ }
11063
+ };
11064
+
11022
11065
  var __defProp = Object.defineProperty;
11023
- var __defProps = Object.defineProperties;
11024
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
11025
11066
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
11026
11067
  var __hasOwnProp = Object.prototype.hasOwnProperty;
11027
11068
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
@@ -11037,7 +11078,6 @@ var __spreadValues = (a, b) => {
11037
11078
  }
11038
11079
  return a;
11039
11080
  };
11040
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
11041
11081
  var __objRest = (source, exclude) => {
11042
11082
  var target = {};
11043
11083
  for (var prop in source)
@@ -11052,24 +11092,24 @@ var __objRest = (source, exclude) => {
11052
11092
  };
11053
11093
  const anyShape = {};
11054
11094
  class Db {
11055
- constructor(adapter, queryBuilder, table = void 0, shape = anyShape, columnTypes, transactionStorage, options, tableData = getTableData()) {
11095
+ constructor(adapter, queryBuilder, table = void 0, shape = anyShape, columnTypes, transactionStorage, options, tableData = emptyObject) {
11056
11096
  this.adapter = adapter;
11057
11097
  this.queryBuilder = queryBuilder;
11058
11098
  this.table = table;
11059
11099
  this.shape = shape;
11060
11100
  this.columnTypes = columnTypes;
11061
- this.tableData = tableData;
11062
- var _a, _b;
11101
+ var _a;
11063
11102
  const self = this;
11064
11103
  const { softDelete } = options;
11065
11104
  const scopes = options.scopes || softDelete ? {} : emptyObject;
11066
- this.internal = __spreadProps(__spreadValues({}, tableData), {
11105
+ this.internal = {
11067
11106
  transactionStorage,
11068
11107
  scopes,
11069
11108
  snakeCase: options.snakeCase,
11070
11109
  noPrimaryKey: options.noPrimaryKey === "ignore",
11071
- comment: options.comment
11072
- });
11110
+ comment: options.comment,
11111
+ tableData
11112
+ };
11073
11113
  this.baseQuery = this;
11074
11114
  const logger = options.logger || console;
11075
11115
  const parsers = {};
@@ -11130,20 +11170,21 @@ class Db {
11130
11170
  log: logParamToLogObject(logger, options.log),
11131
11171
  autoPreparedStatements: (_a = options.autoPreparedStatements) != null ? _a : false,
11132
11172
  parsers: hasParsers ? parsers : void 0,
11133
- language: options.language
11173
+ language: options.language,
11174
+ schema: options == null ? void 0 : options.schema
11134
11175
  };
11135
- if (options == null ? void 0 : options.schema) {
11136
- this.q.schema = options.schema;
11176
+ let shapeHasPrimaryKey;
11177
+ for (const key in shape) {
11178
+ if (shape[key].data.primaryKey) {
11179
+ shapeHasPrimaryKey = true;
11180
+ if (this.internal.singlePrimaryKey) {
11181
+ this.internal.singlePrimaryKey = void 0;
11182
+ break;
11183
+ }
11184
+ this.internal.singlePrimaryKey = key;
11185
+ }
11137
11186
  }
11138
- this.primaryKeys = Object.keys(shape).filter(
11139
- (key) => shape[key].data.primaryKey
11140
- );
11141
- const primaryKeysFromData = (_b = getTableData().primaryKey) == null ? void 0 : _b.columns;
11142
- if (primaryKeysFromData)
11143
- this.primaryKeys.push(...primaryKeysFromData);
11144
- if (this.primaryKeys.length === 1) {
11145
- this.singlePrimaryKey = this.primaryKeys[0];
11146
- } else if (this.primaryKeys.length === 0 && shape !== anyShape && options.noPrimaryKey !== "ignore") {
11187
+ if (!shapeHasPrimaryKey && !tableData.primaryKey && shape !== anyShape && options.noPrimaryKey !== "ignore") {
11147
11188
  const message = `Table ${table} has no primary key`;
11148
11189
  if (options.noPrimaryKey === "error")
11149
11190
  throw new Error(message);
@@ -11339,14 +11380,15 @@ const createDb = (_a) => {
11339
11380
  commonOptions,
11340
11381
  options
11341
11382
  );
11342
- const tableConstructor = (table, shape, options2) => new Db(
11383
+ const tableConstructor = (table, shape, dataFn, options2) => new Db(
11343
11384
  adapter,
11344
11385
  qb,
11345
11386
  table,
11346
11387
  typeof shape === "function" ? getColumnTypes(ct, shape, nowSQL, options2 == null ? void 0 : options2.language) : shape,
11347
11388
  ct,
11348
11389
  transactionStorage,
11349
- __spreadValues(__spreadValues({}, commonOptions), options2)
11390
+ __spreadValues(__spreadValues({}, commonOptions), options2),
11391
+ parseTableData(dataFn)
11350
11392
  );
11351
11393
  const db = Object.assign(tableConstructor, qb, {
11352
11394
  adapter,
@@ -11365,8 +11407,7 @@ const _initQueryBuilder = (adapter, columnTypes, transactionStorage, commonOptio
11365
11407
  anyShape,
11366
11408
  columnTypes,
11367
11409
  transactionStorage,
11368
- commonOptions,
11369
- emptyObject
11410
+ commonOptions
11370
11411
  );
11371
11412
  if (options.extensions) {
11372
11413
  const arr = [];
@@ -11516,5 +11557,5 @@ function copyTableData(query, arg) {
11516
11557
  return q;
11517
11558
  }
11518
11559
 
11519
- export { Adapter, AggregateMethods, ArrayColumn, AsMethods, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CharColumn, CidrColumn, CircleColumn, CitextColumn, Clear, ColumnRefExpression, ColumnType, Create, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DecimalColumn, Delete, DomainColumn, DoublePrecisionColumn, DynamicRawSQL, EnumColumn, FnExpression, For, From, Having, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, Join, JsonMethods, JsonModifiers, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, OnConflictQueryBuilder, OnMethods, Operators, OrchidOrmError, OrchidOrmInternalError, PathColumn, PointColumn, PolygonColumn, QueryBase, QueryError, QueryGet, QueryHooks, QueryLog, QueryMethods, QueryUpsertOrCreate, RawSQL, RawSqlMethods, RealColumn, SearchMethods, Select, SerialColumn, SmallIntColumn, SmallSerialColumn, StringColumn, TextBaseColumn, TextColumn, Then, TimeColumn, TimestampColumn, TimestampTZColumn, Transaction, TransactionAdapter, TransformMethods, TsQueryColumn, TsVectorColumn, UUIDColumn, UnhandledTypeError, Union, UnknownColumn, Update, VarCharColumn, VirtualColumn, Where, With, XMLColumn, _initQueryBuilder, _queryAfterSaveCommit, _queryAll, _queryAs, _queryChangeCounter, _queryCreate, _queryCreateFrom, _queryCreateMany, _queryCreateManyFrom, _queryCreateManyRaw, _queryCreateRaw, _queryDefaults, _queryDelete, _queryExec, _queryFindBy, _queryFindByOptional, _queryGet, _queryGetOptional, _queryHookAfterCreate, _queryHookAfterCreateCommit, _queryHookAfterDelete, _queryHookAfterDeleteCommit, _queryHookAfterQuery, _queryHookAfterSave, _queryHookAfterUpdate, _queryHookAfterUpdateCommit, _queryHookBeforeCreate, _queryHookBeforeDelete, _queryHookBeforeQuery, _queryHookBeforeSave, _queryHookBeforeUpdate, _queryInsert, _queryInsertFrom, _queryInsertMany, _queryInsertManyFrom, _queryInsertManyRaw, _queryInsertRaw, _queryJoinOn, _queryJoinOnJsonPathEquals, _queryJoinOrOn, _queryOr, _queryOrNot, _queryRows, _querySelect, _queryTake, _queryTakeOptional, _queryUpdate, _queryUpdateOrThrow, _queryUpdateRaw, _queryWhere, _queryWhereExists, _queryWhereIn, _queryWhereNot, _queryWhereNotSql, _queryWhereSql, addComputedColumns, addParserForRawExpression, addParserForSelectItem, addQueryOn, anyShape, checkIfASimpleQuery, cloneQuery, cloneQueryBaseUnscoped, columnCheckToCode, columnCode, columnForeignKeysToCode, columnIndexesToCode, columnsShapeToCode, constraintInnerToCode, constraintPropsToCode, constraintToCode, copyTableData, countSelect, createDb, defaultSchemaConfig, extendQuery, foreignKeyArgumentToCode, getClonedQueryData, getColumnInfo, getColumnTypes, getConstraintKind, getQueryAs, getShapeFromSelect, getTableData, handleResult, identityToCode, indexInnerToCode, indexToCode, instantiateColumn, isDefaultTimeStamp, isQueryReturnsAll, isSelectingCount, joinSubQuery, logColors, logParamToLogObject, makeColumnTypes, makeColumnsByType, makeExpression, makeFnExpression, makeRegexToFindInSql, makeSQL, newTableData, parseRecord, parseResult, primaryKeyInnerToCode, primaryKeyToCode, processSelectArg, pushLimitSQL, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, queryFrom, queryFromSql, queryJson, queryMethodByReturnType, queryTypeWithLimitOne, queryWrap, quote, quoteString, raw, referencesArgsToCode, resetTableData, resolveSubQueryCallback, saveSearchAlias, setParserForSelectedString, setQueryObjectValue, setQueryOperators, simplifyColumnDefault, sqlQueryArgsToExpression, templateLiteralToSQL, testTransaction, throwIfNoWhere, toSQL, toSQLCacheKey };
11560
+ export { Adapter, AggregateMethods, ArrayColumn, AsMethods, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CharColumn, CidrColumn, CircleColumn, CitextColumn, Clear, ColumnRefExpression, ColumnType, Create, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DecimalColumn, Delete, DomainColumn, DoublePrecisionColumn, DynamicRawSQL, EnumColumn, FnExpression, For, From, Having, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, Join, JsonMethods, JsonModifiers, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, OnConflictQueryBuilder, OnMethods, Operators, OrchidOrmError, OrchidOrmInternalError, PathColumn, PointColumn, PolygonColumn, QueryBase, QueryError, QueryGet, QueryHooks, QueryLog, QueryMethods, QueryUpsertOrCreate, RawSQL, RawSqlMethods, RealColumn, SearchMethods, Select, SerialColumn, SmallIntColumn, SmallSerialColumn, StringColumn, TextBaseColumn, TextColumn, Then, TimeColumn, TimestampColumn, TimestampTZColumn, Transaction, TransactionAdapter, TransformMethods, TsQueryColumn, TsVectorColumn, UUIDColumn, UnhandledTypeError, Union, UnknownColumn, Update, VarCharColumn, VirtualColumn, Where, With, XMLColumn, _initQueryBuilder, _queryAfterSaveCommit, _queryAll, _queryAs, _queryChangeCounter, _queryCreate, _queryCreateFrom, _queryCreateMany, _queryCreateManyFrom, _queryCreateManyRaw, _queryCreateRaw, _queryDefaults, _queryDelete, _queryExec, _queryFindBy, _queryFindByOptional, _queryGet, _queryGetOptional, _queryHookAfterCreate, _queryHookAfterCreateCommit, _queryHookAfterDelete, _queryHookAfterDeleteCommit, _queryHookAfterQuery, _queryHookAfterSave, _queryHookAfterUpdate, _queryHookAfterUpdateCommit, _queryHookBeforeCreate, _queryHookBeforeDelete, _queryHookBeforeQuery, _queryHookBeforeSave, _queryHookBeforeUpdate, _queryInsert, _queryInsertFrom, _queryInsertMany, _queryInsertManyFrom, _queryInsertManyRaw, _queryInsertRaw, _queryJoinOn, _queryJoinOnJsonPathEquals, _queryJoinOrOn, _queryOr, _queryOrNot, _queryRows, _querySelect, _queryTake, _queryTakeOptional, _queryUpdate, _queryUpdateOrThrow, _queryUpdateRaw, _queryWhere, _queryWhereExists, _queryWhereIn, _queryWhereNot, _queryWhereNotSql, _queryWhereSql, addComputedColumns, addParserForRawExpression, addParserForSelectItem, addQueryOn, anyShape, checkIfASimpleQuery, cloneQuery, cloneQueryBaseUnscoped, columnCheckToCode, columnCode, columnForeignKeysToCode, columnIndexesToCode, columnsShapeToCode, constraintInnerToCode, constraintToCode, copyTableData, countSelect, createDb, defaultSchemaConfig, extendQuery, foreignKeyArgumentToCode, getClonedQueryData, getColumnInfo, getColumnTypes, getPrimaryKeys, getQueryAs, getShapeFromSelect, handleResult, identityToCode, indexInnerToCode, indexToCode, instantiateColumn, isDefaultTimeStamp, isQueryReturnsAll, isSelectingCount, joinSubQuery, logColors, logParamToLogObject, makeColumnTypes, makeColumnsByType, makeExpression, makeFnExpression, makeRegexToFindInSql, makeSQL, parseRecord, parseResult, parseTableData, parseTableDataInput, primaryKeyInnerToCode, processSelectArg, pushLimitSQL, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, pushTableDataCode, queryFrom, queryFromSql, queryJson, queryMethodByReturnType, queryTypeWithLimitOne, queryWrap, quote, quoteString, raw, referencesArgsToCode, resolveSubQueryCallback, saveSearchAlias, setParserForSelectedString, setQueryObjectValue, setQueryOperators, simplifyColumnDefault, sqlFn, sqlQueryArgsToExpression, tableDataMethods, templateLiteralToSQL, testTransaction, throwIfNoWhere, toSQL, toSQLCacheKey };
11520
11561
  //# sourceMappingURL=index.mjs.map