pqb 0.27.7 → 0.28.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;
@@ -3316,29 +3379,11 @@ const pushInsertSql = (ctx, q, query, quotedAs) => {
3316
3379
  ""
3317
3380
  )})`
3318
3381
  );
3319
- } else {
3382
+ } else if ("toSQL" in expr) {
3320
3383
  ctx.sql.push(expr.toSQL(ctx, quotedAs));
3384
+ } else {
3385
+ ctx.sql.push(`ON CONSTRAINT "${expr.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
3388
  if (type === "ignore") {
3344
3389
  ctx.sql.push("DO NOTHING");
@@ -4012,10 +4057,27 @@ const extendQuery = (q, methods) => {
4012
4057
  cloned.q = getClonedQueryData(q.q);
4013
4058
  return cloned;
4014
4059
  };
4060
+ const getPrimaryKeys = (q) => {
4061
+ var _a, _b;
4062
+ return (_b = (_a = q.internal).primaryKeys) != null ? _b : _a.primaryKeys = collectPrimaryKeys(q);
4063
+ };
4064
+ const collectPrimaryKeys = (q) => {
4065
+ const primaryKeys = [];
4066
+ const { shape } = q.q;
4067
+ for (const key in shape) {
4068
+ if (shape[key].data.primaryKey) {
4069
+ primaryKeys.push(key);
4070
+ }
4071
+ }
4072
+ if (q.internal.primaryKeys) {
4073
+ primaryKeys.push(...q.internal.primaryKeys);
4074
+ }
4075
+ return primaryKeys;
4076
+ };
4015
4077
 
4016
4078
  var __defProp$a = Object.defineProperty;
4017
- var __defProps$6 = Object.defineProperties;
4018
- var __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors;
4079
+ var __defProps$4 = Object.defineProperties;
4080
+ var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
4019
4081
  var __getOwnPropSymbols$b = Object.getOwnPropertySymbols;
4020
4082
  var __hasOwnProp$b = Object.prototype.hasOwnProperty;
4021
4083
  var __propIsEnum$b = Object.prototype.propertyIsEnumerable;
@@ -4031,7 +4093,7 @@ var __spreadValues$a = (a, b) => {
4031
4093
  }
4032
4094
  return a;
4033
4095
  };
4034
- var __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b));
4096
+ var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
4035
4097
  function setQueryOperators(query, operators) {
4036
4098
  const q = query.q;
4037
4099
  if (q.operators) {
@@ -4090,7 +4152,7 @@ const base = {
4090
4152
  (key, value, ctx, quotedAs) => `NOT ${key} IN ${quoteValue(value, ctx, quotedAs)}`
4091
4153
  )
4092
4154
  };
4093
- const boolean = __spreadProps$6(__spreadValues$a({}, base), {
4155
+ const boolean = __spreadProps$4(__spreadValues$a({}, base), {
4094
4156
  and: make(
4095
4157
  (key, value, ctx, quotedAs) => `${key} AND ${value.q.expr.toSQL(ctx, quotedAs)}`
4096
4158
  ),
@@ -4098,7 +4160,7 @@ const boolean = __spreadProps$6(__spreadValues$a({}, base), {
4098
4160
  (key, value, ctx, quotedAs) => `(${key}) OR (${value.q.expr.toSQL(ctx, quotedAs)})`
4099
4161
  )
4100
4162
  });
4101
- const numeric = __spreadProps$6(__spreadValues$a({}, base), {
4163
+ const numeric = __spreadProps$4(__spreadValues$a({}, base), {
4102
4164
  lt: make(
4103
4165
  (key, value, ctx, quotedAs) => `${key} < ${quoteValue(value, ctx, quotedAs)}`
4104
4166
  ),
@@ -4119,7 +4181,7 @@ const numeric = __spreadProps$6(__spreadValues$a({}, base), {
4119
4181
  )}`
4120
4182
  )
4121
4183
  });
4122
- const text = __spreadProps$6(__spreadValues$a({}, base), {
4184
+ const text = __spreadProps$4(__spreadValues$a({}, base), {
4123
4185
  contains: make(
4124
4186
  (key, value, ctx, quotedAs) => `${key} ILIKE '%' || ${quoteValue(value, ctx, quotedAs)} || '%'`
4125
4187
  ),
@@ -4139,7 +4201,7 @@ const text = __spreadProps$6(__spreadValues$a({}, base), {
4139
4201
  (key, value, ctx, quotedAs) => `${key} LIKE '%' || ${quoteValue(value, ctx, quotedAs)}`
4140
4202
  )
4141
4203
  });
4142
- const json = __spreadProps$6(__spreadValues$a({}, base), {
4204
+ const json = __spreadProps$4(__spreadValues$a({}, base), {
4143
4205
  jsonPath: make(
4144
4206
  (key, [path, op, value], ctx, quotedAs) => `jsonb_path_query_first(${key}, '${path}') #>> '{}' ${op} ${value === null ? "null" : quoteValue(value, ctx, quotedAs, true)}`
4145
4207
  ),
@@ -4333,8 +4395,8 @@ class BigSerialColumn extends NumberAsStringBaseColumn {
4333
4395
  }
4334
4396
 
4335
4397
  var __defProp$9 = Object.defineProperty;
4336
- var __defProps$5 = Object.defineProperties;
4337
- var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
4398
+ var __defProps$3 = Object.defineProperties;
4399
+ var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
4338
4400
  var __getOwnPropSymbols$a = Object.getOwnPropertySymbols;
4339
4401
  var __hasOwnProp$a = Object.prototype.hasOwnProperty;
4340
4402
  var __propIsEnum$a = Object.prototype.propertyIsEnumerable;
@@ -4350,7 +4412,7 @@ var __spreadValues$9 = (a, b) => {
4350
4412
  }
4351
4413
  return a;
4352
4414
  };
4353
- var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
4415
+ var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
4354
4416
  class TextBaseColumn extends ColumnType {
4355
4417
  constructor(schema, schemaType = schema.stringSchema()) {
4356
4418
  super(schema, schemaType);
@@ -4709,8 +4771,11 @@ class UUIDColumn extends ColumnType {
4709
4771
  this.dataType = "uuid";
4710
4772
  this.operators = Operators.text;
4711
4773
  }
4712
- primaryKey() {
4713
- const column = super.primaryKey();
4774
+ /**
4775
+ * see {@link ColumnType.primaryKey}
4776
+ */
4777
+ primaryKey(name) {
4778
+ const column = super.primaryKey(name);
4714
4779
  if (!column.data.default)
4715
4780
  column.data.default = uuidDefault;
4716
4781
  return column;
@@ -4723,7 +4788,7 @@ class UUIDColumn extends ColumnType {
4723
4788
  `uuid()`,
4724
4789
  m,
4725
4790
  // 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
4791
+ data.default instanceof orchidCore.RawSQLBase && data.default._sql === uuidDefaultSQL ? __spreadProps$3(__spreadValues$9({}, data), { default: void 0 }) : data
4727
4792
  );
4728
4793
  }
4729
4794
  }
@@ -4795,8 +4860,6 @@ class DomainColumn extends CustomTypeColumn {
4795
4860
  }
4796
4861
 
4797
4862
  var __defProp$8 = Object.defineProperty;
4798
- var __defProps$4 = Object.defineProperties;
4799
- var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
4800
4863
  var __getOwnPropSymbols$9 = Object.getOwnPropertySymbols;
4801
4864
  var __hasOwnProp$9 = Object.prototype.hasOwnProperty;
4802
4865
  var __propIsEnum$9 = Object.prototype.propertyIsEnumerable;
@@ -4812,19 +4875,11 @@ var __spreadValues$8 = (a, b) => {
4812
4875
  }
4813
4876
  return a;
4814
4877
  };
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()) => {
4878
+ const getColumnTypes = (types, fn, nowSQL, language) => {
4823
4879
  if (nowSQL)
4824
4880
  orchidCore.setDefaultNowFn(nowSQL);
4825
4881
  if (language)
4826
4882
  orchidCore.setDefaultLanguage(language);
4827
- resetTableData(data);
4828
4883
  return fn(types);
4829
4884
  };
4830
4885
  const makeColumnTypes = (schema) => {
@@ -4836,20 +4891,7 @@ const makeColumnTypes = (schema) => {
4836
4891
  orchidCore.setCurrentColumnName(name);
4837
4892
  return this;
4838
4893
  },
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
- },
4894
+ sql: sqlFn,
4853
4895
  smallint: schema.smallint,
4854
4896
  integer: schema.integer,
4855
4897
  bigint: schema.bigint,
@@ -4946,66 +4988,6 @@ const makeColumnTypes = (schema) => {
4946
4988
  },
4947
4989
  domain(dataType) {
4948
4990
  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
4991
  }
5010
4992
  }, orchidCore.makeTimestampsHelpers(makeRegexToFindInSql));
5011
4993
  };
@@ -5252,8 +5234,8 @@ class TransactionAdapter {
5252
5234
  }
5253
5235
 
5254
5236
  var __defProp$7 = Object.defineProperty;
5255
- var __defProps$3 = Object.defineProperties;
5256
- var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
5237
+ var __defProps$2 = Object.defineProperties;
5238
+ var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
5257
5239
  var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
5258
5240
  var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
5259
5241
  var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
@@ -5269,7 +5251,7 @@ var __spreadValues$7 = (a, b) => {
5269
5251
  }
5270
5252
  return a;
5271
5253
  };
5272
- var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
5254
+ var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
5273
5255
  class FnExpression extends orchidCore.Expression {
5274
5256
  /**
5275
5257
  * @param q - query object.
@@ -5326,7 +5308,7 @@ class FnExpression extends orchidCore.Expression {
5326
5308
  sql.push(" ");
5327
5309
  if (options.order) {
5328
5310
  pushOrderBySql(
5329
- __spreadProps$3(__spreadValues$7({}, ctx), { sql }),
5311
+ __spreadProps$2(__spreadValues$7({}, ctx), { sql }),
5330
5312
  this.q.q,
5331
5313
  quotedAs,
5332
5314
  orchidCore.toArray(options.order)
@@ -6257,9 +6239,9 @@ class Create {
6257
6239
  * password: '1234',
6258
6240
  * });
6259
6241
  *
6260
- * // When using `.onConflict().ignore()`,
6242
+ * // When using `.onConflictIgnore()`,
6261
6243
  * // the record may be not created and the `createdCount` will be 0.
6262
- * const createdCount = await db.table.insert(data).onConflict().ignore();
6244
+ * const createdCount = await db.table.insert(data).onConflictIgnore();
6263
6245
  *
6264
6246
  * await db.table.create({
6265
6247
  * // raw SQL
@@ -6473,32 +6455,44 @@ class Create {
6473
6455
  return _queryDefaults(this.clone(), data);
6474
6456
  }
6475
6457
  /**
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.
6458
+ * By default, violating unique constraint will cause the creative query to throw,
6459
+ * you can define what to do on a conflict: to ignore it, or to merge the existing record with a new data.
6460
+ *
6461
+ * A conflict occurs when a table has a primary key or a unique index on a column,
6462
+ * or a composite primary key unique index on a set of columns,
6463
+ * and a row being created has the same value as a row that already exists in the table in this column(s).
6464
+ *
6465
+ * Use `onConflictIgnore()` to suppress the error and continue without updating the record,
6466
+ * or `onConflict(['uniqueColumn']).merge()` to update the record with a new data.
6467
+ *
6468
+ * `onConflict` only accepts column names that are defined in `primaryKey` or `unique` in the table definition.
6469
+ * To specify a constraint, its name also must be explicitly set in `primaryKey` or `unique` in the table code.
6481
6470
  *
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()`.
6471
+ * 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
6472
+ * for updating the record.
6473
+ *
6474
+ * If your table has multiple potential reasons for unique constraint violation, such as username and email columns in a user table,
6475
+ * consider using [upsert](#upsert) instead.
6484
6476
  *
6485
6477
  * ```ts
6486
6478
  * // leave `onConflict` without argument to ignore or merge on any conflict
6487
- * db.table.create(data).onConflict().ignore();
6479
+ * db.table.create(data).onConflictIgnore();
6488
6480
  *
6489
6481
  * // single column:
6490
- * db.table.create(data).onConfict('email');
6482
+ * db.table.create(data).onConfict('email').merge();
6491
6483
  *
6492
6484
  * // array of columns:
6493
- * db.table.create(data).onConfict(['email', 'name']);
6485
+ * db.table.create(data).onConfict(['email', 'name']).merge();
6494
6486
  *
6495
- * // raw expression:
6496
- * db.table.create(data).onConfict(db.table.sql`(email) where condition`);
6497
- * ```
6487
+ * // constraint name
6488
+ * db.table.create(data).onConfict({ constraint: 'unique_index_name' }).merge();
6498
6489
  *
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.
6490
+ * // raw SQL expression:
6491
+ * db.table
6492
+ * .create(data)
6493
+ * .onConfict(db.table.sql`(email) where condition`)
6494
+ * .merge();
6495
+ * ```
6502
6496
  *
6503
6497
  * You can use the db.table.sql function in onConflict.
6504
6498
  * It can be useful to specify a condition when you have a partial index:
@@ -6515,29 +6509,17 @@ class Create {
6515
6509
  * .ignore();
6516
6510
  * ```
6517
6511
  *
6518
- * :::
6519
- *
6520
- * See the documentation on the .ignore() and .merge() methods for more details.
6521
- *
6522
6512
  * @param arg - optionally provide an array of columns
6523
6513
  */
6524
6514
  onConflict(arg) {
6525
6515
  return new OnConflictQueryBuilder(this, arg);
6526
6516
  }
6527
- }
6528
- class OnConflictQueryBuilder {
6529
- constructor(query, onConflict) {
6530
- this.query = query;
6531
- this.onConflict = onConflict;
6532
- }
6533
6517
  /**
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.
6518
+ * Use `onConflictIgnore` to suppress unique constraint violation error when creating a record.
6537
6519
  *
6538
- * Adds the `ON CONFLICT (columns) DO NOTHING` clause to the insert statement.
6520
+ * Adds `ON CONFLICT (columns) DO NOTHING` clause to the insert statement, columns are optional.
6539
6521
  *
6540
- * It produces `ON CONFLICT DO NOTHING` when no `onConflict` argument provided.
6522
+ * Can also accept a constraint name.
6541
6523
  *
6542
6524
  * ```ts
6543
6525
  * db.table
@@ -6545,40 +6527,39 @@ class OnConflictQueryBuilder {
6545
6527
  * email: 'ignore@example.com',
6546
6528
  * name: 'John Doe',
6547
6529
  * })
6548
- * .onConflict('email')
6549
- * .ignore();
6530
+ * // on any conflict:
6531
+ * .onConflictIgnore()
6532
+ * // or, for a specific column:
6533
+ * .onConflictIgnore('email')
6534
+ * // or, for a specific constraint:
6535
+ * .onConflictIgnore({ constraint: 'unique_index_name' });
6550
6536
  * ```
6551
6537
  *
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`.
6538
+ * When there is a conflict, nothing can be returned from the database, so `onConflictIgnore` adds `| undefined` part to the response type.
6556
6539
  *
6557
6540
  * ```ts
6558
6541
  * const maybeRecord: RecordType | undefined = await db.table
6559
6542
  * .create(data)
6560
- * .onConflict()
6561
- * .ignore();
6543
+ * .onConflictIgnore();
6562
6544
  *
6563
6545
  * const maybeId: number | undefined = await db.table
6564
6546
  * .get('id')
6565
6547
  * .create(data)
6566
- * .onConflict()
6567
- * .ignore();
6548
+ * .onConflictIgnore();
6568
6549
  * ```
6569
6550
  *
6570
- * When creating many records, only the created records will be returned. If no records were created, array will be empty:
6551
+ * When creating multiple records, only created records will be returned. If no records were created, array will be empty:
6571
6552
  *
6572
6553
  * ```ts
6573
6554
  * // array can be empty
6574
- * const arr = await db.table.createMany([data, data, data]).onConflict().ignore();
6555
+ * const arr = await db.table.createMany([data, data, data]).onConflictIgnore();
6575
6556
  * ```
6576
6557
  */
6577
- ignore() {
6578
- const q = this.query;
6558
+ onConflictIgnore(arg) {
6559
+ const q = this.clone();
6579
6560
  q.q.onConflict = {
6580
6561
  type: "ignore",
6581
- expr: this.onConflict
6562
+ expr: arg
6582
6563
  };
6583
6564
  if (q.q.returnType === "oneOrThrow") {
6584
6565
  q.q.returnType = "one";
@@ -6587,23 +6568,27 @@ class OnConflictQueryBuilder {
6587
6568
  }
6588
6569
  return q;
6589
6570
  }
6571
+ }
6572
+ class OnConflictQueryBuilder {
6573
+ constructor(query, onConflict) {
6574
+ this.query = query;
6575
+ this.onConflict = onConflict;
6576
+ }
6590
6577
  /**
6591
- * Available only after `onConflict`.
6592
- *
6593
- * Modifies a create query, to turn it into an 'upsert' operation.
6578
+ * Available only after [onConflict](#onconflict).
6594
6579
  *
6595
6580
  * Adds an `ON CONFLICT (columns) DO UPDATE` clause to the insert statement.
6596
6581
  *
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.
6599
- *
6600
6582
  * ```ts
6601
6583
  * db.table
6602
6584
  * .create({
6603
6585
  * email: 'ignore@example.com',
6604
6586
  * name: 'John Doe',
6605
6587
  * })
6588
+ * // for a specific column:
6606
6589
  * .onConflict('email')
6590
+ * // or, for a specific constraint:
6591
+ * .onConflict({ constraint: 'unique_constraint_name' })
6607
6592
  * .merge();
6608
6593
  * ```
6609
6594
  *
@@ -6634,15 +6619,15 @@ class OnConflictQueryBuilder {
6634
6619
  * updatedAt: timestamp,
6635
6620
  * })
6636
6621
  * .onConflict('email')
6637
- * // string argument for a single column:
6622
+ * // update only a single column
6638
6623
  * .merge('email')
6639
- * // array of strings for multiple columns:
6624
+ * // or, update multiple columns
6640
6625
  * .merge(['email', 'name', 'updatedAt']);
6641
6626
  * ```
6642
6627
  *
6643
- * It is also possible to specify data to update separately from the data to create.
6628
+ * It's possible to specify data to update separately from the data to create.
6644
6629
  * 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:
6630
+ * For example, changing a value if the row already exists:
6646
6631
  *
6647
6632
  * ```ts
6648
6633
  * const timestamp = Date.now();
@@ -6660,7 +6645,7 @@ class OnConflictQueryBuilder {
6660
6645
  * });
6661
6646
  * ```
6662
6647
  *
6663
- * It is also possible to add a WHERE clause to conditionally update only the matching rows:
6648
+ * You can use `where` to update only the matching rows:
6664
6649
  *
6665
6650
  * ```ts
6666
6651
  * const timestamp = Date.now();
@@ -6680,7 +6665,7 @@ class OnConflictQueryBuilder {
6680
6665
  * .where({ updatedAt: { lt: timestamp } });
6681
6666
  * ```
6682
6667
  *
6683
- * `merge` also accepts raw expression:
6668
+ * `merge` can take a raw SQL expression:
6684
6669
  *
6685
6670
  * ```ts
6686
6671
  * db.table
@@ -7916,10 +7901,7 @@ class JsonModifiers {
7916
7901
  options
7917
7902
  ]
7918
7903
  };
7919
- return Object.assign(
7920
- pushQueryValue(q, "select", json),
7921
- json
7922
- );
7904
+ return Object.assign(pushQueryValue(q, "select", json), json);
7923
7905
  }
7924
7906
  /**
7925
7907
  * 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 +7949,7 @@ class JsonModifiers {
7967
7949
  options
7968
7950
  ]
7969
7951
  };
7970
- return Object.assign(
7971
- pushQueryValue(q, "select", json),
7972
- json
7973
- );
7952
+ return Object.assign(pushQueryValue(q, "select", json), json);
7974
7953
  }
7975
7954
  /**
7976
7955
  * Return a JSON value/object/array where a given value is removed at the given JSON path.
@@ -8009,10 +7988,7 @@ class JsonModifiers {
8009
7988
  path
8010
7989
  ]
8011
7990
  };
8012
- return Object.assign(
8013
- pushQueryValue(q, "select", json),
8014
- json
8015
- );
7991
+ return Object.assign(pushQueryValue(q, "select", json), json);
8016
7992
  }
8017
7993
  /**
8018
7994
  * Selects a value from JSON data using a JSON path.
@@ -8058,10 +8034,7 @@ class JsonModifiers {
8058
8034
  const json = {
8059
8035
  __json: ["pathQuery", as, type, column, path, options]
8060
8036
  };
8061
- return Object.assign(
8062
- pushQueryValue(q, "select", json),
8063
- json
8064
- );
8037
+ return Object.assign(pushQueryValue(q, "select", json), json);
8065
8038
  }
8066
8039
  }
8067
8040
  class JsonMethods {
@@ -8078,10 +8051,7 @@ class JsonMethods {
8078
8051
  * @param coalesce
8079
8052
  */
8080
8053
  json(coalesce) {
8081
- return queryJson(
8082
- this.clone(),
8083
- coalesce
8084
- );
8054
+ return queryJson(this.clone(), coalesce);
8085
8055
  }
8086
8056
  }
8087
8057
 
@@ -8208,8 +8178,8 @@ class MergeQueryMethods {
8208
8178
  }
8209
8179
 
8210
8180
  var __defProp$4 = Object.defineProperty;
8211
- var __defProps$2 = Object.defineProperties;
8212
- var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
8181
+ var __defProps$1 = Object.defineProperties;
8182
+ var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
8213
8183
  var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
8214
8184
  var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
8215
8185
  var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
@@ -8225,7 +8195,7 @@ var __spreadValues$4 = (a, b) => {
8225
8195
  }
8226
8196
  return a;
8227
8197
  };
8228
- var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
8198
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
8229
8199
  class With {
8230
8200
  /**
8231
8201
  * Add Common Table Expression (CTE) to the query.
@@ -8300,7 +8270,7 @@ class With {
8300
8270
  const query = typeof last === "function" ? last(q.queryBuilder) : last;
8301
8271
  const shape = args.length === 4 ? args[2] : orchidCore.isExpression(query) ? args[1] : query.q.shape;
8302
8272
  if ((options == null ? void 0 : options.columns) === true) {
8303
- options = __spreadProps$2(__spreadValues$4({}, options), {
8273
+ options = __spreadProps$1(__spreadValues$4({}, options), {
8304
8274
  columns: Object.keys(shape)
8305
8275
  });
8306
8276
  }
@@ -9242,9 +9212,9 @@ const _queryUpdate = (query, arg) => {
9242
9212
  if (queries) {
9243
9213
  q.patchResult = async (_, queryResult) => {
9244
9214
  await Promise.all(queries.map(orchidCore.callWithThis, queryResult));
9245
- if (ctx.updateData) {
9215
+ if (ctx.collect) {
9246
9216
  const t = query.baseQuery.clone();
9247
- const keys = query.primaryKeys;
9217
+ const { keys } = ctx.collect;
9248
9218
  _queryWhereIn(
9249
9219
  t,
9250
9220
  keys,
@@ -9252,10 +9222,10 @@ const _queryUpdate = (query, arg) => {
9252
9222
  );
9253
9223
  _queryUpdate(
9254
9224
  t,
9255
- ctx.updateData
9225
+ ctx.collect.data
9256
9226
  );
9257
9227
  for (const row of queryResult.rows) {
9258
- Object.assign(row, ctx.updateData);
9228
+ Object.assign(row, ctx.collect.data);
9259
9229
  }
9260
9230
  }
9261
9231
  };
@@ -9688,8 +9658,8 @@ class Transaction {
9688
9658
  }
9689
9659
 
9690
9660
  var __defProp$2 = Object.defineProperty;
9691
- var __defProps$1 = Object.defineProperties;
9692
- var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
9661
+ var __defProps = Object.defineProperties;
9662
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
9693
9663
  var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
9694
9664
  var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
9695
9665
  var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
@@ -9705,7 +9675,7 @@ var __spreadValues$2 = (a, b) => {
9705
9675
  }
9706
9676
  return a;
9707
9677
  };
9708
- var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
9678
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
9709
9679
  class Headline extends orchidCore.Expression {
9710
9680
  constructor(q, source, params) {
9711
9681
  super();
@@ -9927,7 +9897,7 @@ class SearchMethods {
9927
9897
  const q = this.clone();
9928
9898
  if (!arg.as) {
9929
9899
  const as = saveSearchAlias(q, "@q", "joinedShapes");
9930
- arg = __spreadProps$1(__spreadValues$2({}, arg), {
9900
+ arg = __spreadProps(__spreadValues$2({}, arg), {
9931
9901
  as
9932
9902
  });
9933
9903
  }
@@ -10516,20 +10486,11 @@ class QueryMethods {
10516
10486
  );
10517
10487
  }
10518
10488
  /**
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:
10489
+ * Finds a single record by the primary key (id), throws [NotFoundError](/guide/error-handling.html) if not found.
10490
+ * Not available if the table has no or multiple primary keys.
10523
10491
  *
10524
10492
  * ```ts
10525
- * await db.table.find(1);
10526
- * ```
10527
- *
10528
- * ```ts
10529
- * await db.user.find`
10530
- * age = ${age} AND
10531
- * name = ${name}
10532
- * `;
10493
+ * const result: TableType = await db.table.find(1);
10533
10494
  * ```
10534
10495
  *
10535
10496
  * @param value - primary key value to find by
@@ -10545,7 +10506,7 @@ class QueryMethods {
10545
10506
  return _queryTake(
10546
10507
  _queryWhere(q, [
10547
10508
  {
10548
- [q.singlePrimaryKey]: value
10509
+ [q.internal.singlePrimaryKey]: value
10549
10510
  }
10550
10511
  ])
10551
10512
  );
@@ -10567,8 +10528,8 @@ class QueryMethods {
10567
10528
  return _queryTake(_queryWhereSql(q, args));
10568
10529
  }
10569
10530
  /**
10570
- * Find a single record by the primary key (id), adds `LIMIT 1`.
10571
- * Returns `undefined` when not found.
10531
+ * Finds a single record by the primary key (id), returns `undefined` when not found.
10532
+ * Not available if the table has no or multiple primary keys.
10572
10533
  *
10573
10534
  * ```ts
10574
10535
  * const result: TableType | undefined = await db.table.find(123);
@@ -10598,40 +10559,40 @@ class QueryMethods {
10598
10559
  );
10599
10560
  }
10600
10561
  /**
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.
10562
+ * Finds a single unique record, throws [NotFoundError](/guide/error-handling.html) if not found.
10563
+ * It accepts values of primary keys or unique indexes defined on the table.
10564
+ * `findBy`'s argument type is a union of all possible sets of unique conditions.
10565
+ *
10566
+ * You can use `where(...).take()` for non-unique conditions.
10603
10567
  *
10604
10568
  * ```ts
10605
- * const result: TableType = await db.table.findBy({ key: 'value' });
10606
- * // is equivalent to:
10607
- * db.table.where({ key: 'value' }).take()
10569
+ * await db.table.findBy({ key: 'value' });
10608
10570
  * ```
10609
10571
  *
10610
- * @param args - `where` conditions
10572
+ * @param uniqueColumnValues - is derived from primary keys and unique indexes in the table
10611
10573
  */
10612
- findBy(...args) {
10613
- return _queryFindBy(
10614
- this.clone(),
10615
- args
10616
- );
10574
+ findBy(uniqueColumnValues) {
10575
+ return _queryFindBy(this.clone(), [
10576
+ uniqueColumnValues
10577
+ ]);
10617
10578
  }
10618
10579
  /**
10619
- * The same as `where(conditions).takeOptional()`, it will filter records and add a `LIMIT 1`.
10620
- * Returns `undefined` when not found.
10580
+ * Finds a single unique record, returns `undefined` if not found.
10581
+ * It accepts values of primary keys or unique indexes defined on the table.
10582
+ * `findBy`'s argument type is a union of all possible sets of unique conditions.
10583
+ *
10584
+ * You can use `where(...).takeOptional()` for non-unique conditions.
10621
10585
  *
10622
10586
  * ```ts
10623
- * const result: TableType | undefined = await db.table.findByOptional({
10624
- * key: 'value',
10625
- * });
10587
+ * await db.table.findByOptional({ key: 'value' });
10626
10588
  * ```
10627
10589
  *
10628
- * @param args - `where` conditions
10590
+ * @param uniqueColumnValues - is derived from primary keys and unique indexes in the table
10629
10591
  */
10630
- findByOptional(...args) {
10631
- return _queryFindByOptional(
10632
- this.clone(),
10633
- args
10634
- );
10592
+ findByOptional(uniqueColumnValues) {
10593
+ return _queryFindByOptional(this.clone(), [
10594
+ uniqueColumnValues
10595
+ ]);
10635
10596
  }
10636
10597
  /**
10637
10598
  * Specifies the schema to be used as a prefix of a table name.
@@ -10777,9 +10738,9 @@ class QueryMethods {
10777
10738
  * Order by raw SQL expression.
10778
10739
  *
10779
10740
  * ```ts
10780
- * db.table.order`raw sql`;
10741
+ * db.table.orderSql`raw sql`;
10781
10742
  * // or
10782
- * db.table.order(db.table.sql`raw sql`);
10743
+ * db.table.orderSql(db.table.sql`raw sql`);
10783
10744
  * ```
10784
10745
  *
10785
10746
  * @param args - SQL expression
@@ -11021,9 +10982,86 @@ orchidCore.applyMixins(QueryMethods, [
11021
10982
  SoftDeleteMethods
11022
10983
  ]);
11023
10984
 
10985
+ const makeIndex = (columns, first, second) => {
10986
+ if (typeof first === "string") {
10987
+ const options = second != null ? second : {};
10988
+ return {
10989
+ index: { columns, options, name: first }
10990
+ };
10991
+ } else {
10992
+ const options = first != null ? first : {};
10993
+ return {
10994
+ index: { columns, options }
10995
+ };
10996
+ }
10997
+ };
10998
+ const tableDataMethods = {
10999
+ primaryKey(columns, name) {
11000
+ return { primaryKey: { columns, name } };
11001
+ },
11002
+ unique(columns, ...[first, second]) {
11003
+ const input = makeIndex(columns, first, second);
11004
+ input.index.options.unique = true;
11005
+ return input;
11006
+ },
11007
+ index: makeIndex,
11008
+ searchIndex(columns, ...[first, second]) {
11009
+ var _a, _b;
11010
+ const input = makeIndex(columns, first, second);
11011
+ (_b = (_a = input.index.options).using) != null ? _b : _a.using = "gin";
11012
+ input.index.options.tsVector = true;
11013
+ return input;
11014
+ },
11015
+ foreignKey(columns, fnOrTable, foreignColumns, options) {
11016
+ return {
11017
+ constraint: {
11018
+ name: options == null ? void 0 : options.name,
11019
+ references: { columns, fnOrTable, foreignColumns, options }
11020
+ }
11021
+ };
11022
+ },
11023
+ check(check, name) {
11024
+ return { constraint: { check, name } };
11025
+ },
11026
+ sql: sqlFn
11027
+ };
11028
+ const parseTableData = (dataFn) => {
11029
+ const tableData = {};
11030
+ if (dataFn) {
11031
+ const input = dataFn(tableDataMethods);
11032
+ if (Array.isArray(input)) {
11033
+ for (const item of input) {
11034
+ parseTableDataInput(tableData, item);
11035
+ }
11036
+ } else {
11037
+ parseTableDataInput(tableData, input);
11038
+ }
11039
+ }
11040
+ return tableData;
11041
+ };
11042
+ const parseTableDataInput = (tableData, item) => {
11043
+ var _a, _b, _c, _d;
11044
+ if (item.primaryKey) {
11045
+ tableData.primaryKey = item.primaryKey;
11046
+ } else if (item.index) {
11047
+ const index = item.index;
11048
+ for (let i = index.columns.length - 1; i >= 0; i--) {
11049
+ if (typeof index.columns[i] === "string") {
11050
+ index.columns[i] = {
11051
+ column: index.columns[i]
11052
+ };
11053
+ }
11054
+ }
11055
+ ((_a = tableData.indexes) != null ? _a : tableData.indexes = []).push(item.index);
11056
+ } else if (item.constraint) {
11057
+ ((_b = tableData.constraints) != null ? _b : tableData.constraints = []).push(item.constraint);
11058
+ if ((_d = (_c = item.constraint.references) == null ? void 0 : _c.options) == null ? void 0 : _d.dropMode) {
11059
+ item.constraint.dropMode = item.constraint.references.options.dropMode;
11060
+ }
11061
+ }
11062
+ };
11063
+
11024
11064
  var __defProp = Object.defineProperty;
11025
- var __defProps = Object.defineProperties;
11026
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
11027
11065
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
11028
11066
  var __hasOwnProp = Object.prototype.hasOwnProperty;
11029
11067
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
@@ -11039,7 +11077,6 @@ var __spreadValues = (a, b) => {
11039
11077
  }
11040
11078
  return a;
11041
11079
  };
11042
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
11043
11080
  var __objRest = (source, exclude) => {
11044
11081
  var target = {};
11045
11082
  for (var prop in source)
@@ -11054,24 +11091,24 @@ var __objRest = (source, exclude) => {
11054
11091
  };
11055
11092
  const anyShape = {};
11056
11093
  class Db {
11057
- constructor(adapter, queryBuilder, table = void 0, shape = anyShape, columnTypes, transactionStorage, options, tableData = getTableData()) {
11094
+ constructor(adapter, queryBuilder, table = void 0, shape = anyShape, columnTypes, transactionStorage, options, tableData = orchidCore.emptyObject) {
11058
11095
  this.adapter = adapter;
11059
11096
  this.queryBuilder = queryBuilder;
11060
11097
  this.table = table;
11061
11098
  this.shape = shape;
11062
11099
  this.columnTypes = columnTypes;
11063
- this.tableData = tableData;
11064
- var _a, _b;
11100
+ var _a;
11065
11101
  const self = this;
11066
11102
  const { softDelete } = options;
11067
11103
  const scopes = options.scopes || softDelete ? {} : orchidCore.emptyObject;
11068
- this.internal = __spreadProps(__spreadValues({}, tableData), {
11104
+ this.internal = {
11069
11105
  transactionStorage,
11070
11106
  scopes,
11071
11107
  snakeCase: options.snakeCase,
11072
11108
  noPrimaryKey: options.noPrimaryKey === "ignore",
11073
- comment: options.comment
11074
- });
11109
+ comment: options.comment,
11110
+ tableData
11111
+ };
11075
11112
  this.baseQuery = this;
11076
11113
  const logger = options.logger || console;
11077
11114
  const parsers = {};
@@ -11132,20 +11169,21 @@ class Db {
11132
11169
  log: logParamToLogObject(logger, options.log),
11133
11170
  autoPreparedStatements: (_a = options.autoPreparedStatements) != null ? _a : false,
11134
11171
  parsers: hasParsers ? parsers : void 0,
11135
- language: options.language
11172
+ language: options.language,
11173
+ schema: options == null ? void 0 : options.schema
11136
11174
  };
11137
- if (options == null ? void 0 : options.schema) {
11138
- this.q.schema = options.schema;
11175
+ let shapeHasPrimaryKey;
11176
+ for (const key in shape) {
11177
+ if (shape[key].data.primaryKey) {
11178
+ shapeHasPrimaryKey = true;
11179
+ if (this.internal.singlePrimaryKey) {
11180
+ this.internal.singlePrimaryKey = void 0;
11181
+ break;
11182
+ }
11183
+ this.internal.singlePrimaryKey = key;
11184
+ }
11139
11185
  }
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") {
11186
+ if (!shapeHasPrimaryKey && !tableData.primaryKey && shape !== anyShape && options.noPrimaryKey !== "ignore") {
11149
11187
  const message = `Table ${table} has no primary key`;
11150
11188
  if (options.noPrimaryKey === "error")
11151
11189
  throw new Error(message);
@@ -11341,14 +11379,15 @@ const createDb = (_a) => {
11341
11379
  commonOptions,
11342
11380
  options
11343
11381
  );
11344
- const tableConstructor = (table, shape, options2) => new Db(
11382
+ const tableConstructor = (table, shape, dataFn, options2) => new Db(
11345
11383
  adapter,
11346
11384
  qb,
11347
11385
  table,
11348
11386
  typeof shape === "function" ? getColumnTypes(ct, shape, nowSQL, options2 == null ? void 0 : options2.language) : shape,
11349
11387
  ct,
11350
11388
  transactionStorage,
11351
- __spreadValues(__spreadValues({}, commonOptions), options2)
11389
+ __spreadValues(__spreadValues({}, commonOptions), options2),
11390
+ parseTableData(dataFn)
11352
11391
  );
11353
11392
  const db = Object.assign(tableConstructor, qb, {
11354
11393
  adapter,
@@ -11367,8 +11406,7 @@ const _initQueryBuilder = (adapter, columnTypes, transactionStorage, commonOptio
11367
11406
  anyShape,
11368
11407
  columnTypes,
11369
11408
  transactionStorage,
11370
- commonOptions,
11371
- orchidCore.emptyObject
11409
+ commonOptions
11372
11410
  );
11373
11411
  if (options.extensions) {
11374
11412
  const arr = [];
@@ -11687,7 +11725,6 @@ exports.columnForeignKeysToCode = columnForeignKeysToCode;
11687
11725
  exports.columnIndexesToCode = columnIndexesToCode;
11688
11726
  exports.columnsShapeToCode = columnsShapeToCode;
11689
11727
  exports.constraintInnerToCode = constraintInnerToCode;
11690
- exports.constraintPropsToCode = constraintPropsToCode;
11691
11728
  exports.constraintToCode = constraintToCode;
11692
11729
  exports.copyTableData = copyTableData;
11693
11730
  exports.countSelect = countSelect;
@@ -11698,10 +11735,9 @@ exports.foreignKeyArgumentToCode = foreignKeyArgumentToCode;
11698
11735
  exports.getClonedQueryData = getClonedQueryData;
11699
11736
  exports.getColumnInfo = getColumnInfo;
11700
11737
  exports.getColumnTypes = getColumnTypes;
11701
- exports.getConstraintKind = getConstraintKind;
11738
+ exports.getPrimaryKeys = getPrimaryKeys;
11702
11739
  exports.getQueryAs = getQueryAs;
11703
11740
  exports.getShapeFromSelect = getShapeFromSelect;
11704
- exports.getTableData = getTableData;
11705
11741
  exports.handleResult = handleResult;
11706
11742
  exports.identityToCode = identityToCode;
11707
11743
  exports.indexInnerToCode = indexInnerToCode;
@@ -11719,17 +11755,18 @@ exports.makeExpression = makeExpression;
11719
11755
  exports.makeFnExpression = makeFnExpression;
11720
11756
  exports.makeRegexToFindInSql = makeRegexToFindInSql;
11721
11757
  exports.makeSQL = makeSQL;
11722
- exports.newTableData = newTableData;
11723
11758
  exports.parseRecord = parseRecord;
11724
11759
  exports.parseResult = parseResult;
11760
+ exports.parseTableData = parseTableData;
11761
+ exports.parseTableDataInput = parseTableDataInput;
11725
11762
  exports.primaryKeyInnerToCode = primaryKeyInnerToCode;
11726
- exports.primaryKeyToCode = primaryKeyToCode;
11727
11763
  exports.processSelectArg = processSelectArg;
11728
11764
  exports.pushLimitSQL = pushLimitSQL;
11729
11765
  exports.pushQueryArray = pushQueryArray;
11730
11766
  exports.pushQueryOn = pushQueryOn;
11731
11767
  exports.pushQueryOrOn = pushQueryOrOn;
11732
11768
  exports.pushQueryValue = pushQueryValue;
11769
+ exports.pushTableDataCode = pushTableDataCode;
11733
11770
  exports.queryFrom = queryFrom;
11734
11771
  exports.queryFromSql = queryFromSql;
11735
11772
  exports.queryJson = queryJson;
@@ -11740,14 +11777,15 @@ exports.quote = quote;
11740
11777
  exports.quoteString = quoteString;
11741
11778
  exports.raw = raw;
11742
11779
  exports.referencesArgsToCode = referencesArgsToCode;
11743
- exports.resetTableData = resetTableData;
11744
11780
  exports.resolveSubQueryCallback = resolveSubQueryCallback;
11745
11781
  exports.saveSearchAlias = saveSearchAlias;
11746
11782
  exports.setParserForSelectedString = setParserForSelectedString;
11747
11783
  exports.setQueryObjectValue = setQueryObjectValue;
11748
11784
  exports.setQueryOperators = setQueryOperators;
11749
11785
  exports.simplifyColumnDefault = simplifyColumnDefault;
11786
+ exports.sqlFn = sqlFn;
11750
11787
  exports.sqlQueryArgsToExpression = sqlQueryArgsToExpression;
11788
+ exports.tableDataMethods = tableDataMethods;
11751
11789
  exports.templateLiteralToSQL = templateLiteralToSQL;
11752
11790
  exports.testTransaction = testTransaction;
11753
11791
  exports.throwIfNoWhere = throwIfNoWhere;