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