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.js CHANGED
@@ -101,10 +101,23 @@ const countSelect = [new RawSQL("count(*)")];
101
101
  function sqlQueryArgsToExpression(args) {
102
102
  return Array.isArray(args[0]) ? new RawSQL(args) : args[0];
103
103
  }
104
+ const sqlFn = (...args) => {
105
+ const arg = args[0];
106
+ if (Array.isArray(arg)) {
107
+ return new RawSQL(args);
108
+ }
109
+ if (typeof args[0] === "string") {
110
+ return new RawSQL(args[0]);
111
+ }
112
+ if (args[1] !== void 0) {
113
+ return new RawSQL(args[1], arg);
114
+ }
115
+ return (...args2) => new RawSQL(args2, arg);
116
+ };
104
117
 
105
118
  var __defProp$h = Object.defineProperty;
106
- var __defProps$b = Object.defineProperties;
107
- var __getOwnPropDescs$b = Object.getOwnPropertyDescriptors;
119
+ var __defProps$9 = Object.defineProperties;
120
+ var __getOwnPropDescs$9 = Object.getOwnPropertyDescriptors;
108
121
  var __getOwnPropSymbols$i = Object.getOwnPropertySymbols;
109
122
  var __hasOwnProp$i = Object.prototype.hasOwnProperty;
110
123
  var __propIsEnum$i = Object.prototype.propertyIsEnumerable;
@@ -120,7 +133,7 @@ var __spreadValues$h = (a, b) => {
120
133
  }
121
134
  return a;
122
135
  };
123
- var __spreadProps$b = (a, b) => __defProps$b(a, __getOwnPropDescs$b(b));
136
+ var __spreadProps$9 = (a, b) => __defProps$9(a, __getOwnPropDescs$9(b));
124
137
  class ColumnType extends orchidCore.ColumnTypeBase {
125
138
  /**
126
139
  * Mark the column as a primary key.
@@ -135,6 +148,8 @@ class ColumnType extends orchidCore.ColumnTypeBase {
135
148
  * readonly table = 'table';
136
149
  * columns = this.setColumns((t) => ({
137
150
  * id: t.uuid().primaryKey(),
151
+ * // database-level name can be passed:
152
+ * id: t.uuid().primaryKey('primary_key_name'),
138
153
  * }));
139
154
  * }
140
155
  *
@@ -142,21 +157,76 @@ class ColumnType extends orchidCore.ColumnTypeBase {
142
157
  * db.table.find('97ba9e78-7510-415a-9c03-23d440aec443');
143
158
  * ```
144
159
  *
145
- * @param options - to specify a constraint name
160
+ * @param name - to specify a constraint name
146
161
  */
147
- primaryKey(options) {
148
- var _a;
149
- return orchidCore.setColumnData(this, "primaryKey", (_a = options == null ? void 0 : options.name) != null ? _a : true);
162
+ primaryKey(name) {
163
+ return orchidCore.setColumnData(this, "primaryKey", name != null ? name : true);
150
164
  }
151
165
  foreignKey(fnOrTable, column, options = orchidCore.emptyObject) {
152
- const item = typeof fnOrTable === "string" ? __spreadValues$h({ table: fnOrTable, columns: [column] }, options) : __spreadValues$h({ fn: fnOrTable, columns: [column] }, options);
153
- return orchidCore.pushColumnData(this, "foreignKeys", item);
166
+ return orchidCore.pushColumnData(this, "foreignKeys", {
167
+ fnOrTable,
168
+ foreignColumns: [column],
169
+ options
170
+ });
154
171
  }
155
172
  toSQL() {
156
173
  return this.dataType;
157
174
  }
158
- index(options = {}) {
159
- return orchidCore.pushColumnData(this, "indexes", options);
175
+ /**
176
+ * Add an index to the column.
177
+ *
178
+ * ```ts
179
+ * import { change } from '../dbScript';
180
+ *
181
+ * change(async (db) => {
182
+ * await db.createTable('table', (t) => ({
183
+ * // add an index to the name column with default settings:
184
+ * name: t.text().index(),
185
+ * // options are described below:
186
+ * name: t.text().index({ ...options }),
187
+ * // with a database-level name:
188
+ * name: t.text().index('custom_index_name'),
189
+ * // with name and options:
190
+ * name: t.text().index('custom_index_name', { ...options }),
191
+ * }));
192
+ * });
193
+ * ```
194
+ *
195
+ * Possible options are:
196
+ *
197
+ * ```ts
198
+ * type IndexOptions = {
199
+ * // NULLS NOT DISTINCT: availabe in Postgres 15+, makes sense only for unique index
200
+ * nullsNotDistinct?: true;
201
+ * // index algorithm to use such as GIST, GIN
202
+ * using?: string;
203
+ * // specify collation:
204
+ * collate?: string;
205
+ * // see `opclass` in the Postgres document for creating the index
206
+ * opclass?: string;
207
+ * // specify index order such as ASC NULLS FIRST, DESC NULLS LAST
208
+ * order?: string;
209
+ * // include columns to an index to optimize specific queries
210
+ * include?: MaybeArray<string>;
211
+ * // see "storage parameters" in the Postgres document for creating an index, for example, 'fillfactor = 70'
212
+ * with?: string;
213
+ * // The tablespace in which to create the index. If not specified, default_tablespace is consulted, or temp_tablespaces for indexes on temporary tables.
214
+ * tablespace?: string;
215
+ * // WHERE clause to filter records for the index
216
+ * where?: string;
217
+ * // mode is for dropping the index
218
+ * mode?: 'CASCADE' | 'RESTRICT';
219
+ * };
220
+ * ```
221
+ *
222
+ * @param args
223
+ */
224
+ index(...args) {
225
+ var _a;
226
+ return orchidCore.pushColumnData(this, "indexes", {
227
+ options: (_a = typeof args[0] === "string" ? args[1] : args[0]) != null ? _a : orchidCore.emptyObject,
228
+ name: typeof args[0] === "string" ? args[0] : void 0
229
+ });
160
230
  }
161
231
  /**
162
232
  * `searchIndex` is designed for [full text search](/guide/text-search).
@@ -260,11 +330,19 @@ class ColumnType extends orchidCore.ColumnTypeBase {
260
330
  *
261
331
  * @param options - index options
262
332
  */
263
- searchIndex(options) {
264
- return orchidCore.pushColumnData(this, "indexes", __spreadValues$h(__spreadValues$h({}, options), this.dataType === "tsvector" ? { using: "GIN" } : { tsVector: true }));
333
+ searchIndex(...args) {
334
+ return orchidCore.pushColumnData(this, "indexes", {
335
+ options: __spreadValues$h(__spreadValues$h({}, typeof args[0] === "string" ? args[1] : args[0]), this.dataType === "tsvector" ? { using: "GIN" } : { tsVector: true }),
336
+ name: typeof args[0] === "string" ? args[0] : void 0
337
+ });
265
338
  }
266
- unique(options = {}) {
267
- return orchidCore.pushColumnData(this, "indexes", __spreadProps$b(__spreadValues$h({}, options), { unique: true }));
339
+ unique(...args) {
340
+ return orchidCore.pushColumnData(this, "indexes", {
341
+ options: __spreadProps$9(__spreadValues$h({}, typeof args[0] === "string" ? args[1] : args[0]), {
342
+ unique: true
343
+ }),
344
+ name: typeof args[0] === "string" ? args[0] : void 0
345
+ });
268
346
  }
269
347
  comment(comment) {
270
348
  return orchidCore.setColumnData(this, "comment", comment);
@@ -303,8 +381,8 @@ class ColumnType extends orchidCore.ColumnTypeBase {
303
381
  }
304
382
 
305
383
  var __defProp$g = Object.defineProperty;
306
- var __defProps$a = Object.defineProperties;
307
- var __getOwnPropDescs$a = Object.getOwnPropertyDescriptors;
384
+ var __defProps$8 = Object.defineProperties;
385
+ var __getOwnPropDescs$8 = Object.getOwnPropertyDescriptors;
308
386
  var __getOwnPropSymbols$h = Object.getOwnPropertySymbols;
309
387
  var __hasOwnProp$h = Object.prototype.hasOwnProperty;
310
388
  var __propIsEnum$h = Object.prototype.propertyIsEnumerable;
@@ -320,7 +398,7 @@ var __spreadValues$g = (a, b) => {
320
398
  }
321
399
  return a;
322
400
  };
323
- var __spreadProps$a = (a, b) => __defProps$a(a, __getOwnPropDescs$a(b));
401
+ var __spreadProps$8 = (a, b) => __defProps$8(a, __getOwnPropDescs$8(b));
324
402
  const knownDefaults = {
325
403
  current_timestamp: "now()",
326
404
  "transaction_timestamp()": "now()"
@@ -336,7 +414,7 @@ const simplifyColumnDefault = (value) => {
336
414
  const instantiateColumn = (typeFn, params) => {
337
415
  const column = typeFn();
338
416
  const { dateTimePrecision } = params;
339
- Object.assign(column.data, __spreadProps$a(__spreadValues$g({}, params), {
417
+ Object.assign(column.data, __spreadProps$8(__spreadValues$g({}, params), {
340
418
  dateTimePrecision: (
341
419
  // 0 is default for date, 6 is default for timestamp
342
420
  dateTimePrecision && dateTimePrecision !== 6 ? dateTimePrecision : void 0
@@ -346,15 +424,6 @@ const instantiateColumn = (typeFn, params) => {
346
424
  }));
347
425
  return column;
348
426
  };
349
- const getConstraintKind = (it) => {
350
- let num = 0;
351
- for (const key in it) {
352
- if ((key === "references" || key === "check") && it[key] !== void 0) {
353
- num++;
354
- }
355
- }
356
- return num === 1 ? it.references ? "foreignKey" : "check" : "constraint";
357
- };
358
427
 
359
428
  const isDefaultTimeStamp = (item) => {
360
429
  if (item.dataType !== "timestamptz")
@@ -382,7 +451,7 @@ const combineCodeElements = (input) => {
382
451
  }
383
452
  return output;
384
453
  };
385
- const columnsShapeToCode = (shape, tableData, t, m) => {
454
+ const columnsShapeToCode = (shape, t) => {
386
455
  const hasTimestamps = "createdAt" in shape && isDefaultTimeStamp(shape.createdAt) && "updatedAt" in shape && isDefaultTimeStamp(shape.updatedAt);
387
456
  const code = [];
388
457
  for (const key in shape) {
@@ -399,33 +468,40 @@ const columnsShapeToCode = (shape, tableData, t, m) => {
399
468
  if (hasTimestamps) {
400
469
  code.push(`...${t}.timestamps(),`);
401
470
  }
402
- const { primaryKey, indexes, constraints } = tableData;
403
- if (primaryKey) {
404
- code.push(primaryKeyToCode(primaryKey, t));
471
+ return code;
472
+ };
473
+ const pushTableDataCode = (code, ast) => {
474
+ const lines = [];
475
+ if (ast.primaryKey) {
476
+ lines.push([primaryKeyInnerToCode(ast.primaryKey, "t") + ","]);
405
477
  }
406
- if (indexes) {
407
- for (const index of indexes) {
408
- code.push(...indexToCode(index, t));
478
+ if (ast.indexes) {
479
+ for (const index of ast.indexes) {
480
+ lines.push(indexToCode(index, "t"));
409
481
  }
410
482
  }
411
- if (constraints) {
412
- for (const item of constraints) {
413
- code.push(...constraintToCode(item, t, m));
483
+ if (ast.constraints) {
484
+ for (const constraint of ast.constraints) {
485
+ lines.push(constraintToCode(constraint, "t", true));
414
486
  }
415
487
  }
488
+ if (lines.length > 1) {
489
+ code.push("(t) => [", ...lines, "],");
490
+ } else if (lines[0].length === 1 && typeof lines[0][0] === "string") {
491
+ code.push("(t) => " + lines[0][0]);
492
+ } else {
493
+ code.push("(t) => ", lines[0]);
494
+ }
416
495
  return code;
417
496
  };
418
- const primaryKeyToCode = (primaryKey, t) => {
419
- return `...${primaryKeyInnerToCode(primaryKey, t)},`;
420
- };
421
497
  const primaryKeyInnerToCode = (primaryKey, t) => {
422
- var _a;
423
- const name = (_a = primaryKey.options) == null ? void 0 : _a.name;
424
- return `${t}.primaryKey([${primaryKey.columns.map(orchidCore.singleQuote).join(", ")}]${name ? `, { name: ${orchidCore.singleQuote(name)} }` : ""})`;
498
+ const name = primaryKey.name;
499
+ return `${t}.primaryKey([${primaryKey.columns.map(orchidCore.singleQuote).join(", ")}]${name ? `, ${orchidCore.singleQuote(name)}` : ""})`;
425
500
  };
426
- const indexToCode = (index, t) => {
501
+ const indexToCode = (index, t, prefix) => {
427
502
  const code = indexInnerToCode(index, t);
428
- code[0] = `...${code[0]}`;
503
+ if (prefix)
504
+ code[0] = prefix + code[0];
429
505
  const last = code[code.length - 1];
430
506
  if (typeof last === "string" && !last.endsWith(","))
431
507
  orchidCore.addCode(code, ",");
@@ -437,6 +513,19 @@ const indexInnerToCode = (index, t) => {
437
513
  `${t}.${index.options.tsVector ? "searchIndex" : index.options.unique ? "unique" : "index"}(`
438
514
  );
439
515
  const columnOptions = ["collate", "opclass", "order", "weight"];
516
+ const indexOptionsKeys = [
517
+ index.options.tsVector ? "unique" : void 0,
518
+ "using",
519
+ "nullsNotDistinct",
520
+ "include",
521
+ "with",
522
+ "tablespace",
523
+ "where",
524
+ "language",
525
+ "languageColumn",
526
+ "dropMode"
527
+ ];
528
+ const hasOptions = indexOptionsKeys.some((key) => key && index.options[key]);
440
529
  const columnsMultiline = index.columns.some((column) => {
441
530
  for (const key in column) {
442
531
  if (key !== "column" && column[key] !== void 0)
@@ -448,13 +537,13 @@ const indexInnerToCode = (index, t) => {
448
537
  const objects = [];
449
538
  for (const column of index.columns) {
450
539
  const expr = "column" in column ? column.column : column.expression;
451
- let hasOptions = false;
540
+ let hasOptions2 = false;
452
541
  for (const key in column) {
453
542
  if (key !== "column") {
454
- hasOptions = true;
543
+ hasOptions2 = true;
455
544
  }
456
545
  }
457
- if (!hasOptions) {
546
+ if (!hasOptions2) {
458
547
  objects.push(`${orchidCore.singleQuote(expr)},`);
459
548
  } else {
460
549
  const props = [
@@ -471,38 +560,29 @@ const indexInnerToCode = (index, t) => {
471
560
  objects.push("{", props, "},");
472
561
  }
473
562
  }
474
- code.push(["[", objects, "]"]);
563
+ code.push(["[", objects, hasOptions || index.name ? "]," : "]"]);
564
+ if (index.name) {
565
+ orchidCore.addCode(code, ` ${orchidCore.singleQuote(index.name)},`);
566
+ }
475
567
  } else {
476
568
  orchidCore.addCode(
477
569
  code,
478
570
  `[${index.columns.map((it) => orchidCore.singleQuote(it.column)).join(", ")}]`
479
571
  );
572
+ if (index.name) {
573
+ orchidCore.addCode(code, `, ${orchidCore.singleQuote(index.name)}`);
574
+ }
480
575
  }
481
- const indexOptionsKeys = [
482
- "name",
483
- "using",
484
- "nullsNotDistinct",
485
- "include",
486
- "with",
487
- "tablespace",
488
- "where",
489
- "language",
490
- "languageColumn",
491
- "dropMode"
492
- ];
493
- if (index.options.tsVector && index.options.unique) {
494
- indexOptionsKeys.unshift("unique");
495
- }
496
- if (indexOptionsKeys.some((key) => index.options[key])) {
576
+ if (hasOptions) {
497
577
  if (columnsMultiline) {
498
- const columns = code[code.length - 1];
499
- columns[columns.length - 1] += ",";
500
578
  code.push(["{"]);
501
579
  } else {
502
580
  orchidCore.addCode(code, ", {");
503
581
  }
504
582
  const options = [];
505
583
  for (const key of indexOptionsKeys) {
584
+ if (!key)
585
+ continue;
506
586
  const value = index.options[key];
507
587
  if (value === null || value === void 0)
508
588
  continue;
@@ -524,46 +604,26 @@ const indexInnerToCode = (index, t) => {
524
604
  }
525
605
  return code;
526
606
  };
527
- const constraintToCode = (item, t, m) => {
607
+ const constraintToCode = (item, t, m, prefix) => {
528
608
  const code = constraintInnerToCode(item, t, m);
529
- code[0] = `...${code[0]}`;
609
+ if (prefix)
610
+ code[0] = prefix + code[0];
530
611
  const last = code[code.length - 1];
531
612
  if (typeof last === "string" && !last.endsWith(","))
532
613
  code[code.length - 1] += ",";
533
614
  return code;
534
615
  };
535
616
  const constraintInnerToCode = (item, t, m) => {
536
- const kind = getConstraintKind(item);
537
- if (kind === "foreignKey" && item.references) {
617
+ if (item.references) {
538
618
  return [
539
619
  `${t}.foreignKey(`,
540
620
  referencesArgsToCode(item.references, item.name, m),
541
621
  "),"
542
622
  ];
543
- } else if (kind === "check" && item.check) {
544
- return [
545
- `${t}.check(${item.check.toCode(t)}${item.name ? `, { name: '${item.name}' }` : ""})`
546
- ];
547
- } else {
548
- return [`${t}.constraint({`, constraintPropsToCode(t, item, m), "}),"];
549
- }
550
- };
551
- const constraintPropsToCode = (t, item, m) => {
552
- const props = [];
553
- if (item.name) {
554
- props.push(`name: ${orchidCore.singleQuote(item.name)},`);
555
- }
556
- if (item.references) {
557
- props.push(
558
- `references: [`,
559
- referencesArgsToCode(item.references, false, m),
560
- "],"
561
- );
562
- }
563
- if (item.check) {
564
- props.push(`check: ${item.check.toCode(t)},`);
565
623
  }
566
- return props;
624
+ return [
625
+ `${t}.check(${item.check.toCode(t)}${item.name ? `, ${orchidCore.singleQuote(item.name)}` : ""})`
626
+ ];
567
627
  };
568
628
  const referencesArgsToCode = ({
569
629
  columns,
@@ -607,9 +667,12 @@ const columnForeignKeysToCode = (foreignKeys, migration) => {
607
667
  }
608
668
  return code;
609
669
  };
610
- const foreignKeyArgumentToCode = (foreignKey, migration) => {
670
+ const foreignKeyArgumentToCode = ({
671
+ fnOrTable,
672
+ foreignColumns,
673
+ options = orchidCore.emptyObject
674
+ }, migration) => {
611
675
  const code = [];
612
- let fnOrTable = "fn" in foreignKey ? foreignKey.fn : foreignKey.table;
613
676
  if (migration && typeof fnOrTable !== "string") {
614
677
  const { schema, table } = new (fnOrTable())();
615
678
  fnOrTable = schema ? `${schema}.${table}` : table;
@@ -617,18 +680,18 @@ const foreignKeyArgumentToCode = (foreignKey, migration) => {
617
680
  code.push(
618
681
  typeof fnOrTable === "string" ? orchidCore.singleQuote(fnOrTable) : fnOrTable.toString()
619
682
  );
620
- orchidCore.addCode(code, `, ${orchidCore.singleQuote(foreignKey.columns[0])}`);
621
- const hasOptions = foreignKey.name || foreignKey.match || foreignKey.onUpdate || foreignKey.onDelete;
683
+ orchidCore.addCode(code, `, ${orchidCore.singleQuote(foreignColumns[0])}`);
684
+ const hasOptions = options.name || options.match || options.onUpdate || options.onDelete;
622
685
  if (hasOptions) {
623
686
  const arr = [];
624
- if (foreignKey.name)
625
- arr.push(`name: ${orchidCore.singleQuote(foreignKey.name)},`);
626
- if (foreignKey.match)
627
- arr.push(`match: ${orchidCore.singleQuote(foreignKey.match)},`);
628
- if (foreignKey.onUpdate)
629
- arr.push(`onUpdate: ${orchidCore.singleQuote(foreignKey.onUpdate)},`);
630
- if (foreignKey.onDelete)
631
- arr.push(`onDelete: ${orchidCore.singleQuote(foreignKey.onDelete)},`);
687
+ if (options.name)
688
+ arr.push(`name: ${orchidCore.singleQuote(options.name)},`);
689
+ if (options.match)
690
+ arr.push(`match: ${orchidCore.singleQuote(options.match)},`);
691
+ if (options.onUpdate)
692
+ arr.push(`onUpdate: ${orchidCore.singleQuote(options.onUpdate)},`);
693
+ if (options.onDelete)
694
+ arr.push(`onDelete: ${orchidCore.singleQuote(options.onDelete)},`);
632
695
  orchidCore.addCode(code, ", {");
633
696
  code.push(arr);
634
697
  orchidCore.addCode(code, "}");
@@ -637,31 +700,31 @@ const foreignKeyArgumentToCode = (foreignKey, migration) => {
637
700
  };
638
701
  const columnIndexesToCode = (indexes) => {
639
702
  const code = [];
640
- for (const index of indexes) {
641
- orchidCore.addCode(code, `.${index.unique ? "unique" : "index"}(`);
703
+ for (const { options, name } of indexes) {
704
+ orchidCore.addCode(code, `.${options.unique ? "unique" : "index"}(`);
642
705
  const arr = [];
643
- if (index.collate)
644
- arr.push(`collate: ${orchidCore.singleQuote(index.collate)},`);
645
- if (index.opclass)
646
- arr.push(`opclass: ${orchidCore.singleQuote(index.opclass)},`);
647
- if (index.order)
648
- arr.push(`order: ${orchidCore.singleQuote(index.order)},`);
649
- if (index.name)
650
- arr.push(`name: ${orchidCore.singleQuote(index.name)},`);
651
- if (index.using)
652
- arr.push(`using: ${orchidCore.singleQuote(index.using)},`);
653
- if (index.include)
706
+ if (options.collate)
707
+ arr.push(`collate: ${orchidCore.singleQuote(options.collate)},`);
708
+ if (options.opclass)
709
+ arr.push(`opclass: ${orchidCore.singleQuote(options.opclass)},`);
710
+ if (options.order)
711
+ arr.push(`order: ${orchidCore.singleQuote(options.order)},`);
712
+ if (name)
713
+ arr.push(`name: ${orchidCore.singleQuote(name)},`);
714
+ if (options.using)
715
+ arr.push(`using: ${orchidCore.singleQuote(options.using)},`);
716
+ if (options.include)
654
717
  arr.push(
655
- `include: ${typeof index.include === "string" ? orchidCore.singleQuote(index.include) : `[${index.include.map(orchidCore.singleQuote).join(", ")}]`},`
718
+ `include: ${typeof options.include === "string" ? orchidCore.singleQuote(options.include) : `[${options.include.map(orchidCore.singleQuote).join(", ")}]`},`
656
719
  );
657
- if (index.nullsNotDistinct)
720
+ if (options.nullsNotDistinct)
658
721
  arr.push(`nullsNotDistinct: true,`);
659
- if (index.with)
660
- arr.push(`with: ${orchidCore.singleQuote(index.with)},`);
661
- if (index.tablespace)
662
- arr.push(`tablespace: ${orchidCore.singleQuote(index.tablespace)},`);
663
- if (index.where)
664
- arr.push(`where: ${orchidCore.singleQuote(index.where)},`);
722
+ if (options.with)
723
+ arr.push(`with: ${orchidCore.singleQuote(options.with)},`);
724
+ if (options.tablespace)
725
+ arr.push(`tablespace: ${orchidCore.singleQuote(options.tablespace)},`);
726
+ if (options.where)
727
+ arr.push(`where: ${orchidCore.singleQuote(options.where)},`);
665
728
  if (arr.length) {
666
729
  orchidCore.addCode(code, "{");
667
730
  orchidCore.addCode(code, arr);
@@ -671,8 +734,8 @@ const columnIndexesToCode = (indexes) => {
671
734
  }
672
735
  return code;
673
736
  };
674
- const columnCheckToCode = (t, { sql, options }) => {
675
- return `.check(${sql.toCode(t)}${(options == null ? void 0 : options.name) ? `, { name: '${options.name}' }` : ""})`;
737
+ const columnCheckToCode = (t, { sql, name }) => {
738
+ return `.check(${sql.toCode(t)}${name ? `, { name: '${name}' }` : ""})`;
676
739
  };
677
740
  const identityToCode = (identity, dataType) => {
678
741
  const code = [];
@@ -717,7 +780,7 @@ const columnCode = (type, t, code, migration, data = type.data, skip) => {
717
780
  if (data.primaryKey) {
718
781
  orchidCore.addCode(
719
782
  code,
720
- `.primaryKey(${data.primaryKey === true ? "" : `{ name: '${data.primaryKey}' }`})`
783
+ `.primaryKey(${data.primaryKey === true ? "" : orchidCore.singleQuote(data.primaryKey)})`
721
784
  );
722
785
  }
723
786
  if (data.foreignKeys) {
@@ -1205,8 +1268,8 @@ const pushIn = (ctx, query, ands, quotedAs, arg) => {
1205
1268
  };
1206
1269
 
1207
1270
  var __defProp$f = Object.defineProperty;
1208
- var __defProps$9 = Object.defineProperties;
1209
- var __getOwnPropDescs$9 = Object.getOwnPropertyDescriptors;
1271
+ var __defProps$7 = Object.defineProperties;
1272
+ var __getOwnPropDescs$7 = Object.getOwnPropertyDescriptors;
1210
1273
  var __getOwnPropSymbols$g = Object.getOwnPropertySymbols;
1211
1274
  var __hasOwnProp$g = Object.prototype.hasOwnProperty;
1212
1275
  var __propIsEnum$g = Object.prototype.propertyIsEnumerable;
@@ -1222,7 +1285,7 @@ var __spreadValues$f = (a, b) => {
1222
1285
  }
1223
1286
  return a;
1224
1287
  };
1225
- var __spreadProps$9 = (a, b) => __defProps$9(a, __getOwnPropDescs$9(b));
1288
+ var __spreadProps$7 = (a, b) => __defProps$7(a, __getOwnPropDescs$7(b));
1226
1289
  const processJoinItem = (ctx, table, query, args, quotedAs) => {
1227
1290
  let target;
1228
1291
  let on;
@@ -1284,8 +1347,8 @@ const processJoinItem = (ctx, table, query, args, quotedAs) => {
1284
1347
  const whereSql = whereToSql(
1285
1348
  ctx,
1286
1349
  q,
1287
- __spreadProps$9(__spreadValues$f({}, q.q), {
1288
- joinedShapes: __spreadProps$9(__spreadValues$f(__spreadValues$f({}, query.joinedShapes), q.q.joinedShapes), {
1350
+ __spreadProps$7(__spreadValues$f({}, q.q), {
1351
+ joinedShapes: __spreadProps$7(__spreadValues$f(__spreadValues$f({}, query.joinedShapes), q.q.joinedShapes), {
1289
1352
  [table.q.as || table.table]: table.q.shape
1290
1353
  })
1291
1354
  }),
@@ -1442,8 +1505,8 @@ const getIsJoinSubQuery = (query) => {
1442
1505
  };
1443
1506
 
1444
1507
  var __defProp$e = Object.defineProperty;
1445
- var __defProps$8 = Object.defineProperties;
1446
- var __getOwnPropDescs$8 = Object.getOwnPropertyDescriptors;
1508
+ var __defProps$6 = Object.defineProperties;
1509
+ var __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors;
1447
1510
  var __getOwnPropSymbols$f = Object.getOwnPropertySymbols;
1448
1511
  var __hasOwnProp$f = Object.prototype.hasOwnProperty;
1449
1512
  var __propIsEnum$f = Object.prototype.propertyIsEnumerable;
@@ -1459,7 +1522,7 @@ var __spreadValues$e = (a, b) => {
1459
1522
  }
1460
1523
  return a;
1461
1524
  };
1462
- var __spreadProps$8 = (a, b) => __defProps$8(a, __getOwnPropDescs$8(b));
1525
+ var __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b));
1463
1526
  const processJoinArgs = (joinTo, first, args, joinSubQuery) => {
1464
1527
  var _a;
1465
1528
  if (typeof first === "string") {
@@ -1491,7 +1554,7 @@ const processJoinArgs = (joinTo, first, args, joinSubQuery) => {
1491
1554
  logger: joinToQ.logger
1492
1555
  };
1493
1556
  j.baseQuery = j;
1494
- const joinedShapes = __spreadProps$8(__spreadValues$e({}, joinToQ.joinedShapes), {
1557
+ const joinedShapes = __spreadProps$6(__spreadValues$e({}, joinToQ.joinedShapes), {
1495
1558
  [joinToQ.as || joinTo.table]: joinTo.shape
1496
1559
  });
1497
1560
  const r = args[0](
@@ -1518,7 +1581,7 @@ const processJoinArgs = (joinTo, first, args, joinSubQuery) => {
1518
1581
  pushQueryArray(q, "or", query.or);
1519
1582
  }
1520
1583
  }
1521
- const joinedShapes = __spreadProps$8(__spreadValues$e({}, joinTo.q.joinedShapes), {
1584
+ const joinedShapes = __spreadProps$6(__spreadValues$e({}, joinTo.q.joinedShapes), {
1522
1585
  [joinTo.q.as || joinTo.table]: joinTo.shape
1523
1586
  });
1524
1587
  const r = args[0](
@@ -1547,8 +1610,8 @@ const makeJoinQueryBuilder = (joinedQuery, joinedShapes, joinTo) => {
1547
1610
  };
1548
1611
 
1549
1612
  var __defProp$d = Object.defineProperty;
1550
- var __defProps$7 = Object.defineProperties;
1551
- var __getOwnPropDescs$7 = Object.getOwnPropertyDescriptors;
1613
+ var __defProps$5 = Object.defineProperties;
1614
+ var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
1552
1615
  var __getOwnPropSymbols$e = Object.getOwnPropertySymbols;
1553
1616
  var __hasOwnProp$e = Object.prototype.hasOwnProperty;
1554
1617
  var __propIsEnum$e = Object.prototype.propertyIsEnumerable;
@@ -1564,7 +1627,7 @@ var __spreadValues$d = (a, b) => {
1564
1627
  }
1565
1628
  return a;
1566
1629
  };
1567
- var __spreadProps$7 = (a, b) => __defProps$7(a, __getOwnPropDescs$7(b));
1630
+ var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
1568
1631
  const _join = (q, require2, type, first, args) => {
1569
1632
  var _a, _b;
1570
1633
  let joinKey;
@@ -1665,7 +1728,7 @@ const _joinLateral = (self, type, arg, cb, as) => {
1665
1728
  const t = Object.create(q.queryBuilder);
1666
1729
  t.table = arg;
1667
1730
  t.shape = shape;
1668
- t.q = __spreadProps$7(__spreadValues$d({}, t.q), {
1731
+ t.q = __spreadProps$5(__spreadValues$d({}, t.q), {
1669
1732
  shape
1670
1733
  });
1671
1734
  t.baseQuery = t;
@@ -3302,13 +3365,13 @@ const pushInsertSql = (ctx, q, query, quotedAs) => {
3302
3365
  }
3303
3366
  if (query.onConflict) {
3304
3367
  ctx.sql.push("ON CONFLICT");
3305
- const { expr, type } = query.onConflict;
3306
- if (expr) {
3307
- if (typeof expr === "string") {
3308
- ctx.sql.push(`("${((_b = shape[expr]) == null ? void 0 : _b.data.name) || expr}")`);
3309
- } else if (Array.isArray(expr)) {
3368
+ const { target } = query.onConflict;
3369
+ if (target) {
3370
+ if (typeof target === "string") {
3371
+ ctx.sql.push(`("${((_b = shape[target]) == null ? void 0 : _b.data.name) || target}")`);
3372
+ } else if (Array.isArray(target)) {
3310
3373
  ctx.sql.push(
3311
- `(${expr.reduce(
3374
+ `(${target.reduce(
3312
3375
  (sql, item, i) => {
3313
3376
  var _a2;
3314
3377
  return sql + (i ? ", " : "") + `"${((_a2 = shape[item]) == null ? void 0 : _a2.data.name) || item}"`;
@@ -3316,68 +3379,67 @@ const pushInsertSql = (ctx, q, query, quotedAs) => {
3316
3379
  ""
3317
3380
  )})`
3318
3381
  );
3382
+ } else if ("toSQL" in target) {
3383
+ ctx.sql.push(target.toSQL(ctx, quotedAs));
3319
3384
  } else {
3320
- ctx.sql.push(expr.toSQL(ctx, quotedAs));
3385
+ ctx.sql.push(`ON CONSTRAINT "${target.constraint}"`);
3321
3386
  }
3322
- } else if (type === "merge") {
3323
- const { indexes } = q.internal;
3324
- const quotedUniques = columns.reduce((arr, key, i) => {
3325
- var _a2, _b2;
3326
- const unique = (
3327
- // check column index
3328
- ((_b2 = ((_a2 = shape[key]) == null ? void 0 : _a2.data).indexes) == null ? void 0 : _b2.some(
3329
- (index) => index.unique
3330
- )) || // check table composite indexes
3331
- (indexes == null ? void 0 : indexes.some(
3332
- (index) => index.columns.some(
3333
- (item) => "column" in item && item.column === key
3334
- )
3335
- ))
3336
- );
3337
- if (unique)
3338
- arr.push(quotedColumns[i]);
3339
- return arr;
3340
- }, []);
3341
- ctx.sql.push(`(${quotedUniques.join(", ")})`);
3342
3387
  }
3343
- if (type === "ignore") {
3344
- ctx.sql.push("DO NOTHING");
3345
- } else if (type === "merge") {
3346
- let set;
3347
- const { update } = query.onConflict;
3348
- if (update) {
3349
- if (typeof update === "string") {
3350
- const name = ((_c = shape[update]) == null ? void 0 : _c.data.name) || update;
3351
- set = `"${name}" = excluded."${name}"`;
3352
- } else if (Array.isArray(update)) {
3353
- set = update.reduce((sql, item, i) => {
3388
+ if ("merge" in query.onConflict) {
3389
+ let sql;
3390
+ const { merge } = query.onConflict;
3391
+ if (merge) {
3392
+ if (typeof merge === "string") {
3393
+ const name = ((_c = shape[merge]) == null ? void 0 : _c.data.name) || merge;
3394
+ sql = `"${name}" = excluded."${name}"`;
3395
+ } else if ("except" in merge) {
3396
+ const notExcluded = [];
3397
+ const except = orchidCore.toArray(merge.except);
3398
+ for (let i = 0; i < columns.length; i++) {
3399
+ if (!except.includes(columns[i])) {
3400
+ notExcluded.push(quotedColumns[i]);
3401
+ }
3402
+ }
3403
+ sql = mergeColumnsSql(notExcluded);
3404
+ } else {
3405
+ sql = merge.reduce((sql2, item, i) => {
3354
3406
  var _a2;
3355
3407
  const name = ((_a2 = shape[item]) == null ? void 0 : _a2.data.name) || item;
3356
- return sql + (i ? ", " : "") + `"${name}" = excluded."${name}"`;
3408
+ return sql2 + (i ? ", " : "") + `"${name}" = excluded."${name}"`;
3357
3409
  }, "");
3358
- } else if (orchidCore.isExpression(update)) {
3359
- set = update.toSQL(ctx, quotedAs);
3360
- } else {
3361
- const arr = [];
3362
- for (const key in update) {
3363
- arr.push(
3364
- `"${((_d = shape[key]) == null ? void 0 : _d.data.name) || key}" = ${addValue(
3365
- ctx.values,
3366
- update[key]
3367
- )}`
3368
- );
3369
- }
3370
- set = arr.join(", ");
3371
3410
  }
3372
3411
  } else {
3373
- set = quotedColumns.map((column) => `${column} = excluded.${column}`).join(", ");
3412
+ sql = mergeColumnsSql(quotedColumns);
3374
3413
  }
3375
- ctx.sql.push("DO UPDATE SET", set);
3414
+ ctx.sql.push("DO UPDATE SET", sql);
3415
+ } else if (query.onConflict.set) {
3416
+ let sql;
3417
+ const { set } = query.onConflict;
3418
+ if (orchidCore.isExpression(set)) {
3419
+ sql = set.toSQL(ctx, quotedAs);
3420
+ } else {
3421
+ const arr = [];
3422
+ for (const key in set) {
3423
+ arr.push(
3424
+ `"${((_d = shape[key]) == null ? void 0 : _d.data.name) || key}" = ${addValue(
3425
+ ctx.values,
3426
+ set[key]
3427
+ )}`
3428
+ );
3429
+ }
3430
+ sql = arr.join(", ");
3431
+ }
3432
+ ctx.sql.push("DO UPDATE SET", sql);
3433
+ } else {
3434
+ ctx.sql.push("DO NOTHING");
3376
3435
  }
3377
3436
  }
3378
3437
  pushWhereStatementSql(ctx, q, query, quotedAs);
3379
3438
  return pushReturningSql(ctx, q, query, quotedAs, query.afterCreateSelect);
3380
3439
  };
3440
+ const mergeColumnsSql = (quotedColumns2) => {
3441
+ return quotedColumns2.map((column) => `${column} = excluded.${column}`).join(", ");
3442
+ };
3381
3443
  const encodeRow = (ctx, q, QueryClass, row, runtimeDefaults, quotedAs) => {
3382
3444
  const arr = row.map((value) => {
3383
3445
  if (typeof value === "function") {
@@ -4012,10 +4074,27 @@ const extendQuery = (q, methods) => {
4012
4074
  cloned.q = getClonedQueryData(q.q);
4013
4075
  return cloned;
4014
4076
  };
4077
+ const getPrimaryKeys = (q) => {
4078
+ var _a, _b;
4079
+ return (_b = (_a = q.internal).primaryKeys) != null ? _b : _a.primaryKeys = collectPrimaryKeys(q);
4080
+ };
4081
+ const collectPrimaryKeys = (q) => {
4082
+ const primaryKeys = [];
4083
+ const { shape } = q.q;
4084
+ for (const key in shape) {
4085
+ if (shape[key].data.primaryKey) {
4086
+ primaryKeys.push(key);
4087
+ }
4088
+ }
4089
+ if (q.internal.primaryKeys) {
4090
+ primaryKeys.push(...q.internal.primaryKeys);
4091
+ }
4092
+ return primaryKeys;
4093
+ };
4015
4094
 
4016
4095
  var __defProp$a = Object.defineProperty;
4017
- var __defProps$6 = Object.defineProperties;
4018
- var __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors;
4096
+ var __defProps$4 = Object.defineProperties;
4097
+ var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
4019
4098
  var __getOwnPropSymbols$b = Object.getOwnPropertySymbols;
4020
4099
  var __hasOwnProp$b = Object.prototype.hasOwnProperty;
4021
4100
  var __propIsEnum$b = Object.prototype.propertyIsEnumerable;
@@ -4031,7 +4110,7 @@ var __spreadValues$a = (a, b) => {
4031
4110
  }
4032
4111
  return a;
4033
4112
  };
4034
- var __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b));
4113
+ var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
4035
4114
  function setQueryOperators(query, operators) {
4036
4115
  const q = query.q;
4037
4116
  if (q.operators) {
@@ -4090,7 +4169,7 @@ const base = {
4090
4169
  (key, value, ctx, quotedAs) => `NOT ${key} IN ${quoteValue(value, ctx, quotedAs)}`
4091
4170
  )
4092
4171
  };
4093
- const boolean = __spreadProps$6(__spreadValues$a({}, base), {
4172
+ const boolean = __spreadProps$4(__spreadValues$a({}, base), {
4094
4173
  and: make(
4095
4174
  (key, value, ctx, quotedAs) => `${key} AND ${value.q.expr.toSQL(ctx, quotedAs)}`
4096
4175
  ),
@@ -4098,7 +4177,7 @@ const boolean = __spreadProps$6(__spreadValues$a({}, base), {
4098
4177
  (key, value, ctx, quotedAs) => `(${key}) OR (${value.q.expr.toSQL(ctx, quotedAs)})`
4099
4178
  )
4100
4179
  });
4101
- const numeric = __spreadProps$6(__spreadValues$a({}, base), {
4180
+ const numeric = __spreadProps$4(__spreadValues$a({}, base), {
4102
4181
  lt: make(
4103
4182
  (key, value, ctx, quotedAs) => `${key} < ${quoteValue(value, ctx, quotedAs)}`
4104
4183
  ),
@@ -4119,7 +4198,7 @@ const numeric = __spreadProps$6(__spreadValues$a({}, base), {
4119
4198
  )}`
4120
4199
  )
4121
4200
  });
4122
- const text = __spreadProps$6(__spreadValues$a({}, base), {
4201
+ const text = __spreadProps$4(__spreadValues$a({}, base), {
4123
4202
  contains: make(
4124
4203
  (key, value, ctx, quotedAs) => `${key} ILIKE '%' || ${quoteValue(value, ctx, quotedAs)} || '%'`
4125
4204
  ),
@@ -4139,7 +4218,7 @@ const text = __spreadProps$6(__spreadValues$a({}, base), {
4139
4218
  (key, value, ctx, quotedAs) => `${key} LIKE '%' || ${quoteValue(value, ctx, quotedAs)}`
4140
4219
  )
4141
4220
  });
4142
- const json = __spreadProps$6(__spreadValues$a({}, base), {
4221
+ const json = __spreadProps$4(__spreadValues$a({}, base), {
4143
4222
  jsonPath: make(
4144
4223
  (key, [path, op, value], ctx, quotedAs) => `jsonb_path_query_first(${key}, '${path}') #>> '{}' ${op} ${value === null ? "null" : quoteValue(value, ctx, quotedAs, true)}`
4145
4224
  ),
@@ -4333,8 +4412,8 @@ class BigSerialColumn extends NumberAsStringBaseColumn {
4333
4412
  }
4334
4413
 
4335
4414
  var __defProp$9 = Object.defineProperty;
4336
- var __defProps$5 = Object.defineProperties;
4337
- var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
4415
+ var __defProps$3 = Object.defineProperties;
4416
+ var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
4338
4417
  var __getOwnPropSymbols$a = Object.getOwnPropertySymbols;
4339
4418
  var __hasOwnProp$a = Object.prototype.hasOwnProperty;
4340
4419
  var __propIsEnum$a = Object.prototype.propertyIsEnumerable;
@@ -4350,7 +4429,7 @@ var __spreadValues$9 = (a, b) => {
4350
4429
  }
4351
4430
  return a;
4352
4431
  };
4353
- var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
4432
+ var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
4354
4433
  class TextBaseColumn extends ColumnType {
4355
4434
  constructor(schema, schemaType = schema.stringSchema()) {
4356
4435
  super(schema, schemaType);
@@ -4709,8 +4788,11 @@ class UUIDColumn extends ColumnType {
4709
4788
  this.dataType = "uuid";
4710
4789
  this.operators = Operators.text;
4711
4790
  }
4712
- primaryKey() {
4713
- const column = super.primaryKey();
4791
+ /**
4792
+ * see {@link ColumnType.primaryKey}
4793
+ */
4794
+ primaryKey(name) {
4795
+ const column = super.primaryKey(name);
4714
4796
  if (!column.data.default)
4715
4797
  column.data.default = uuidDefault;
4716
4798
  return column;
@@ -4723,7 +4805,7 @@ class UUIDColumn extends ColumnType {
4723
4805
  `uuid()`,
4724
4806
  m,
4725
4807
  // don't output the default default
4726
- data.default instanceof orchidCore.RawSQLBase && data.default._sql === uuidDefaultSQL ? __spreadProps$5(__spreadValues$9({}, data), { default: void 0 }) : data
4808
+ data.default instanceof orchidCore.RawSQLBase && data.default._sql === uuidDefaultSQL ? __spreadProps$3(__spreadValues$9({}, data), { default: void 0 }) : data
4727
4809
  );
4728
4810
  }
4729
4811
  }
@@ -4795,8 +4877,6 @@ class DomainColumn extends CustomTypeColumn {
4795
4877
  }
4796
4878
 
4797
4879
  var __defProp$8 = Object.defineProperty;
4798
- var __defProps$4 = Object.defineProperties;
4799
- var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
4800
4880
  var __getOwnPropSymbols$9 = Object.getOwnPropertySymbols;
4801
4881
  var __hasOwnProp$9 = Object.prototype.hasOwnProperty;
4802
4882
  var __propIsEnum$9 = Object.prototype.propertyIsEnumerable;
@@ -4812,19 +4892,11 @@ var __spreadValues$8 = (a, b) => {
4812
4892
  }
4813
4893
  return a;
4814
4894
  };
4815
- var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
4816
- const newTableData = () => ({});
4817
- let tableData = newTableData();
4818
- const getTableData = () => tableData;
4819
- const resetTableData = (data = newTableData()) => {
4820
- tableData = data;
4821
- };
4822
- const getColumnTypes = (types, fn, nowSQL, language, data = newTableData()) => {
4895
+ const getColumnTypes = (types, fn, nowSQL, language) => {
4823
4896
  if (nowSQL)
4824
4897
  orchidCore.setDefaultNowFn(nowSQL);
4825
4898
  if (language)
4826
4899
  orchidCore.setDefaultLanguage(language);
4827
- resetTableData(data);
4828
4900
  return fn(types);
4829
4901
  };
4830
4902
  const makeColumnTypes = (schema) => {
@@ -4836,20 +4908,7 @@ const makeColumnTypes = (schema) => {
4836
4908
  orchidCore.setCurrentColumnName(name);
4837
4909
  return this;
4838
4910
  },
4839
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
4840
- sql(...args) {
4841
- const arg = args[0];
4842
- if (Array.isArray(arg)) {
4843
- return new RawSQL(args);
4844
- }
4845
- if (typeof args[0] === "string") {
4846
- return new RawSQL(args[0]);
4847
- }
4848
- if (args[1] !== void 0) {
4849
- return new RawSQL(args[1], arg);
4850
- }
4851
- return (...args2) => new RawSQL(args2, arg);
4852
- },
4911
+ sql: sqlFn,
4853
4912
  smallint: schema.smallint,
4854
4913
  integer: schema.integer,
4855
4914
  bigint: schema.bigint,
@@ -4946,66 +5005,6 @@ const makeColumnTypes = (schema) => {
4946
5005
  },
4947
5006
  domain(dataType) {
4948
5007
  return new DomainColumn(schema, dataType);
4949
- },
4950
- primaryKey(columns, options) {
4951
- tableData.primaryKey = { columns, options };
4952
- return orchidCore.emptyObject;
4953
- },
4954
- index(columns, options = {}) {
4955
- var _a;
4956
- const index = {
4957
- columns: orchidCore.toArray(columns).map(
4958
- (column) => typeof column === "string" ? { column } : column
4959
- ),
4960
- options
4961
- };
4962
- ((_a = tableData.indexes) != null ? _a : tableData.indexes = []).push(index);
4963
- return orchidCore.emptyObject;
4964
- },
4965
- unique(columns, options) {
4966
- return this.index(columns, __spreadProps$4(__spreadValues$8({}, options), { unique: true }));
4967
- },
4968
- /**
4969
- * See {@link ColumnType.searchIndex}
4970
- */
4971
- searchIndex(columns, options) {
4972
- return this.index(columns, __spreadProps$4(__spreadValues$8({ using: "gin" }, options), { tsVector: true }));
4973
- },
4974
- constraint({ name, references, check, dropMode }) {
4975
- var _a;
4976
- ((_a = tableData.constraints) != null ? _a : tableData.constraints = []).push({
4977
- name,
4978
- references: references ? {
4979
- columns: references[0],
4980
- fnOrTable: references[1],
4981
- foreignColumns: references[2],
4982
- options: references[3]
4983
- } : void 0,
4984
- check,
4985
- dropMode
4986
- });
4987
- return orchidCore.emptyObject;
4988
- },
4989
- foreignKey(columns, fnOrTable, foreignColumns, options) {
4990
- var _a;
4991
- ((_a = tableData.constraints) != null ? _a : tableData.constraints = []).push({
4992
- name: options == null ? void 0 : options.name,
4993
- references: {
4994
- columns,
4995
- fnOrTable,
4996
- foreignColumns,
4997
- options
4998
- },
4999
- dropMode: options == null ? void 0 : options.dropMode
5000
- });
5001
- return orchidCore.emptyObject;
5002
- },
5003
- check(check, options) {
5004
- var _a;
5005
- ((_a = tableData.constraints) != null ? _a : tableData.constraints = []).push(__spreadProps$4(__spreadValues$8({}, options), {
5006
- check
5007
- }));
5008
- return orchidCore.emptyObject;
5009
5008
  }
5010
5009
  }, orchidCore.makeTimestampsHelpers(makeRegexToFindInSql));
5011
5010
  };
@@ -5252,8 +5251,8 @@ class TransactionAdapter {
5252
5251
  }
5253
5252
 
5254
5253
  var __defProp$7 = Object.defineProperty;
5255
- var __defProps$3 = Object.defineProperties;
5256
- var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
5254
+ var __defProps$2 = Object.defineProperties;
5255
+ var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
5257
5256
  var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
5258
5257
  var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
5259
5258
  var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
@@ -5269,7 +5268,7 @@ var __spreadValues$7 = (a, b) => {
5269
5268
  }
5270
5269
  return a;
5271
5270
  };
5272
- var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
5271
+ var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
5273
5272
  class FnExpression extends orchidCore.Expression {
5274
5273
  /**
5275
5274
  * @param q - query object.
@@ -5326,7 +5325,7 @@ class FnExpression extends orchidCore.Expression {
5326
5325
  sql.push(" ");
5327
5326
  if (options.order) {
5328
5327
  pushOrderBySql(
5329
- __spreadProps$3(__spreadValues$7({}, ctx), { sql }),
5328
+ __spreadProps$2(__spreadValues$7({}, ctx), { sql }),
5330
5329
  this.q.q,
5331
5330
  quotedAs,
5332
5331
  orchidCore.toArray(options.order)
@@ -6257,9 +6256,9 @@ class Create {
6257
6256
  * password: '1234',
6258
6257
  * });
6259
6258
  *
6260
- * // When using `.onConflict().ignore()`,
6259
+ * // When using `.onConflictDoNothing()`,
6261
6260
  * // the record may be not created and the `createdCount` will be 0.
6262
- * const createdCount = await db.table.insert(data).onConflict().ignore();
6261
+ * const createdCount = await db.table.insert(data).onConflictDoNothing();
6263
6262
  *
6264
6263
  * await db.table.create({
6265
6264
  * // raw SQL
@@ -6452,7 +6451,7 @@ class Create {
6452
6451
  *
6453
6452
  * Columns provided in `defaults` are marked as optional in the following `create`.
6454
6453
  *
6455
- * Default data is the same as in [create](#create) and [createMany](#createMany),
6454
+ * Default data is the same as in {@link create} and {@link createMany},
6456
6455
  * so you can provide a raw SQL, or a query with a query.
6457
6456
  *
6458
6457
  * ```ts
@@ -6473,32 +6472,45 @@ class Create {
6473
6472
  return _queryDefaults(this.clone(), data);
6474
6473
  }
6475
6474
  /**
6476
- * A modifier for creating queries that specify alternative behavior in the case of a conflict.
6477
- * A conflict occurs when a table has a `PRIMARY KEY` or a `UNIQUE` index on a column
6478
- * (or a composite index on a set of columns) and a row being created has the same value as a row
6479
- * that already exists in the table in this column(s).
6480
- * The default behavior in case of conflict is to raise an error and abort the query.
6475
+ * By default, violating unique constraint will cause the creative query to throw,
6476
+ * you can define what to do on a conflict: to ignore it, or to merge the existing record with a new data.
6477
+ *
6478
+ * A conflict occurs when a table has a primary key or a unique index on a column,
6479
+ * or a composite primary key unique index on a set of columns,
6480
+ * and a row being created has the same value as a row that already exists in the table in this column(s).
6481
+ *
6482
+ * Use {@link onConflictDoNothing} to suppress the error and continue without updating the record,
6483
+ * or the `merge` to update the record with new values automatically,
6484
+ * or the `set` to specify own values for the update.
6481
6485
  *
6482
- * Use `onConflict` to either ignore the error by using `.onConflict().ignore()`,
6483
- * or to update the existing row with new data (perform an "UPSERT") by using `.onConflict().merge()`.
6486
+ * `onConflict` only accepts column names that are defined in `primaryKey` or `unique` in the table definition.
6487
+ * To specify a constraint, its name also must be explicitly set in `primaryKey` or `unique` in the table code.
6488
+ *
6489
+ * 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
6490
+ * for updating the record.
6491
+ *
6492
+ * If your table has multiple potential reasons for unique constraint violation, such as username and email columns in a user table,
6493
+ * consider using `upsert` instead.
6484
6494
  *
6485
6495
  * ```ts
6486
6496
  * // leave `onConflict` without argument to ignore or merge on any conflict
6487
- * db.table.create(data).onConflict().ignore();
6497
+ * db.table.create(data).onConflictDoNothing();
6488
6498
  *
6489
6499
  * // single column:
6490
- * db.table.create(data).onConfict('email');
6500
+ * db.table.create(data).onConfict('email').merge();
6491
6501
  *
6492
6502
  * // array of columns:
6493
- * db.table.create(data).onConfict(['email', 'name']);
6503
+ * db.table.create(data).onConfict(['email', 'name']).merge();
6494
6504
  *
6495
- * // raw expression:
6496
- * db.table.create(data).onConfict(db.table.sql`(email) where condition`);
6497
- * ```
6505
+ * // constraint name
6506
+ * db.table.create(data).onConfict({ constraint: 'unique_index_name' }).merge();
6498
6507
  *
6499
- * ::: info
6500
- * 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.
6501
- * When specifying multiple columns, they must be a composite PRIMARY KEY or have a composite UNIQUE index.
6508
+ * // raw SQL expression:
6509
+ * db.table
6510
+ * .create(data)
6511
+ * .onConfict(db.table.sql`(email) where condition`)
6512
+ * .merge();
6513
+ * ```
6502
6514
  *
6503
6515
  * You can use the db.table.sql function in onConflict.
6504
6516
  * It can be useful to specify a condition when you have a partial index:
@@ -6515,29 +6527,32 @@ class Create {
6515
6527
  * .ignore();
6516
6528
  * ```
6517
6529
  *
6518
- * :::
6530
+ * For `merge` and `set`, you can append `where` to update data only for the matching rows:
6519
6531
  *
6520
- * See the documentation on the .ignore() and .merge() methods for more details.
6532
+ * ```ts
6533
+ * const timestamp = Date.now();
6534
+ *
6535
+ * db.table
6536
+ * .create(data)
6537
+ * .onConflict('email')
6538
+ * .set({
6539
+ * name: 'John Doe',
6540
+ * updatedAt: timestamp,
6541
+ * })
6542
+ * .where({ updatedAt: { lt: timestamp } });
6543
+ * ```
6521
6544
  *
6522
6545
  * @param arg - optionally provide an array of columns
6523
6546
  */
6524
6547
  onConflict(arg) {
6525
6548
  return new OnConflictQueryBuilder(this, arg);
6526
6549
  }
6527
- }
6528
- class OnConflictQueryBuilder {
6529
- constructor(query, onConflict) {
6530
- this.query = query;
6531
- this.onConflict = onConflict;
6532
- }
6533
6550
  /**
6534
- * Available only after `onConflict`.
6535
- *
6536
- * `ignore` modifies a create query, and causes it to be silently dropped without an error if a conflict occurs.
6551
+ * Use `onConflictDoNothing` to suppress unique constraint violation error when creating a record.
6537
6552
  *
6538
- * Adds the `ON CONFLICT (columns) DO NOTHING` clause to the insert statement.
6553
+ * Adds `ON CONFLICT (columns) DO NOTHING` clause to the insert statement, columns are optional.
6539
6554
  *
6540
- * It produces `ON CONFLICT DO NOTHING` when no `onConflict` argument provided.
6555
+ * Can also accept a constraint name.
6541
6556
  *
6542
6557
  * ```ts
6543
6558
  * db.table
@@ -6545,40 +6560,38 @@ class OnConflictQueryBuilder {
6545
6560
  * email: 'ignore@example.com',
6546
6561
  * name: 'John Doe',
6547
6562
  * })
6548
- * .onConflict('email')
6549
- * .ignore();
6563
+ * // on any conflict:
6564
+ * .onConflictDoNothing()
6565
+ * // or, for a specific column:
6566
+ * .onConflictDoNothing('email')
6567
+ * // or, for a specific constraint:
6568
+ * .onConflictDoNothing({ constraint: 'unique_index_name' });
6550
6569
  * ```
6551
6570
  *
6552
- *
6553
- * 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.
6554
- *
6555
- * `create` returns a full record by default, it becomes `RecordType | undefined` after applying `ignore`.
6571
+ * When there is a conflict, nothing can be returned from the database, so `onConflictDoNothing` adds `| undefined` part to the response type.
6556
6572
  *
6557
6573
  * ```ts
6558
6574
  * const maybeRecord: RecordType | undefined = await db.table
6559
6575
  * .create(data)
6560
- * .onConflict()
6561
- * .ignore();
6576
+ * .onConflictDoNothing();
6562
6577
  *
6563
6578
  * const maybeId: number | undefined = await db.table
6564
6579
  * .get('id')
6565
6580
  * .create(data)
6566
- * .onConflict()
6567
- * .ignore();
6581
+ * .onConflictDoNothing();
6568
6582
  * ```
6569
6583
  *
6570
- * When creating many records, only the created records will be returned. If no records were created, array will be empty:
6584
+ * When creating multiple records, only created records will be returned. If no records were created, array will be empty:
6571
6585
  *
6572
6586
  * ```ts
6573
6587
  * // array can be empty
6574
- * const arr = await db.table.createMany([data, data, data]).onConflict().ignore();
6588
+ * const arr = await db.table.createMany([data, data, data]).onConflictDoNothing();
6575
6589
  * ```
6576
6590
  */
6577
- ignore() {
6578
- const q = this.query;
6591
+ onConflictDoNothing(arg) {
6592
+ const q = this.clone();
6579
6593
  q.q.onConflict = {
6580
- type: "ignore",
6581
- expr: this.onConflict
6594
+ target: arg
6582
6595
  };
6583
6596
  if (q.q.returnType === "oneOrThrow") {
6584
6597
  q.q.returnType = "one";
@@ -6587,115 +6600,90 @@ class OnConflictQueryBuilder {
6587
6600
  }
6588
6601
  return q;
6589
6602
  }
6603
+ }
6604
+ class OnConflictQueryBuilder {
6605
+ constructor(query, onConflict) {
6606
+ this.query = query;
6607
+ this.onConflict = onConflict;
6608
+ }
6590
6609
  /**
6591
6610
  * Available only after `onConflict`.
6592
6611
  *
6593
- * Modifies a create query, to turn it into an 'upsert' operation.
6594
- *
6595
- * Adds an `ON CONFLICT (columns) DO UPDATE` clause to the insert statement.
6596
- *
6597
- * When no `onConflict` argument provided,
6598
- * it will automatically collect all table columns that have unique index and use them as a conflict target.
6612
+ * Updates the record with a given data when conflict occurs.
6599
6613
  *
6600
6614
  * ```ts
6601
- * db.table
6602
- * .create({
6603
- * email: 'ignore@example.com',
6604
- * name: 'John Doe',
6605
- * })
6606
- * .onConflict('email')
6607
- * .merge();
6615
+ * db.table.create(data).onConflict('column').set({
6616
+ * description: 'setting different data on conflict',
6617
+ * });
6608
6618
  * ```
6609
6619
  *
6610
- * This also works with batch creates:
6620
+ * The `set` can take a raw SQL expression:
6611
6621
  *
6612
6622
  * ```ts
6613
6623
  * db.table
6614
- * .createMany([
6615
- * { email: 'john@example.com', name: 'John Doe' },
6616
- * { email: 'jane@example.com', name: 'Jane Doe' },
6617
- * { email: 'alex@example.com', name: 'Alex Doe' },
6618
- * ])
6619
- * .onConflict('email')
6620
- * .merge();
6621
- * ```
6622
- *
6623
- * It is also possible to specify a subset of the columns to merge when a conflict occurs.
6624
- * For example, you may want to set a `createdAt` column when creating but would prefer not to update it if the row already exists:
6625
- *
6626
- * ```ts
6627
- * const timestamp = Date.now();
6624
+ * .create(data)
6625
+ * .onConflict()
6626
+ * .set(db.table.sql`raw SQL expression`);
6628
6627
  *
6628
+ * // update records only on certain conditions
6629
6629
  * db.table
6630
- * .create({
6631
- * email: 'ignore@example.com',
6632
- * name: 'John Doe',
6633
- * createdAt: timestamp,
6634
- * updatedAt: timestamp,
6635
- * })
6630
+ * .create(data)
6636
6631
  * .onConflict('email')
6637
- * // string argument for a single column:
6638
- * .merge('email')
6639
- * // array of strings for multiple columns:
6640
- * .merge(['email', 'name', 'updatedAt']);
6632
+ * .set({ key: 'value' })
6633
+ * .where({ ...certainConditions });
6641
6634
  * ```
6642
6635
  *
6643
- * It is also possible to specify data to update separately from the data to create.
6644
- * This is useful if you want to make an update with different data than in creating.
6645
- * For example, you may want to change a value if the row already exists:
6636
+ * @param set - object containing new column values, or raw SQL
6637
+ */
6638
+ set(set) {
6639
+ this.query.q.onConflict = {
6640
+ target: this.onConflict,
6641
+ set
6642
+ };
6643
+ return this.query;
6644
+ }
6645
+ /**
6646
+ * Available only after `onConflict`.
6646
6647
  *
6647
- * ```ts
6648
- * const timestamp = Date.now();
6648
+ * Use this method to merge all the data you have passed into `create` to update the existing record on conflict.
6649
6649
  *
6650
- * db.table
6651
- * .create({
6652
- * email: 'ignore@example.com',
6653
- * name: 'John Doe',
6654
- * createdAt: timestamp,
6655
- * updatedAt: timestamp,
6656
- * })
6657
- * .onConflict('email')
6658
- * .merge({
6659
- * name: 'John Doe The Second',
6660
- * });
6661
- * ```
6650
+ * If the table has columns with **dynamic** default values, such values will be applied as well.
6662
6651
  *
6663
- * It is also possible to add a WHERE clause to conditionally update only the matching rows:
6652
+ * You can exclude certain columns from being merged by passing the `exclude` option.
6664
6653
  *
6665
6654
  * ```ts
6666
- * const timestamp = Date.now();
6655
+ * // merge the full data
6656
+ * db.table.create(data).onConflict('email').merge();
6657
+ *
6658
+ * // merge only a single column
6659
+ * db.table.create(data).onConflict('email').merge('name');
6660
+ *
6661
+ * // merge multiple columns
6662
+ * db.table.create(data).onConflict('email').merge(['name', 'quantity']);
6667
6663
  *
6664
+ * // merge all columns except some
6668
6665
  * db.table
6669
- * .create({
6670
- * email: 'ignore@example.com',
6671
- * name: 'John Doe',
6672
- * createdAt: timestamp,
6673
- * updatedAt: timestamp,
6674
- * })
6666
+ * .create(data)
6675
6667
  * .onConflict('email')
6676
- * .merge({
6677
- * name: 'John Doe',
6678
- * updatedAt: timestamp,
6679
- * })
6680
- * .where({ updatedAt: { lt: timestamp } });
6681
- * ```
6668
+ * .merge({ except: ['name', 'quantity'] });
6682
6669
  *
6683
- * `merge` also accepts raw expression:
6670
+ * // merge can be applied also for batch creates
6671
+ * db.table.createMany([data1, data2, data2]).onConflict('email').merge();
6684
6672
  *
6685
- * ```ts
6673
+ * // update records only on certain conditions
6686
6674
  * db.table
6687
6675
  * .create(data)
6688
- * .onConflict()
6689
- * .merge(db.table.sql`raw SQL expression`);
6676
+ * .onConflict('email')
6677
+ * .merge()
6678
+ * .where({ ...certainConditions });
6690
6679
  * ```
6691
6680
  *
6692
- * @param update - column, or array of columns, or object for new column values, or raw SQL
6681
+ * @param merge - no argument will merge all data, or provide a column(s) to merge, or provide `except` to update all except some.
6693
6682
  */
6694
- merge(update) {
6683
+ merge(merge) {
6695
6684
  this.query.q.onConflict = {
6696
- type: "merge",
6697
- expr: this.onConflict,
6698
- update
6685
+ target: this.onConflict,
6686
+ merge
6699
6687
  };
6700
6688
  return this.query;
6701
6689
  }
@@ -7916,10 +7904,7 @@ class JsonModifiers {
7916
7904
  options
7917
7905
  ]
7918
7906
  };
7919
- return Object.assign(
7920
- pushQueryValue(q, "select", json),
7921
- json
7922
- );
7907
+ return Object.assign(pushQueryValue(q, "select", json), json);
7923
7908
  }
7924
7909
  /**
7925
7910
  * 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.
@@ -7967,10 +7952,7 @@ class JsonModifiers {
7967
7952
  options
7968
7953
  ]
7969
7954
  };
7970
- return Object.assign(
7971
- pushQueryValue(q, "select", json),
7972
- json
7973
- );
7955
+ return Object.assign(pushQueryValue(q, "select", json), json);
7974
7956
  }
7975
7957
  /**
7976
7958
  * Return a JSON value/object/array where a given value is removed at the given JSON path.
@@ -8009,10 +7991,7 @@ class JsonModifiers {
8009
7991
  path
8010
7992
  ]
8011
7993
  };
8012
- return Object.assign(
8013
- pushQueryValue(q, "select", json),
8014
- json
8015
- );
7994
+ return Object.assign(pushQueryValue(q, "select", json), json);
8016
7995
  }
8017
7996
  /**
8018
7997
  * Selects a value from JSON data using a JSON path.
@@ -8058,10 +8037,7 @@ class JsonModifiers {
8058
8037
  const json = {
8059
8038
  __json: ["pathQuery", as, type, column, path, options]
8060
8039
  };
8061
- return Object.assign(
8062
- pushQueryValue(q, "select", json),
8063
- json
8064
- );
8040
+ return Object.assign(pushQueryValue(q, "select", json), json);
8065
8041
  }
8066
8042
  }
8067
8043
  class JsonMethods {
@@ -8078,10 +8054,7 @@ class JsonMethods {
8078
8054
  * @param coalesce
8079
8055
  */
8080
8056
  json(coalesce) {
8081
- return queryJson(
8082
- this.clone(),
8083
- coalesce
8084
- );
8057
+ return queryJson(this.clone(), coalesce);
8085
8058
  }
8086
8059
  }
8087
8060
 
@@ -8208,8 +8181,8 @@ class MergeQueryMethods {
8208
8181
  }
8209
8182
 
8210
8183
  var __defProp$4 = Object.defineProperty;
8211
- var __defProps$2 = Object.defineProperties;
8212
- var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
8184
+ var __defProps$1 = Object.defineProperties;
8185
+ var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
8213
8186
  var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
8214
8187
  var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
8215
8188
  var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
@@ -8225,7 +8198,7 @@ var __spreadValues$4 = (a, b) => {
8225
8198
  }
8226
8199
  return a;
8227
8200
  };
8228
- var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
8201
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
8229
8202
  class With {
8230
8203
  /**
8231
8204
  * Add Common Table Expression (CTE) to the query.
@@ -8300,7 +8273,7 @@ class With {
8300
8273
  const query = typeof last === "function" ? last(q.queryBuilder) : last;
8301
8274
  const shape = args.length === 4 ? args[2] : orchidCore.isExpression(query) ? args[1] : query.q.shape;
8302
8275
  if ((options == null ? void 0 : options.columns) === true) {
8303
- options = __spreadProps$2(__spreadValues$4({}, options), {
8276
+ options = __spreadProps$1(__spreadValues$4({}, options), {
8304
8277
  columns: Object.keys(shape)
8305
8278
  });
8306
8279
  }
@@ -9242,9 +9215,9 @@ const _queryUpdate = (query, arg) => {
9242
9215
  if (queries) {
9243
9216
  q.patchResult = async (_, queryResult) => {
9244
9217
  await Promise.all(queries.map(orchidCore.callWithThis, queryResult));
9245
- if (ctx.updateData) {
9218
+ if (ctx.collect) {
9246
9219
  const t = query.baseQuery.clone();
9247
- const keys = query.primaryKeys;
9220
+ const { keys } = ctx.collect;
9248
9221
  _queryWhereIn(
9249
9222
  t,
9250
9223
  keys,
@@ -9252,10 +9225,10 @@ const _queryUpdate = (query, arg) => {
9252
9225
  );
9253
9226
  _queryUpdate(
9254
9227
  t,
9255
- ctx.updateData
9228
+ ctx.collect.data
9256
9229
  );
9257
9230
  for (const row of queryResult.rows) {
9258
- Object.assign(row, ctx.updateData);
9231
+ Object.assign(row, ctx.collect.data);
9259
9232
  }
9260
9233
  }
9261
9234
  };
@@ -9688,8 +9661,8 @@ class Transaction {
9688
9661
  }
9689
9662
 
9690
9663
  var __defProp$2 = Object.defineProperty;
9691
- var __defProps$1 = Object.defineProperties;
9692
- var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
9664
+ var __defProps = Object.defineProperties;
9665
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
9693
9666
  var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
9694
9667
  var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
9695
9668
  var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
@@ -9705,7 +9678,7 @@ var __spreadValues$2 = (a, b) => {
9705
9678
  }
9706
9679
  return a;
9707
9680
  };
9708
- var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
9681
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
9709
9682
  class Headline extends orchidCore.Expression {
9710
9683
  constructor(q, source, params) {
9711
9684
  super();
@@ -9927,7 +9900,7 @@ class SearchMethods {
9927
9900
  const q = this.clone();
9928
9901
  if (!arg.as) {
9929
9902
  const as = saveSearchAlias(q, "@q", "joinedShapes");
9930
- arg = __spreadProps$1(__spreadValues$2({}, arg), {
9903
+ arg = __spreadProps(__spreadValues$2({}, arg), {
9931
9904
  as
9932
9905
  });
9933
9906
  }
@@ -10516,20 +10489,11 @@ class QueryMethods {
10516
10489
  );
10517
10490
  }
10518
10491
  /**
10519
- * The `find` method is available only for tables which has exactly one primary key.
10520
- * And also it can accept raw SQL template literal, then the primary key is not required.
10521
- *
10522
- * Finds a record by id, throws {@link NotFoundError} if not found:
10492
+ * Finds a single record by the primary key (id), throws [NotFoundError](/guide/error-handling.html) if not found.
10493
+ * Not available if the table has no or multiple primary keys.
10523
10494
  *
10524
10495
  * ```ts
10525
- * await db.table.find(1);
10526
- * ```
10527
- *
10528
- * ```ts
10529
- * await db.user.find`
10530
- * age = ${age} AND
10531
- * name = ${name}
10532
- * `;
10496
+ * const result: TableType = await db.table.find(1);
10533
10497
  * ```
10534
10498
  *
10535
10499
  * @param value - primary key value to find by
@@ -10545,7 +10509,7 @@ class QueryMethods {
10545
10509
  return _queryTake(
10546
10510
  _queryWhere(q, [
10547
10511
  {
10548
- [q.singlePrimaryKey]: value
10512
+ [q.internal.singlePrimaryKey]: value
10549
10513
  }
10550
10514
  ])
10551
10515
  );
@@ -10567,8 +10531,8 @@ class QueryMethods {
10567
10531
  return _queryTake(_queryWhereSql(q, args));
10568
10532
  }
10569
10533
  /**
10570
- * Find a single record by the primary key (id), adds `LIMIT 1`.
10571
- * Returns `undefined` when not found.
10534
+ * Finds a single record by the primary key (id), returns `undefined` when not found.
10535
+ * Not available if the table has no or multiple primary keys.
10572
10536
  *
10573
10537
  * ```ts
10574
10538
  * const result: TableType | undefined = await db.table.find(123);
@@ -10598,40 +10562,40 @@ class QueryMethods {
10598
10562
  );
10599
10563
  }
10600
10564
  /**
10601
- * The same as `where(conditions).take()`, takes the same arguments as {@link Where.where}, it will filter records and add a `LIMIT 1`.
10602
- * Throws `NotFoundError` if not found.
10565
+ * Finds a single unique record, throws [NotFoundError](/guide/error-handling.html) if not found.
10566
+ * It accepts values of primary keys or unique indexes defined on the table.
10567
+ * `findBy`'s argument type is a union of all possible sets of unique conditions.
10568
+ *
10569
+ * You can use `where(...).take()` for non-unique conditions.
10603
10570
  *
10604
10571
  * ```ts
10605
- * const result: TableType = await db.table.findBy({ key: 'value' });
10606
- * // is equivalent to:
10607
- * db.table.where({ key: 'value' }).take()
10572
+ * await db.table.findBy({ key: 'value' });
10608
10573
  * ```
10609
10574
  *
10610
- * @param args - `where` conditions
10575
+ * @param uniqueColumnValues - is derived from primary keys and unique indexes in the table
10611
10576
  */
10612
- findBy(...args) {
10613
- return _queryFindBy(
10614
- this.clone(),
10615
- args
10616
- );
10577
+ findBy(uniqueColumnValues) {
10578
+ return _queryFindBy(this.clone(), [
10579
+ uniqueColumnValues
10580
+ ]);
10617
10581
  }
10618
10582
  /**
10619
- * The same as `where(conditions).takeOptional()`, it will filter records and add a `LIMIT 1`.
10620
- * Returns `undefined` when not found.
10583
+ * Finds a single unique record, returns `undefined` if not found.
10584
+ * It accepts values of primary keys or unique indexes defined on the table.
10585
+ * `findBy`'s argument type is a union of all possible sets of unique conditions.
10586
+ *
10587
+ * You can use `where(...).takeOptional()` for non-unique conditions.
10621
10588
  *
10622
10589
  * ```ts
10623
- * const result: TableType | undefined = await db.table.findByOptional({
10624
- * key: 'value',
10625
- * });
10590
+ * await db.table.findByOptional({ key: 'value' });
10626
10591
  * ```
10627
10592
  *
10628
- * @param args - `where` conditions
10593
+ * @param uniqueColumnValues - is derived from primary keys and unique indexes in the table
10629
10594
  */
10630
- findByOptional(...args) {
10631
- return _queryFindByOptional(
10632
- this.clone(),
10633
- args
10634
- );
10595
+ findByOptional(uniqueColumnValues) {
10596
+ return _queryFindByOptional(this.clone(), [
10597
+ uniqueColumnValues
10598
+ ]);
10635
10599
  }
10636
10600
  /**
10637
10601
  * Specifies the schema to be used as a prefix of a table name.
@@ -10777,9 +10741,9 @@ class QueryMethods {
10777
10741
  * Order by raw SQL expression.
10778
10742
  *
10779
10743
  * ```ts
10780
- * db.table.order`raw sql`;
10744
+ * db.table.orderSql`raw sql`;
10781
10745
  * // or
10782
- * db.table.order(db.table.sql`raw sql`);
10746
+ * db.table.orderSql(db.table.sql`raw sql`);
10783
10747
  * ```
10784
10748
  *
10785
10749
  * @param args - SQL expression
@@ -11021,9 +10985,86 @@ orchidCore.applyMixins(QueryMethods, [
11021
10985
  SoftDeleteMethods
11022
10986
  ]);
11023
10987
 
10988
+ const makeIndex = (columns, first, second) => {
10989
+ if (typeof first === "string") {
10990
+ const options = second != null ? second : {};
10991
+ return {
10992
+ index: { columns, options, name: first }
10993
+ };
10994
+ } else {
10995
+ const options = first != null ? first : {};
10996
+ return {
10997
+ index: { columns, options }
10998
+ };
10999
+ }
11000
+ };
11001
+ const tableDataMethods = {
11002
+ primaryKey(columns, name) {
11003
+ return { primaryKey: { columns, name } };
11004
+ },
11005
+ unique(columns, ...[first, second]) {
11006
+ const input = makeIndex(columns, first, second);
11007
+ input.index.options.unique = true;
11008
+ return input;
11009
+ },
11010
+ index: makeIndex,
11011
+ searchIndex(columns, ...[first, second]) {
11012
+ var _a, _b;
11013
+ const input = makeIndex(columns, first, second);
11014
+ (_b = (_a = input.index.options).using) != null ? _b : _a.using = "gin";
11015
+ input.index.options.tsVector = true;
11016
+ return input;
11017
+ },
11018
+ foreignKey(columns, fnOrTable, foreignColumns, options) {
11019
+ return {
11020
+ constraint: {
11021
+ name: options == null ? void 0 : options.name,
11022
+ references: { columns, fnOrTable, foreignColumns, options }
11023
+ }
11024
+ };
11025
+ },
11026
+ check(check, name) {
11027
+ return { constraint: { check, name } };
11028
+ },
11029
+ sql: sqlFn
11030
+ };
11031
+ const parseTableData = (dataFn) => {
11032
+ const tableData = {};
11033
+ if (dataFn) {
11034
+ const input = dataFn(tableDataMethods);
11035
+ if (Array.isArray(input)) {
11036
+ for (const item of input) {
11037
+ parseTableDataInput(tableData, item);
11038
+ }
11039
+ } else {
11040
+ parseTableDataInput(tableData, input);
11041
+ }
11042
+ }
11043
+ return tableData;
11044
+ };
11045
+ const parseTableDataInput = (tableData, item) => {
11046
+ var _a, _b, _c, _d;
11047
+ if (item.primaryKey) {
11048
+ tableData.primaryKey = item.primaryKey;
11049
+ } else if (item.index) {
11050
+ const index = item.index;
11051
+ for (let i = index.columns.length - 1; i >= 0; i--) {
11052
+ if (typeof index.columns[i] === "string") {
11053
+ index.columns[i] = {
11054
+ column: index.columns[i]
11055
+ };
11056
+ }
11057
+ }
11058
+ ((_a = tableData.indexes) != null ? _a : tableData.indexes = []).push(item.index);
11059
+ } else if (item.constraint) {
11060
+ ((_b = tableData.constraints) != null ? _b : tableData.constraints = []).push(item.constraint);
11061
+ if ((_d = (_c = item.constraint.references) == null ? void 0 : _c.options) == null ? void 0 : _d.dropMode) {
11062
+ item.constraint.dropMode = item.constraint.references.options.dropMode;
11063
+ }
11064
+ }
11065
+ };
11066
+
11024
11067
  var __defProp = Object.defineProperty;
11025
- var __defProps = Object.defineProperties;
11026
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
11027
11068
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
11028
11069
  var __hasOwnProp = Object.prototype.hasOwnProperty;
11029
11070
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
@@ -11039,7 +11080,6 @@ var __spreadValues = (a, b) => {
11039
11080
  }
11040
11081
  return a;
11041
11082
  };
11042
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
11043
11083
  var __objRest = (source, exclude) => {
11044
11084
  var target = {};
11045
11085
  for (var prop in source)
@@ -11054,24 +11094,24 @@ var __objRest = (source, exclude) => {
11054
11094
  };
11055
11095
  const anyShape = {};
11056
11096
  class Db {
11057
- constructor(adapter, queryBuilder, table = void 0, shape = anyShape, columnTypes, transactionStorage, options, tableData = getTableData()) {
11097
+ constructor(adapter, queryBuilder, table = void 0, shape = anyShape, columnTypes, transactionStorage, options, tableData = orchidCore.emptyObject) {
11058
11098
  this.adapter = adapter;
11059
11099
  this.queryBuilder = queryBuilder;
11060
11100
  this.table = table;
11061
11101
  this.shape = shape;
11062
11102
  this.columnTypes = columnTypes;
11063
- this.tableData = tableData;
11064
- var _a, _b;
11103
+ var _a;
11065
11104
  const self = this;
11066
11105
  const { softDelete } = options;
11067
11106
  const scopes = options.scopes || softDelete ? {} : orchidCore.emptyObject;
11068
- this.internal = __spreadProps(__spreadValues({}, tableData), {
11107
+ this.internal = {
11069
11108
  transactionStorage,
11070
11109
  scopes,
11071
11110
  snakeCase: options.snakeCase,
11072
11111
  noPrimaryKey: options.noPrimaryKey === "ignore",
11073
- comment: options.comment
11074
- });
11112
+ comment: options.comment,
11113
+ tableData
11114
+ };
11075
11115
  this.baseQuery = this;
11076
11116
  const logger = options.logger || console;
11077
11117
  const parsers = {};
@@ -11132,20 +11172,21 @@ class Db {
11132
11172
  log: logParamToLogObject(logger, options.log),
11133
11173
  autoPreparedStatements: (_a = options.autoPreparedStatements) != null ? _a : false,
11134
11174
  parsers: hasParsers ? parsers : void 0,
11135
- language: options.language
11175
+ language: options.language,
11176
+ schema: options == null ? void 0 : options.schema
11136
11177
  };
11137
- if (options == null ? void 0 : options.schema) {
11138
- this.q.schema = options.schema;
11178
+ let shapeHasPrimaryKey;
11179
+ for (const key in shape) {
11180
+ if (shape[key].data.primaryKey) {
11181
+ shapeHasPrimaryKey = true;
11182
+ if (this.internal.singlePrimaryKey) {
11183
+ this.internal.singlePrimaryKey = void 0;
11184
+ break;
11185
+ }
11186
+ this.internal.singlePrimaryKey = key;
11187
+ }
11139
11188
  }
11140
- this.primaryKeys = Object.keys(shape).filter(
11141
- (key) => shape[key].data.primaryKey
11142
- );
11143
- const primaryKeysFromData = (_b = getTableData().primaryKey) == null ? void 0 : _b.columns;
11144
- if (primaryKeysFromData)
11145
- this.primaryKeys.push(...primaryKeysFromData);
11146
- if (this.primaryKeys.length === 1) {
11147
- this.singlePrimaryKey = this.primaryKeys[0];
11148
- } else if (this.primaryKeys.length === 0 && shape !== anyShape && options.noPrimaryKey !== "ignore") {
11189
+ if (!shapeHasPrimaryKey && !tableData.primaryKey && shape !== anyShape && options.noPrimaryKey !== "ignore") {
11149
11190
  const message = `Table ${table} has no primary key`;
11150
11191
  if (options.noPrimaryKey === "error")
11151
11192
  throw new Error(message);
@@ -11341,14 +11382,15 @@ const createDb = (_a) => {
11341
11382
  commonOptions,
11342
11383
  options
11343
11384
  );
11344
- const tableConstructor = (table, shape, options2) => new Db(
11385
+ const tableConstructor = (table, shape, dataFn, options2) => new Db(
11345
11386
  adapter,
11346
11387
  qb,
11347
11388
  table,
11348
11389
  typeof shape === "function" ? getColumnTypes(ct, shape, nowSQL, options2 == null ? void 0 : options2.language) : shape,
11349
11390
  ct,
11350
11391
  transactionStorage,
11351
- __spreadValues(__spreadValues({}, commonOptions), options2)
11392
+ __spreadValues(__spreadValues({}, commonOptions), options2),
11393
+ parseTableData(dataFn)
11352
11394
  );
11353
11395
  const db = Object.assign(tableConstructor, qb, {
11354
11396
  adapter,
@@ -11367,8 +11409,7 @@ const _initQueryBuilder = (adapter, columnTypes, transactionStorage, commonOptio
11367
11409
  anyShape,
11368
11410
  columnTypes,
11369
11411
  transactionStorage,
11370
- commonOptions,
11371
- orchidCore.emptyObject
11412
+ commonOptions
11372
11413
  );
11373
11414
  if (options.extensions) {
11374
11415
  const arr = [];
@@ -11687,7 +11728,6 @@ exports.columnForeignKeysToCode = columnForeignKeysToCode;
11687
11728
  exports.columnIndexesToCode = columnIndexesToCode;
11688
11729
  exports.columnsShapeToCode = columnsShapeToCode;
11689
11730
  exports.constraintInnerToCode = constraintInnerToCode;
11690
- exports.constraintPropsToCode = constraintPropsToCode;
11691
11731
  exports.constraintToCode = constraintToCode;
11692
11732
  exports.copyTableData = copyTableData;
11693
11733
  exports.countSelect = countSelect;
@@ -11698,10 +11738,9 @@ exports.foreignKeyArgumentToCode = foreignKeyArgumentToCode;
11698
11738
  exports.getClonedQueryData = getClonedQueryData;
11699
11739
  exports.getColumnInfo = getColumnInfo;
11700
11740
  exports.getColumnTypes = getColumnTypes;
11701
- exports.getConstraintKind = getConstraintKind;
11741
+ exports.getPrimaryKeys = getPrimaryKeys;
11702
11742
  exports.getQueryAs = getQueryAs;
11703
11743
  exports.getShapeFromSelect = getShapeFromSelect;
11704
- exports.getTableData = getTableData;
11705
11744
  exports.handleResult = handleResult;
11706
11745
  exports.identityToCode = identityToCode;
11707
11746
  exports.indexInnerToCode = indexInnerToCode;
@@ -11719,17 +11758,18 @@ exports.makeExpression = makeExpression;
11719
11758
  exports.makeFnExpression = makeFnExpression;
11720
11759
  exports.makeRegexToFindInSql = makeRegexToFindInSql;
11721
11760
  exports.makeSQL = makeSQL;
11722
- exports.newTableData = newTableData;
11723
11761
  exports.parseRecord = parseRecord;
11724
11762
  exports.parseResult = parseResult;
11763
+ exports.parseTableData = parseTableData;
11764
+ exports.parseTableDataInput = parseTableDataInput;
11725
11765
  exports.primaryKeyInnerToCode = primaryKeyInnerToCode;
11726
- exports.primaryKeyToCode = primaryKeyToCode;
11727
11766
  exports.processSelectArg = processSelectArg;
11728
11767
  exports.pushLimitSQL = pushLimitSQL;
11729
11768
  exports.pushQueryArray = pushQueryArray;
11730
11769
  exports.pushQueryOn = pushQueryOn;
11731
11770
  exports.pushQueryOrOn = pushQueryOrOn;
11732
11771
  exports.pushQueryValue = pushQueryValue;
11772
+ exports.pushTableDataCode = pushTableDataCode;
11733
11773
  exports.queryFrom = queryFrom;
11734
11774
  exports.queryFromSql = queryFromSql;
11735
11775
  exports.queryJson = queryJson;
@@ -11740,14 +11780,15 @@ exports.quote = quote;
11740
11780
  exports.quoteString = quoteString;
11741
11781
  exports.raw = raw;
11742
11782
  exports.referencesArgsToCode = referencesArgsToCode;
11743
- exports.resetTableData = resetTableData;
11744
11783
  exports.resolveSubQueryCallback = resolveSubQueryCallback;
11745
11784
  exports.saveSearchAlias = saveSearchAlias;
11746
11785
  exports.setParserForSelectedString = setParserForSelectedString;
11747
11786
  exports.setQueryObjectValue = setQueryObjectValue;
11748
11787
  exports.setQueryOperators = setQueryOperators;
11749
11788
  exports.simplifyColumnDefault = simplifyColumnDefault;
11789
+ exports.sqlFn = sqlFn;
11750
11790
  exports.sqlQueryArgsToExpression = sqlQueryArgsToExpression;
11791
+ exports.tableDataMethods = tableDataMethods;
11751
11792
  exports.templateLiteralToSQL = templateLiteralToSQL;
11752
11793
  exports.testTransaction = testTransaction;
11753
11794
  exports.throwIfNoWhere = throwIfNoWhere;