pqb 0.27.6 → 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
@@ -1,4 +1,4 @@
1
- import { ExpressionTypeMethod, Expression, RawSQLBase, isTemplateLiteralArgs, ColumnTypeBase, setColumnData, pushColumnData, emptyObject, quoteObjectKey, toArray, singleQuote, addCode, objectHasValues, singleQuoteArray, columnDefaultArgumentToCode, columnErrorMessagesToCode, isExpression, dateDataToCode, joinTruthy, arrayDataToCode, noop, getValueKey, emptyArray, callWithThis, setParserToQuery, applyTransforms, isRawSQL, pushOrNewArray, pushOrNewArrayToObject, numberDataToCode, stringDataToCode, getDefaultLanguage, setDefaultNowFn, setDefaultLanguage, makeTimestampsHelpers, setCurrentColumnName, setAdapterConnectRetry, isObjectEmpty, applyMixins, toSnakeCase, snakeCaseKey } from 'orchid-core';
1
+ import { ExpressionTypeMethod, Expression, RawSQLBase, isTemplateLiteralArgs, ColumnTypeBase, setColumnData, pushColumnData, emptyObject, quoteObjectKey, toArray, singleQuote, addCode, singleQuoteArray, objectHasValues, columnDefaultArgumentToCode, columnErrorMessagesToCode, isExpression, dateDataToCode, joinTruthy, arrayDataToCode, noop, getValueKey, emptyArray, callWithThis, setParserToQuery, applyTransforms, isRawSQL, pushOrNewArray, pushOrNewArrayToObject, numberDataToCode, stringDataToCode, getDefaultLanguage, setDefaultNowFn, setDefaultLanguage, makeTimestampsHelpers, setCurrentColumnName, setAdapterConnectRetry, isObjectEmpty, applyMixins, toSnakeCase, snakeCaseKey } from 'orchid-core';
2
2
  import pg from 'pg';
3
3
  import { inspect } from 'node:util';
4
4
  import { AsyncLocalStorage } from 'node:async_hooks';
@@ -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,30 +146,90 @@ 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
  *
139
154
  * // primary key can be used by `find` later:
140
155
  * db.table.find('97ba9e78-7510-415a-9c03-23d440aec443');
141
156
  * ```
157
+ *
158
+ * @param name - to specify a constraint name
142
159
  */
143
- primaryKey() {
144
- return setColumnData(this, "isPrimaryKey", true);
160
+ primaryKey(name) {
161
+ return setColumnData(this, "primaryKey", name != null ? name : true);
145
162
  }
146
163
  foreignKey(fnOrTable, column, options = emptyObject) {
147
- const item = typeof fnOrTable === "string" ? __spreadValues$h({ table: fnOrTable, columns: [column] }, options) : __spreadValues$h({ fn: fnOrTable, columns: [column] }, options);
148
- return pushColumnData(this, "foreignKeys", item);
164
+ return pushColumnData(this, "foreignKeys", {
165
+ fnOrTable,
166
+ foreignColumns: [column],
167
+ options
168
+ });
149
169
  }
150
170
  toSQL() {
151
171
  return this.dataType;
152
172
  }
153
- index(options = {}) {
154
- 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
+ });
155
228
  }
156
229
  /**
157
- * `searchIndex` is designed for full text search.
230
+ * `searchIndex` is designed for [full text search](/guide/text-search).
158
231
  *
159
- * It can accept the same options as a regular `index`, but it is `USING GIN` by default, and it is concatenating columns into a `tsvector`.
232
+ * It can accept the same options as a regular `index`, but it is `USING GIN` by default, and it is concatenating columns into a `tsvector` database type.
160
233
  *
161
234
  * ```ts
162
235
  * import { change } from '../dbScript';
@@ -164,8 +237,8 @@ class ColumnType extends ColumnTypeBase {
164
237
  * change(async (db) => {
165
238
  * await db.createTable('table', (t) => ({
166
239
  * id: t.identity().primaryKey(),
167
- * title: t.string(),
168
- * body: t.string(),
240
+ * title: t.text(),
241
+ * body: t.text(),
169
242
  * ...t.searchIndex(['title', 'body']),
170
243
  * }));
171
244
  * });
@@ -174,10 +247,29 @@ class ColumnType extends ColumnTypeBase {
174
247
  * Produces the following index ('english' is a default language, see [full text search](/guide/text-search.html#language) for changing it):
175
248
  *
176
249
  * ```sql
177
- * CREATE INDEX "table_title_body_idx" ON "table" USING GIN (to_tsvector('english', concat_ws(' ', "title", "body")))
250
+ * CREATE INDEX "table_title_body_idx" ON "table" USING GIN (to_tsvector('english', "title" || ' ' || "body"))
251
+ * ```
252
+ *
253
+ * You can set different search weights (`A` to `D`) on different columns inside the index:
254
+ *
255
+ * ```ts
256
+ * import { change } from '../dbScript';
257
+ *
258
+ * change(async (db) => {
259
+ * await db.createTable('table', (t) => ({
260
+ * id: t.identity().primaryKey(),
261
+ * title: t.text(),
262
+ * body: t.text(),
263
+ * ...t.searchIndex([
264
+ * { column: 'title', weight: 'A' },
265
+ * { column: 'body', weight: 'B' },
266
+ * ]),
267
+ * }));
268
+ * });
178
269
  * ```
179
270
  *
180
- * Also, it works well with a generated `tsvector` column:
271
+ * When the table has localized columns,
272
+ * you can define different indexes for different languages by setting the `language` parameter:
181
273
  *
182
274
  * ```ts
183
275
  * import { change } from '../dbScript';
@@ -185,8 +277,44 @@ class ColumnType extends ColumnTypeBase {
185
277
  * change(async (db) => {
186
278
  * await db.createTable('table', (t) => ({
187
279
  * id: t.identity().primaryKey(),
188
- * title: t.string(),
189
- * body: t.string(),
280
+ * titleEn: t.text(),
281
+ * bodyEn: t.text(),
282
+ * titleFr: t.text(),
283
+ * bodyFr: t.text(),
284
+ * ...t.searchIndex(['titleEn', 'bodyEn'], { language: 'english' }),
285
+ * ...t.searchIndex(['titleFr', 'bodyFr'], { language: 'french' }),
286
+ * }));
287
+ * });
288
+ * ```
289
+ *
290
+ * Alternatively, different table records may correspond to a single language,
291
+ * then you can define a search index that relies on a language column by using `languageColumn` parameter:
292
+ *
293
+ * ```ts
294
+ * import { change } from '../dbScript';
295
+ *
296
+ * change(async (db) => {
297
+ * await db.createTable('table', (t) => ({
298
+ * id: t.identity().primaryKey(),
299
+ * lang: t.type('regconfig'),
300
+ * title: t.text(),
301
+ * body: t.text(),
302
+ * ...t.searchIndex(['title', 'body'], { languageColumn: 'lang' }),
303
+ * }));
304
+ * });
305
+ * ```
306
+ *
307
+ * It can be more efficient to use a [generated](/guide/migration-column-methods.html#generated-column) column instead of indexing text column in the way described above,
308
+ * and to set a `searchIndex` on it:
309
+ *
310
+ * ```ts
311
+ * import { change } from '../dbScript';
312
+ *
313
+ * change(async (db) => {
314
+ * await db.createTable('table', (t) => ({
315
+ * id: t.identity().primaryKey(),
316
+ * title: t.text(),
317
+ * body: t.text(),
190
318
  * generatedTsVector: t.tsvector().generated(['title', 'body']).searchIndex(),
191
319
  * }));
192
320
  * });
@@ -200,11 +328,19 @@ class ColumnType extends ColumnTypeBase {
200
328
  *
201
329
  * @param options - index options
202
330
  */
203
- searchIndex(options) {
204
- 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
+ });
205
336
  }
206
- unique(options = {}) {
207
- 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
+ });
208
344
  }
209
345
  comment(comment) {
210
346
  return setColumnData(this, "comment", comment);
@@ -243,8 +379,8 @@ class ColumnType extends ColumnTypeBase {
243
379
  }
244
380
 
245
381
  var __defProp$g = Object.defineProperty;
246
- var __defProps$a = Object.defineProperties;
247
- var __getOwnPropDescs$a = Object.getOwnPropertyDescriptors;
382
+ var __defProps$8 = Object.defineProperties;
383
+ var __getOwnPropDescs$8 = Object.getOwnPropertyDescriptors;
248
384
  var __getOwnPropSymbols$h = Object.getOwnPropertySymbols;
249
385
  var __hasOwnProp$h = Object.prototype.hasOwnProperty;
250
386
  var __propIsEnum$h = Object.prototype.propertyIsEnumerable;
@@ -260,34 +396,32 @@ var __spreadValues$g = (a, b) => {
260
396
  }
261
397
  return a;
262
398
  };
263
- var __spreadProps$a = (a, b) => __defProps$a(a, __getOwnPropDescs$a(b));
399
+ var __spreadProps$8 = (a, b) => __defProps$8(a, __getOwnPropDescs$8(b));
264
400
  const knownDefaults = {
265
401
  current_timestamp: "now()",
266
402
  "transaction_timestamp()": "now()"
267
403
  };
268
404
  const simplifyColumnDefault = (value) => {
269
405
  if (typeof value === "string") {
270
- const lower = value.toLowerCase();
271
- return new RawSQL(knownDefaults[lower] || value);
406
+ return new RawSQL([
407
+ [knownDefaults[value.toLowerCase()] || value]
408
+ ]);
272
409
  }
273
410
  return;
274
411
  };
275
412
  const instantiateColumn = (typeFn, params) => {
276
413
  const column = typeFn();
277
- Object.assign(column.data, __spreadProps$a(__spreadValues$g({}, params), {
414
+ const { dateTimePrecision } = params;
415
+ Object.assign(column.data, __spreadProps$8(__spreadValues$g({}, params), {
416
+ dateTimePrecision: (
417
+ // 0 is default for date, 6 is default for timestamp
418
+ dateTimePrecision && dateTimePrecision !== 6 ? dateTimePrecision : void 0
419
+ ),
420
+ collate: params.collate,
278
421
  default: simplifyColumnDefault(params.default)
279
422
  }));
280
423
  return column;
281
424
  };
282
- const getConstraintKind = (it) => {
283
- let num = 0;
284
- for (const key in it) {
285
- if ((key === "references" || key === "check") && it[key] !== void 0) {
286
- num++;
287
- }
288
- }
289
- return num === 1 ? it.references ? "foreignKey" : "check" : "constraint";
290
- };
291
425
 
292
426
  const isDefaultTimeStamp = (item) => {
293
427
  if (item.dataType !== "timestamptz")
@@ -315,7 +449,7 @@ const combineCodeElements = (input) => {
315
449
  }
316
450
  return output;
317
451
  };
318
- const columnsShapeToCode = (shape, tableData, t) => {
452
+ const columnsShapeToCode = (shape, t) => {
319
453
  const hasTimestamps = "createdAt" in shape && isDefaultTimeStamp(shape.createdAt) && "updatedAt" in shape && isDefaultTimeStamp(shape.updatedAt);
320
454
  const code = [];
321
455
  for (const key in shape) {
@@ -332,30 +466,64 @@ const columnsShapeToCode = (shape, tableData, t) => {
332
466
  if (hasTimestamps) {
333
467
  code.push(`...${t}.timestamps(),`);
334
468
  }
335
- const { primaryKey, indexes, constraints } = tableData;
336
- if (primaryKey) {
337
- 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") + ","]);
338
475
  }
339
- if (indexes) {
340
- for (const index of indexes) {
341
- code.push(...indexToCode(index, t));
476
+ if (ast.indexes) {
477
+ for (const index of ast.indexes) {
478
+ lines.push(indexToCode(index, "t"));
342
479
  }
343
480
  }
344
- if (constraints) {
345
- for (const item of constraints) {
346
- code.push(...constraintToCode(item, t));
481
+ if (ast.constraints) {
482
+ for (const constraint of ast.constraints) {
483
+ lines.push(constraintToCode(constraint, "t", true));
347
484
  }
348
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
+ }
349
493
  return code;
350
494
  };
351
- const primaryKeyToCode = (primaryKey, t) => {
352
- var _a;
353
- const name = (_a = primaryKey.options) == null ? void 0 : _a.name;
354
- return `...${t}.primaryKey([${primaryKey.columns.map(singleQuote).join(", ")}]${name ? `, { name: ${singleQuote(name)} }` : ""}),`;
495
+ const primaryKeyInnerToCode = (primaryKey, t) => {
496
+ const name = primaryKey.name;
497
+ return `${t}.primaryKey([${primaryKey.columns.map(singleQuote).join(", ")}]${name ? `, ${singleQuote(name)}` : ""})`;
498
+ };
499
+ const indexToCode = (index, t, prefix) => {
500
+ const code = indexInnerToCode(index, t);
501
+ if (prefix)
502
+ code[0] = prefix + code[0];
503
+ const last = code[code.length - 1];
504
+ if (typeof last === "string" && !last.endsWith(","))
505
+ addCode(code, ",");
506
+ return code;
355
507
  };
356
- const indexToCode = (index, t) => {
508
+ const indexInnerToCode = (index, t) => {
357
509
  const code = [];
358
- code.push(`...${t}.index(`);
510
+ code.push(
511
+ `${t}.${index.options.tsVector ? "searchIndex" : index.options.unique ? "unique" : "index"}(`
512
+ );
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]);
359
527
  const columnsMultiline = index.columns.some((column) => {
360
528
  for (const key in column) {
361
529
  if (key !== "column" && column[key] !== void 0)
@@ -369,7 +537,7 @@ const indexToCode = (index, t) => {
369
537
  const expr = "column" in column ? column.column : column.expression;
370
538
  let hasOptions2 = false;
371
539
  for (const key in column) {
372
- if (key !== "column" && key !== "expression") {
540
+ if (key !== "column") {
373
541
  hasOptions2 = true;
374
542
  }
375
543
  }
@@ -381,36 +549,38 @@ const indexToCode = (index, t) => {
381
549
  expr
382
550
  )},`
383
551
  ];
384
- if (column.collate !== void 0) {
385
- props.push(`collate: ${singleQuote(column.collate)},`);
386
- }
387
- if (column.opclass !== void 0) {
388
- props.push(`opclass: ${singleQuote(column.opclass)},`);
389
- }
390
- if (column.order !== void 0) {
391
- props.push(`order: ${singleQuote(column.order)},`);
552
+ for (const key of columnOptions) {
553
+ const value = column[key];
554
+ if (value !== void 0) {
555
+ props.push(`${key}: ${singleQuote(value)},`);
556
+ }
392
557
  }
393
558
  objects.push("{", props, "},");
394
559
  }
395
560
  }
396
- code.push(["[", objects, "]"]);
561
+ code.push(["[", objects, hasOptions || index.name ? "]," : "]"]);
562
+ if (index.name) {
563
+ addCode(code, ` ${singleQuote(index.name)},`);
564
+ }
397
565
  } else {
398
566
  addCode(
399
567
  code,
400
568
  `[${index.columns.map((it) => singleQuote(it.column)).join(", ")}]`
401
569
  );
570
+ if (index.name) {
571
+ addCode(code, `, ${singleQuote(index.name)}`);
572
+ }
402
573
  }
403
- const hasOptions = objectHasValues(index.options);
404
574
  if (hasOptions) {
405
575
  if (columnsMultiline) {
406
- const columns = code[code.length - 1];
407
- columns[columns.length - 1] += ",";
408
576
  code.push(["{"]);
409
577
  } else {
410
578
  addCode(code, ", {");
411
579
  }
412
580
  const options = [];
413
- for (const key in index.options) {
581
+ for (const key of indexOptionsKeys) {
582
+ if (!key)
583
+ continue;
414
584
  const value = index.options[key];
415
585
  if (value === null || value === void 0)
416
586
  continue;
@@ -428,49 +598,43 @@ const indexToCode = (index, t) => {
428
598
  if (columnsMultiline) {
429
599
  code.push("),");
430
600
  } else {
431
- addCode(code, "),");
601
+ addCode(code, ")");
432
602
  }
433
603
  return code;
434
604
  };
435
- const constraintToCode = (item, t) => {
436
- const kind = getConstraintKind(item);
437
- if (kind === "foreignKey" && item.references) {
605
+ const constraintToCode = (item, t, m, prefix) => {
606
+ const code = constraintInnerToCode(item, t, m);
607
+ if (prefix)
608
+ code[0] = prefix + code[0];
609
+ const last = code[code.length - 1];
610
+ if (typeof last === "string" && !last.endsWith(","))
611
+ code[code.length - 1] += ",";
612
+ return code;
613
+ };
614
+ const constraintInnerToCode = (item, t, m) => {
615
+ if (item.references) {
438
616
  return [
439
- `...${t}.foreignKey(`,
440
- referencesArgsToCode(item.references, item.name),
617
+ `${t}.foreignKey(`,
618
+ referencesArgsToCode(item.references, item.name, m),
441
619
  "),"
442
620
  ];
443
- } else if (kind === "check" && item.check) {
444
- return [`...${t}.check(${item.check.toCode(t)}),`];
445
- } else {
446
- return [`...${t}.constraint({`, constraintPropsToCode(t, item), "}),"];
447
- }
448
- };
449
- const constraintPropsToCode = (t, item) => {
450
- const props = [];
451
- if (item.name) {
452
- props.push(`name: ${singleQuote(item.name)},`);
453
- }
454
- if (item.references) {
455
- props.push(
456
- `references: [`,
457
- referencesArgsToCode(item.references, false),
458
- "],"
459
- );
460
- }
461
- if (item.check) {
462
- props.push(`check: ${item.check.toCode(t)},`);
463
621
  }
464
- return props;
622
+ return [
623
+ `${t}.check(${item.check.toCode(t)}${item.name ? `, ${singleQuote(item.name)}` : ""})`
624
+ ];
465
625
  };
466
626
  const referencesArgsToCode = ({
467
627
  columns,
468
628
  fnOrTable,
469
629
  foreignColumns,
470
630
  options
471
- }, name = (options == null ? void 0 : options.name) || false) => {
631
+ }, name = (options == null ? void 0 : options.name) || false, m) => {
472
632
  const args = [];
473
633
  args.push(`${singleQuoteArray(columns)},`);
634
+ if (m && typeof fnOrTable !== "string") {
635
+ const { schema, table } = new (fnOrTable())();
636
+ fnOrTable = schema ? `${schema}.${table}` : table;
637
+ }
474
638
  args.push(
475
639
  `${typeof fnOrTable === "string" ? singleQuote(fnOrTable) : fnOrTable.toString()},`
476
640
  );
@@ -490,36 +654,42 @@ const referencesArgsToCode = ({
490
654
  }
491
655
  return args;
492
656
  };
493
- const columnForeignKeysToCode = (foreignKeys) => {
657
+ const columnForeignKeysToCode = (foreignKeys, migration) => {
494
658
  const code = [];
495
659
  for (const foreignKey of foreignKeys) {
496
660
  addCode(code, `.foreignKey(`);
497
- for (const part of foreignKeyArgumentToCode(foreignKey)) {
661
+ for (const part of foreignKeyArgumentToCode(foreignKey, migration)) {
498
662
  addCode(code, part);
499
663
  }
500
664
  addCode(code, ")");
501
665
  }
502
666
  return code;
503
667
  };
504
- const foreignKeyArgumentToCode = (foreignKey) => {
668
+ const foreignKeyArgumentToCode = ({
669
+ fnOrTable,
670
+ foreignColumns,
671
+ options = emptyObject
672
+ }, migration) => {
505
673
  const code = [];
506
- if ("fn" in foreignKey) {
507
- code.push(foreignKey.fn.toString());
508
- } else {
509
- code.push(singleQuote(foreignKey.table));
674
+ if (migration && typeof fnOrTable !== "string") {
675
+ const { schema, table } = new (fnOrTable())();
676
+ fnOrTable = schema ? `${schema}.${table}` : table;
510
677
  }
511
- addCode(code, `, ${singleQuote(foreignKey.columns[0])}`);
512
- const hasOptions = foreignKey.name || foreignKey.match || foreignKey.onUpdate || foreignKey.onDelete;
678
+ code.push(
679
+ typeof fnOrTable === "string" ? singleQuote(fnOrTable) : fnOrTable.toString()
680
+ );
681
+ addCode(code, `, ${singleQuote(foreignColumns[0])}`);
682
+ const hasOptions = options.name || options.match || options.onUpdate || options.onDelete;
513
683
  if (hasOptions) {
514
684
  const arr = [];
515
- if (foreignKey.name)
516
- arr.push(`name: ${singleQuote(foreignKey.name)},`);
517
- if (foreignKey.match)
518
- arr.push(`match: ${singleQuote(foreignKey.match)},`);
519
- if (foreignKey.onUpdate)
520
- arr.push(`onUpdate: ${singleQuote(foreignKey.onUpdate)},`);
521
- if (foreignKey.onDelete)
522
- 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)},`);
523
693
  addCode(code, ", {");
524
694
  code.push(arr);
525
695
  addCode(code, "}");
@@ -528,31 +698,31 @@ const foreignKeyArgumentToCode = (foreignKey) => {
528
698
  };
529
699
  const columnIndexesToCode = (indexes) => {
530
700
  const code = [];
531
- for (const index of indexes) {
532
- addCode(code, `.${index.unique ? "unique" : "index"}(`);
701
+ for (const { options, name } of indexes) {
702
+ addCode(code, `.${options.unique ? "unique" : "index"}(`);
533
703
  const arr = [];
534
- if (index.collate)
535
- arr.push(`collate: ${singleQuote(index.collate)},`);
536
- if (index.opclass)
537
- arr.push(`opclass: ${singleQuote(index.opclass)},`);
538
- if (index.order)
539
- arr.push(`order: ${singleQuote(index.order)},`);
540
- if (index.name)
541
- arr.push(`name: ${singleQuote(index.name)},`);
542
- if (index.using)
543
- arr.push(`using: ${singleQuote(index.using)},`);
544
- 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)
545
715
  arr.push(
546
- `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(", ")}]`},`
547
717
  );
548
- if (index.nullsNotDistinct)
718
+ if (options.nullsNotDistinct)
549
719
  arr.push(`nullsNotDistinct: true,`);
550
- if (index.with)
551
- arr.push(`with: ${singleQuote(index.with)},`);
552
- if (index.tablespace)
553
- arr.push(`tablespace: ${singleQuote(index.tablespace)},`);
554
- if (index.where)
555
- 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)},`);
556
726
  if (arr.length) {
557
727
  addCode(code, "{");
558
728
  addCode(code, arr);
@@ -562,8 +732,8 @@ const columnIndexesToCode = (indexes) => {
562
732
  }
563
733
  return code;
564
734
  };
565
- const columnCheckToCode = (t, check) => {
566
- return `.check(${check.toCode(t)})`;
735
+ const columnCheckToCode = (t, { sql, name }) => {
736
+ return `.check(${sql.toCode(t)}${name ? `, { name: '${name}' }` : ""})`;
567
737
  };
568
738
  const identityToCode = (identity, dataType) => {
569
739
  const code = [];
@@ -575,16 +745,18 @@ const identityToCode = (identity, dataType) => {
575
745
  const props = [];
576
746
  if (identity.always)
577
747
  props.push(`always: true,`);
578
- if (identity.incrementBy)
579
- props.push(`incrementBy: ${identity.incrementBy},`);
580
- if (identity.startWith)
581
- props.push(`startWith: ${identity.startWith},`);
748
+ if (identity.increment && identity.increment !== 1)
749
+ props.push(`increment: ${identity.increment},`);
750
+ if (identity.start && identity.start !== 1)
751
+ props.push(`start: ${identity.start},`);
582
752
  if (identity.min)
583
753
  props.push(`min: ${identity.min},`);
584
754
  if (identity.max)
585
755
  props.push(`max: ${identity.max},`);
586
- if (identity.cache)
756
+ if (identity.cache && identity.cache !== 1)
587
757
  props.push(`cache: ${identity.cache},`);
758
+ if (identity.cycle)
759
+ props.push(`cycle: true,`);
588
760
  if (props.length) {
589
761
  addCode(code, "{");
590
762
  code.push(props, "}");
@@ -592,7 +764,7 @@ const identityToCode = (identity, dataType) => {
592
764
  addCode(code, ")");
593
765
  return code;
594
766
  };
595
- const columnCode = (type, t, code, data = type.data, skip) => {
767
+ const columnCode = (type, t, code, migration, data = type.data, skip) => {
596
768
  code = toArray(code);
597
769
  let prepend = `${t}.`;
598
770
  if (data.name) {
@@ -603,10 +775,14 @@ const columnCode = (type, t, code, data = type.data, skip) => {
603
775
  } else {
604
776
  code[0].unshift(prepend);
605
777
  }
606
- if (data.isPrimaryKey)
607
- addCode(code, ".primaryKey()");
778
+ if (data.primaryKey) {
779
+ addCode(
780
+ code,
781
+ `.primaryKey(${data.primaryKey === true ? "" : singleQuote(data.primaryKey)})`
782
+ );
783
+ }
608
784
  if (data.foreignKeys) {
609
- for (const part of columnForeignKeysToCode(data.foreignKeys)) {
785
+ for (const part of columnForeignKeysToCode(data.foreignKeys, migration)) {
610
786
  addCode(code, part);
611
787
  }
612
788
  }
@@ -620,7 +796,7 @@ const columnCode = (type, t, code, data = type.data, skip) => {
620
796
  addCode(code, `.parse(${type.parseFn.toString()})`);
621
797
  if (data.as)
622
798
  addCode(code, `.as(${data.as.toCode(t)})`);
623
- if (data.default !== void 0) {
799
+ if (data.default !== void 0 && (!migration || typeof data.default !== "function")) {
624
800
  addCode(code, `.default(${columnDefaultArgumentToCode(t, data.default)})`);
625
801
  }
626
802
  if (data.indexes) {
@@ -822,8 +998,8 @@ class JSONColumn extends ColumnType {
822
998
  this.dataType = "jsonb";
823
999
  this.operators = Operators.json;
824
1000
  }
825
- toCode(t) {
826
- return columnCode(this, t, `json()`, this.data, toCodeSkip);
1001
+ toCode(t, m) {
1002
+ return columnCode(this, t, `json()`, m, this.data, toCodeSkip);
827
1003
  }
828
1004
  }
829
1005
  JSONColumn.prototype.encodeFn = JSON.stringify;
@@ -833,8 +1009,8 @@ class JSONTextColumn extends ColumnType {
833
1009
  this.dataType = "json";
834
1010
  this.operators = Operators.text;
835
1011
  }
836
- toCode(t) {
837
- return columnCode(this, t, `jsonText()`, this.data, toCodeSkip);
1012
+ toCode(t, m) {
1013
+ return columnCode(this, t, `jsonText()`, m, this.data, toCodeSkip);
838
1014
  }
839
1015
  }
840
1016
 
@@ -1090,8 +1266,8 @@ const pushIn = (ctx, query, ands, quotedAs, arg) => {
1090
1266
  };
1091
1267
 
1092
1268
  var __defProp$f = Object.defineProperty;
1093
- var __defProps$9 = Object.defineProperties;
1094
- var __getOwnPropDescs$9 = Object.getOwnPropertyDescriptors;
1269
+ var __defProps$7 = Object.defineProperties;
1270
+ var __getOwnPropDescs$7 = Object.getOwnPropertyDescriptors;
1095
1271
  var __getOwnPropSymbols$g = Object.getOwnPropertySymbols;
1096
1272
  var __hasOwnProp$g = Object.prototype.hasOwnProperty;
1097
1273
  var __propIsEnum$g = Object.prototype.propertyIsEnumerable;
@@ -1107,7 +1283,7 @@ var __spreadValues$f = (a, b) => {
1107
1283
  }
1108
1284
  return a;
1109
1285
  };
1110
- var __spreadProps$9 = (a, b) => __defProps$9(a, __getOwnPropDescs$9(b));
1286
+ var __spreadProps$7 = (a, b) => __defProps$7(a, __getOwnPropDescs$7(b));
1111
1287
  const processJoinItem = (ctx, table, query, args, quotedAs) => {
1112
1288
  let target;
1113
1289
  let on;
@@ -1169,8 +1345,8 @@ const processJoinItem = (ctx, table, query, args, quotedAs) => {
1169
1345
  const whereSql = whereToSql(
1170
1346
  ctx,
1171
1347
  q,
1172
- __spreadProps$9(__spreadValues$f({}, q.q), {
1173
- 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), {
1174
1350
  [table.q.as || table.table]: table.q.shape
1175
1351
  })
1176
1352
  }),
@@ -1327,8 +1503,8 @@ const getIsJoinSubQuery = (query) => {
1327
1503
  };
1328
1504
 
1329
1505
  var __defProp$e = Object.defineProperty;
1330
- var __defProps$8 = Object.defineProperties;
1331
- var __getOwnPropDescs$8 = Object.getOwnPropertyDescriptors;
1506
+ var __defProps$6 = Object.defineProperties;
1507
+ var __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors;
1332
1508
  var __getOwnPropSymbols$f = Object.getOwnPropertySymbols;
1333
1509
  var __hasOwnProp$f = Object.prototype.hasOwnProperty;
1334
1510
  var __propIsEnum$f = Object.prototype.propertyIsEnumerable;
@@ -1344,7 +1520,7 @@ var __spreadValues$e = (a, b) => {
1344
1520
  }
1345
1521
  return a;
1346
1522
  };
1347
- var __spreadProps$8 = (a, b) => __defProps$8(a, __getOwnPropDescs$8(b));
1523
+ var __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b));
1348
1524
  const processJoinArgs = (joinTo, first, args, joinSubQuery) => {
1349
1525
  var _a;
1350
1526
  if (typeof first === "string") {
@@ -1376,7 +1552,7 @@ const processJoinArgs = (joinTo, first, args, joinSubQuery) => {
1376
1552
  logger: joinToQ.logger
1377
1553
  };
1378
1554
  j.baseQuery = j;
1379
- const joinedShapes = __spreadProps$8(__spreadValues$e({}, joinToQ.joinedShapes), {
1555
+ const joinedShapes = __spreadProps$6(__spreadValues$e({}, joinToQ.joinedShapes), {
1380
1556
  [joinToQ.as || joinTo.table]: joinTo.shape
1381
1557
  });
1382
1558
  const r = args[0](
@@ -1403,7 +1579,7 @@ const processJoinArgs = (joinTo, first, args, joinSubQuery) => {
1403
1579
  pushQueryArray(q, "or", query.or);
1404
1580
  }
1405
1581
  }
1406
- const joinedShapes = __spreadProps$8(__spreadValues$e({}, joinTo.q.joinedShapes), {
1582
+ const joinedShapes = __spreadProps$6(__spreadValues$e({}, joinTo.q.joinedShapes), {
1407
1583
  [joinTo.q.as || joinTo.table]: joinTo.shape
1408
1584
  });
1409
1585
  const r = args[0](
@@ -1432,8 +1608,8 @@ const makeJoinQueryBuilder = (joinedQuery, joinedShapes, joinTo) => {
1432
1608
  };
1433
1609
 
1434
1610
  var __defProp$d = Object.defineProperty;
1435
- var __defProps$7 = Object.defineProperties;
1436
- var __getOwnPropDescs$7 = Object.getOwnPropertyDescriptors;
1611
+ var __defProps$5 = Object.defineProperties;
1612
+ var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
1437
1613
  var __getOwnPropSymbols$e = Object.getOwnPropertySymbols;
1438
1614
  var __hasOwnProp$e = Object.prototype.hasOwnProperty;
1439
1615
  var __propIsEnum$e = Object.prototype.propertyIsEnumerable;
@@ -1449,7 +1625,7 @@ var __spreadValues$d = (a, b) => {
1449
1625
  }
1450
1626
  return a;
1451
1627
  };
1452
- var __spreadProps$7 = (a, b) => __defProps$7(a, __getOwnPropDescs$7(b));
1628
+ var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
1453
1629
  const _join = (q, require2, type, first, args) => {
1454
1630
  var _a, _b;
1455
1631
  let joinKey;
@@ -1550,7 +1726,7 @@ const _joinLateral = (self, type, arg, cb, as) => {
1550
1726
  const t = Object.create(q.queryBuilder);
1551
1727
  t.table = arg;
1552
1728
  t.shape = shape;
1553
- t.q = __spreadProps$7(__spreadValues$d({}, t.q), {
1729
+ t.q = __spreadProps$5(__spreadValues$d({}, t.q), {
1554
1730
  shape
1555
1731
  });
1556
1732
  t.baseQuery = t;
@@ -1604,11 +1780,12 @@ class DateColumn extends DateBaseColumn {
1604
1780
  super(...arguments);
1605
1781
  this.dataType = "date";
1606
1782
  }
1607
- toCode(t) {
1783
+ toCode(t, m) {
1608
1784
  return columnCode(
1609
1785
  this,
1610
1786
  t,
1611
- `date()${dateDataToCode(this.data)}`,
1787
+ `date()${dateDataToCode(this.data, m)}`,
1788
+ m,
1612
1789
  this.data,
1613
1790
  skipDateMethodsFromToCode
1614
1791
  );
@@ -1635,7 +1812,7 @@ class DateTimeTzBaseClass extends DateTimeBaseClass {
1635
1812
  );
1636
1813
  }
1637
1814
  }
1638
- const timestampToCode = (self, t) => {
1815
+ const timestampToCode = (self, t, m) => {
1639
1816
  const { dateTimePrecision: p } = self.data;
1640
1817
  const { defaultTimestamp } = self.data;
1641
1818
  if (defaultTimestamp) {
@@ -1647,7 +1824,8 @@ const timestampToCode = (self, t) => {
1647
1824
  const code = columnCode(
1648
1825
  self,
1649
1826
  t,
1650
- `timestamps${noTz}(${p && p !== 6 ? p : ""}).${defaultTimestamp}${dateDataToCode(self.data)}`,
1827
+ `timestamps${noTz}(${p && p !== 6 ? p : ""}).${defaultTimestamp}${dateDataToCode(self.data, m)}`,
1828
+ m,
1651
1829
  self.data,
1652
1830
  skipDateMethodsFromToCode
1653
1831
  );
@@ -1658,7 +1836,8 @@ const timestampToCode = (self, t) => {
1658
1836
  return columnCode(
1659
1837
  self,
1660
1838
  t,
1661
- `${self instanceof TimestampColumn ? "timestampNoTZ" : "timestamp"}(${p && p !== 6 ? p : ""})${dateDataToCode(self.data)}`,
1839
+ `${self instanceof TimestampColumn ? "timestampNoTZ" : "timestamp"}(${p && p !== 6 ? p : ""})${dateDataToCode(self.data, m)}`,
1840
+ m,
1662
1841
  self.data,
1663
1842
  skipDateMethodsFromToCode
1664
1843
  );
@@ -1669,8 +1848,8 @@ class TimestampColumn extends DateTimeBaseClass {
1669
1848
  super(...arguments);
1670
1849
  this.dataType = "timestamp";
1671
1850
  }
1672
- toCode(t) {
1673
- return timestampToCode(this, t);
1851
+ toCode(t, m) {
1852
+ return timestampToCode(this, t, m);
1674
1853
  }
1675
1854
  }
1676
1855
  class TimestampTZColumn extends DateTimeTzBaseClass {
@@ -1679,8 +1858,8 @@ class TimestampTZColumn extends DateTimeTzBaseClass {
1679
1858
  this.dataType = "timestamptz";
1680
1859
  this.baseDataType = "timestamp";
1681
1860
  }
1682
- toCode(t) {
1683
- return timestampToCode(this, t);
1861
+ toCode(t, m) {
1862
+ return timestampToCode(this, t, m);
1684
1863
  }
1685
1864
  }
1686
1865
  class TimeColumn extends ColumnType {
@@ -1690,12 +1869,13 @@ class TimeColumn extends ColumnType {
1690
1869
  this.operators = Operators.time;
1691
1870
  this.data.dateTimePrecision = dateTimePrecision;
1692
1871
  }
1693
- toCode(t) {
1872
+ toCode(t, m) {
1694
1873
  const { dateTimePrecision } = this.data;
1695
1874
  return columnCode(
1696
1875
  this,
1697
1876
  t,
1698
- `time(${dateTimePrecision || ""})${dateDataToCode(this.data)}`,
1877
+ `time(${dateTimePrecision || ""})${dateDataToCode(this.data, m)}`,
1878
+ m,
1699
1879
  this.data,
1700
1880
  skipDateMethodsFromToCode
1701
1881
  );
@@ -1709,12 +1889,13 @@ class IntervalColumn extends ColumnType {
1709
1889
  this.data.fields = fields;
1710
1890
  this.data.precision = precision;
1711
1891
  }
1712
- toCode(t) {
1892
+ toCode(t, m) {
1713
1893
  const { fields, precision } = this.data;
1714
1894
  return columnCode(
1715
1895
  this,
1716
1896
  t,
1717
1897
  `interval(${[fields && `'${fields}'`, precision && String(precision)].filter((part) => part).join(", ")})`,
1898
+ m,
1718
1899
  this.data,
1719
1900
  skipDateMethodsFromToCode
1720
1901
  );
@@ -1737,9 +1918,9 @@ class EnumColumn extends ColumnType {
1737
1918
  this.dataType = "enum";
1738
1919
  this.inputSchema = this.outputSchema = this.querySchema = schemaType;
1739
1920
  }
1740
- toCode(t, migration) {
1741
- const options = migration ? "" : `, [${this.options.map((option) => `'${option}'`).join(", ")}]`;
1742
- return columnCode(this, t, `enum('${this.enumName}'${options})`);
1921
+ toCode(t, m) {
1922
+ const options = m ? "" : `, [${this.options.map((option) => `'${option}'`).join(", ")}]`;
1923
+ return columnCode(this, t, `enum('${this.enumName}'${options})`, m);
1743
1924
  }
1744
1925
  toSQL() {
1745
1926
  const name = this.enumName;
@@ -1771,15 +1952,16 @@ class ArrayColumn extends ColumnType {
1771
1952
  }
1772
1953
  );
1773
1954
  this.data.item = item;
1955
+ this.data.name = item.data.name;
1774
1956
  }
1775
1957
  toSQL() {
1776
1958
  return `${this.data.item.toSQL()}[]`;
1777
1959
  }
1778
- toCode(t) {
1960
+ toCode(t, m) {
1779
1961
  const code = ["array("];
1780
1962
  addCode(code, this.data.item.toCode(t));
1781
- addCode(code, `)${arrayDataToCode(this.data)}`);
1782
- return columnCode(this, t, code);
1963
+ addCode(code, `)${arrayDataToCode(this.data, m)}`);
1964
+ return columnCode(this, t, code, m);
1783
1965
  }
1784
1966
  }
1785
1967
  const parseArray = (input, pos, len, entries, nested, item) => {
@@ -3195,29 +3377,11 @@ const pushInsertSql = (ctx, q, query, quotedAs) => {
3195
3377
  ""
3196
3378
  )})`
3197
3379
  );
3198
- } else {
3380
+ } else if ("toSQL" in expr) {
3199
3381
  ctx.sql.push(expr.toSQL(ctx, quotedAs));
3382
+ } else {
3383
+ ctx.sql.push(`ON CONSTRAINT "${expr.constraint}"`);
3200
3384
  }
3201
- } else if (type === "merge") {
3202
- const { indexes } = q.internal;
3203
- const quotedUniques = columns.reduce((arr, key, i) => {
3204
- var _a2, _b2;
3205
- const unique = (
3206
- // check column index
3207
- ((_b2 = ((_a2 = shape[key]) == null ? void 0 : _a2.data).indexes) == null ? void 0 : _b2.some(
3208
- (index) => index.unique
3209
- )) || // check table composite indexes
3210
- (indexes == null ? void 0 : indexes.some(
3211
- (index) => index.columns.some(
3212
- (item) => "column" in item && item.column === key
3213
- )
3214
- ))
3215
- );
3216
- if (unique)
3217
- arr.push(quotedColumns[i]);
3218
- return arr;
3219
- }, []);
3220
- ctx.sql.push(`(${quotedUniques.join(", ")})`);
3221
3385
  }
3222
3386
  if (type === "ignore") {
3223
3387
  ctx.sql.push("DO NOTHING");
@@ -3891,10 +4055,27 @@ const extendQuery = (q, methods) => {
3891
4055
  cloned.q = getClonedQueryData(q.q);
3892
4056
  return cloned;
3893
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
+ };
3894
4075
 
3895
4076
  var __defProp$a = Object.defineProperty;
3896
- var __defProps$6 = Object.defineProperties;
3897
- var __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors;
4077
+ var __defProps$4 = Object.defineProperties;
4078
+ var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
3898
4079
  var __getOwnPropSymbols$b = Object.getOwnPropertySymbols;
3899
4080
  var __hasOwnProp$b = Object.prototype.hasOwnProperty;
3900
4081
  var __propIsEnum$b = Object.prototype.propertyIsEnumerable;
@@ -3910,7 +4091,7 @@ var __spreadValues$a = (a, b) => {
3910
4091
  }
3911
4092
  return a;
3912
4093
  };
3913
- var __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b));
4094
+ var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
3914
4095
  function setQueryOperators(query, operators) {
3915
4096
  const q = query.q;
3916
4097
  if (q.operators) {
@@ -3969,7 +4150,7 @@ const base = {
3969
4150
  (key, value, ctx, quotedAs) => `NOT ${key} IN ${quoteValue(value, ctx, quotedAs)}`
3970
4151
  )
3971
4152
  };
3972
- const boolean = __spreadProps$6(__spreadValues$a({}, base), {
4153
+ const boolean = __spreadProps$4(__spreadValues$a({}, base), {
3973
4154
  and: make(
3974
4155
  (key, value, ctx, quotedAs) => `${key} AND ${value.q.expr.toSQL(ctx, quotedAs)}`
3975
4156
  ),
@@ -3977,7 +4158,7 @@ const boolean = __spreadProps$6(__spreadValues$a({}, base), {
3977
4158
  (key, value, ctx, quotedAs) => `(${key}) OR (${value.q.expr.toSQL(ctx, quotedAs)})`
3978
4159
  )
3979
4160
  });
3980
- const numeric = __spreadProps$6(__spreadValues$a({}, base), {
4161
+ const numeric = __spreadProps$4(__spreadValues$a({}, base), {
3981
4162
  lt: make(
3982
4163
  (key, value, ctx, quotedAs) => `${key} < ${quoteValue(value, ctx, quotedAs)}`
3983
4164
  ),
@@ -3998,7 +4179,7 @@ const numeric = __spreadProps$6(__spreadValues$a({}, base), {
3998
4179
  )}`
3999
4180
  )
4000
4181
  });
4001
- const text = __spreadProps$6(__spreadValues$a({}, base), {
4182
+ const text = __spreadProps$4(__spreadValues$a({}, base), {
4002
4183
  contains: make(
4003
4184
  (key, value, ctx, quotedAs) => `${key} ILIKE '%' || ${quoteValue(value, ctx, quotedAs)} || '%'`
4004
4185
  ),
@@ -4018,7 +4199,7 @@ const text = __spreadProps$6(__spreadValues$a({}, base), {
4018
4199
  (key, value, ctx, quotedAs) => `${key} LIKE '%' || ${quoteValue(value, ctx, quotedAs)}`
4019
4200
  )
4020
4201
  });
4021
- const json = __spreadProps$6(__spreadValues$a({}, base), {
4202
+ const json = __spreadProps$4(__spreadValues$a({}, base), {
4022
4203
  jsonPath: make(
4023
4204
  (key, [path, op, value], ctx, quotedAs) => `jsonb_path_query_first(${key}, '${path}') #>> '{}' ${op} ${value === null ? "null" : quoteValue(value, ctx, quotedAs, true)}`
4024
4205
  ),
@@ -4062,16 +4243,18 @@ class DecimalColumn extends ColumnType {
4062
4243
  constructor(schema, numericPrecision, numericScale) {
4063
4244
  super(schema, schema.stringSchema());
4064
4245
  this.operators = Operators.number;
4065
- this.dataType = "decimal";
4246
+ this.dataType = "numeric";
4066
4247
  this.data.numericPrecision = numericPrecision;
4067
4248
  this.data.numericScale = numericScale;
4249
+ this.data.alias = "decimal";
4068
4250
  }
4069
- toCode(t) {
4251
+ toCode(t, m) {
4070
4252
  const { numericPrecision, numericScale } = this.data;
4071
4253
  return columnCode(
4072
4254
  this,
4073
4255
  t,
4074
- `decimal(${numericPrecision || ""}${numericScale ? `, ${numericScale}` : ""})`
4256
+ `decimal(${numericPrecision || ""}${numericScale ? `, ${numericScale}` : ""})`,
4257
+ m
4075
4258
  );
4076
4259
  }
4077
4260
  toSQL() {
@@ -4083,49 +4266,52 @@ class DecimalColumn extends ColumnType {
4083
4266
  }
4084
4267
  }
4085
4268
  const skipNumberMethods = { int: true };
4086
- const intToCode = (column, t) => {
4269
+ const intToCode = (column, t, alias, m) => {
4087
4270
  let code;
4088
4271
  if (column.data.identity) {
4089
- code = identityToCode(column.data.identity, column.dataType);
4272
+ code = identityToCode(column.data.identity, alias);
4090
4273
  } else {
4091
- code = [`${column.dataType}()`];
4274
+ code = [`${alias}()`];
4092
4275
  }
4093
- addCode(code, numberDataToCode(column.data, skipNumberMethods));
4094
- return columnCode(column, t, code);
4276
+ addCode(code, numberDataToCode(column.data, m, skipNumberMethods));
4277
+ return columnCode(column, t, code, m);
4095
4278
  };
4096
4279
  class SmallIntColumn extends IntegerBaseColumn {
4097
- constructor() {
4098
- super(...arguments);
4099
- this.dataType = "smallint";
4280
+ constructor(schema) {
4281
+ super(schema);
4282
+ this.dataType = "int2";
4100
4283
  this.parseItem = parseInt;
4284
+ this.data.alias = "smallint";
4101
4285
  }
4102
- toCode(t) {
4103
- return intToCode(this, t);
4286
+ toCode(t, m) {
4287
+ return intToCode(this, t, "smallint", m);
4104
4288
  }
4105
4289
  identity(options = {}) {
4106
4290
  return setColumnData(this, "identity", options);
4107
4291
  }
4108
4292
  }
4109
4293
  class IntegerColumn extends IntegerBaseColumn {
4110
- constructor() {
4111
- super(...arguments);
4112
- this.dataType = "integer";
4294
+ constructor(schema) {
4295
+ super(schema);
4296
+ this.dataType = "int4";
4113
4297
  this.parseItem = parseInt;
4298
+ this.data.alias = "integer";
4114
4299
  }
4115
- toCode(t) {
4116
- return intToCode(this, t);
4300
+ toCode(t, m) {
4301
+ return intToCode(this, t, "integer", m);
4117
4302
  }
4118
4303
  identity(options = {}) {
4119
4304
  return setColumnData(this, "identity", options);
4120
4305
  }
4121
4306
  }
4122
4307
  class BigIntColumn extends NumberAsStringBaseColumn {
4123
- constructor() {
4124
- super(...arguments);
4125
- this.dataType = "bigint";
4308
+ constructor(schema) {
4309
+ super(schema);
4310
+ this.dataType = "int8";
4311
+ this.data.alias = "bigint";
4126
4312
  }
4127
- toCode(t) {
4128
- return intToCode(this, t);
4313
+ toCode(t, m) {
4314
+ return intToCode(this, t, "bigint", m);
4129
4315
  }
4130
4316
  identity(options = {}) {
4131
4317
  return setColumnData(this, "identity", options);
@@ -4134,74 +4320,81 @@ class BigIntColumn extends NumberAsStringBaseColumn {
4134
4320
  class RealColumn extends NumberBaseColumn {
4135
4321
  constructor(schema) {
4136
4322
  super(schema, schema.number());
4137
- this.dataType = "real";
4323
+ this.dataType = "float4";
4138
4324
  this.parseItem = parseFloat;
4325
+ this.data.alias = "real";
4139
4326
  }
4140
- toCode(t) {
4141
- return columnCode(this, t, `real()${numberDataToCode(this.data)}`);
4327
+ toCode(t, m) {
4328
+ return columnCode(this, t, `real()${numberDataToCode(this.data, m)}`, m);
4142
4329
  }
4143
4330
  }
4144
4331
  class DoublePrecisionColumn extends NumberAsStringBaseColumn {
4145
- constructor() {
4146
- super(...arguments);
4147
- this.dataType = "double precision";
4332
+ constructor(schema) {
4333
+ super(schema);
4334
+ this.dataType = "float8";
4335
+ this.data.alias = "doublePrecision";
4148
4336
  }
4149
- toCode(t) {
4150
- return columnCode(this, t, `doublePrecision()`);
4337
+ toCode(t, m) {
4338
+ return columnCode(this, t, `doublePrecision()`, m);
4151
4339
  }
4152
4340
  }
4153
4341
  class SmallSerialColumn extends IntegerBaseColumn {
4154
4342
  constructor(schema) {
4155
4343
  super(schema);
4156
- this.dataType = "smallint";
4344
+ this.dataType = "int2";
4157
4345
  this.parseItem = parseInt;
4158
4346
  this.data.int = true;
4347
+ this.data.alias = "smallSerial";
4159
4348
  }
4160
4349
  toSQL() {
4161
4350
  return "smallserial";
4162
4351
  }
4163
- toCode(t) {
4352
+ toCode(t, m) {
4164
4353
  return columnCode(
4165
4354
  this,
4166
4355
  t,
4167
- `smallSerial()${numberDataToCode(this.data, skipNumberMethods)}`
4356
+ `smallSerial()${numberDataToCode(this.data, m, skipNumberMethods)}`,
4357
+ m
4168
4358
  );
4169
4359
  }
4170
4360
  }
4171
4361
  class SerialColumn extends IntegerBaseColumn {
4172
4362
  constructor(schema) {
4173
4363
  super(schema);
4174
- this.dataType = "integer";
4364
+ this.dataType = "int4";
4175
4365
  this.parseItem = parseInt;
4176
4366
  this.data.int = true;
4367
+ this.data.alias = "serial";
4177
4368
  }
4178
4369
  toSQL() {
4179
4370
  return "serial";
4180
4371
  }
4181
- toCode(t) {
4372
+ toCode(t, m) {
4182
4373
  return columnCode(
4183
4374
  this,
4184
4375
  t,
4185
- `serial()${numberDataToCode(this.data, skipNumberMethods)}`
4376
+ `serial()${numberDataToCode(this.data, m, skipNumberMethods)}`,
4377
+ m
4186
4378
  );
4187
4379
  }
4188
4380
  }
4189
4381
  class BigSerialColumn extends NumberAsStringBaseColumn {
4190
- constructor() {
4191
- super(...arguments);
4192
- this.dataType = "bigint";
4382
+ constructor(schema) {
4383
+ super(schema);
4384
+ this.dataType = "int8";
4385
+ this.data.alias = "bigint";
4193
4386
  }
4194
4387
  toSQL() {
4195
4388
  return "bigserial";
4196
4389
  }
4197
- toCode(t) {
4198
- return columnCode(this, t, `bigSerial()`);
4390
+ toCode(t, m) {
4391
+ return columnCode(this, t, `bigSerial()`, m);
4199
4392
  }
4200
4393
  }
4201
4394
 
4202
4395
  var __defProp$9 = Object.defineProperty;
4203
- var __defProps$5 = Object.defineProperties;
4204
- var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
4396
+ var __defProps$3 = Object.defineProperties;
4397
+ var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
4205
4398
  var __getOwnPropSymbols$a = Object.getOwnPropertySymbols;
4206
4399
  var __hasOwnProp$a = Object.prototype.hasOwnProperty;
4207
4400
  var __propIsEnum$a = Object.prototype.propertyIsEnumerable;
@@ -4217,7 +4410,7 @@ var __spreadValues$9 = (a, b) => {
4217
4410
  }
4218
4411
  return a;
4219
4412
  };
4220
- var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
4413
+ var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
4221
4414
  class TextBaseColumn extends ColumnType {
4222
4415
  constructor(schema, schemaType = schema.stringSchema()) {
4223
4416
  super(schema, schemaType);
@@ -4244,12 +4437,13 @@ class VarCharColumn extends LimitedTextBaseColumn {
4244
4437
  super(...arguments);
4245
4438
  this.dataType = "varchar";
4246
4439
  }
4247
- toCode(t) {
4440
+ toCode(t, m) {
4248
4441
  const { maxChars } = this.data;
4249
4442
  return columnCode(
4250
4443
  this,
4251
4444
  t,
4252
- `varchar(${maxChars != null ? maxChars : ""})${stringDataToCode(this.data)}`
4445
+ `varchar(${maxChars != null ? maxChars : ""})${stringDataToCode(this.data, m)}`,
4446
+ m
4253
4447
  );
4254
4448
  }
4255
4449
  }
@@ -4257,14 +4451,15 @@ class StringColumn extends VarCharColumn {
4257
4451
  constructor(schema, limit = 255) {
4258
4452
  super(schema, limit);
4259
4453
  }
4260
- toCode(t) {
4454
+ toCode(t, m) {
4261
4455
  let max = this.data.maxChars;
4262
4456
  if (max === 255)
4263
4457
  max = void 0;
4264
4458
  return columnCode(
4265
4459
  this,
4266
4460
  t,
4267
- `string(${max != null ? max : ""})${stringDataToCode(this.data)}`
4461
+ `string(${max != null ? max : ""})${stringDataToCode(this.data, m)}`,
4462
+ m
4268
4463
  );
4269
4464
  }
4270
4465
  }
@@ -4273,12 +4468,13 @@ class CharColumn extends LimitedTextBaseColumn {
4273
4468
  super(...arguments);
4274
4469
  this.dataType = "char";
4275
4470
  }
4276
- toCode(t) {
4471
+ toCode(t, m) {
4277
4472
  const { maxChars } = this.data;
4278
4473
  return columnCode(
4279
4474
  this,
4280
4475
  t,
4281
- `char(${maxChars != null ? maxChars : ""})${stringDataToCode(this.data)}`
4476
+ `char(${maxChars != null ? maxChars : ""})${stringDataToCode(this.data, m)}`,
4477
+ m
4282
4478
  );
4283
4479
  }
4284
4480
  }
@@ -4290,7 +4486,7 @@ const setTextColumnData = (column, minArg, maxArg) => {
4290
4486
  }
4291
4487
  }
4292
4488
  };
4293
- const textColumnToCode = (column, t) => {
4489
+ const textColumnToCode = (column, t, m) => {
4294
4490
  const data = __spreadValues$9({}, column.data);
4295
4491
  let args = "";
4296
4492
  const hasMax = data.maxArg !== void 0 && data.max === data.maxArg;
@@ -4309,7 +4505,8 @@ const textColumnToCode = (column, t) => {
4309
4505
  return columnCode(
4310
4506
  column,
4311
4507
  t,
4312
- `${column.dataType}(${args})${stringDataToCode(data)}`
4508
+ `${column.dataType}(${args})${stringDataToCode(data, m)}`,
4509
+ m
4313
4510
  );
4314
4511
  };
4315
4512
  const minMaxToSchema = (schema, min, max) => min ? max ? schema.stringMinMax(min, max) : schema.stringMin(min) : schema.stringSchema();
@@ -4319,8 +4516,8 @@ class TextColumn extends TextBaseColumn {
4319
4516
  this.dataType = "text";
4320
4517
  setTextColumnData(this, min, max);
4321
4518
  }
4322
- toCode(t) {
4323
- return textColumnToCode(this, t);
4519
+ toCode(t, m) {
4520
+ return textColumnToCode(this, t, m);
4324
4521
  }
4325
4522
  }
4326
4523
  class ByteaColumn extends ColumnType {
@@ -4329,8 +4526,8 @@ class ByteaColumn extends ColumnType {
4329
4526
  this.dataType = "bytea";
4330
4527
  this.operators = Operators.text;
4331
4528
  }
4332
- toCode(t) {
4333
- return columnCode(this, t, `bytea()`);
4529
+ toCode(t, m) {
4530
+ return columnCode(this, t, `bytea()`, m);
4334
4531
  }
4335
4532
  }
4336
4533
  class PointColumn extends ColumnType {
@@ -4339,8 +4536,8 @@ class PointColumn extends ColumnType {
4339
4536
  this.dataType = "point";
4340
4537
  this.operators = Operators.text;
4341
4538
  }
4342
- toCode(t) {
4343
- return columnCode(this, t, `point()`);
4539
+ toCode(t, m) {
4540
+ return columnCode(this, t, `point()`, m);
4344
4541
  }
4345
4542
  }
4346
4543
  class LineColumn extends ColumnType {
@@ -4349,8 +4546,8 @@ class LineColumn extends ColumnType {
4349
4546
  this.dataType = "line";
4350
4547
  this.operators = Operators.text;
4351
4548
  }
4352
- toCode(t) {
4353
- return columnCode(this, t, `line()`);
4549
+ toCode(t, m) {
4550
+ return columnCode(this, t, `line()`, m);
4354
4551
  }
4355
4552
  }
4356
4553
  class LsegColumn extends ColumnType {
@@ -4359,8 +4556,8 @@ class LsegColumn extends ColumnType {
4359
4556
  this.dataType = "lseg";
4360
4557
  this.operators = Operators.text;
4361
4558
  }
4362
- toCode(t) {
4363
- return columnCode(this, t, `lseg()`);
4559
+ toCode(t, m) {
4560
+ return columnCode(this, t, `lseg()`, m);
4364
4561
  }
4365
4562
  }
4366
4563
  class BoxColumn extends ColumnType {
@@ -4369,8 +4566,8 @@ class BoxColumn extends ColumnType {
4369
4566
  this.dataType = "box";
4370
4567
  this.operators = Operators.text;
4371
4568
  }
4372
- toCode(t) {
4373
- return columnCode(this, t, `box()`);
4569
+ toCode(t, m) {
4570
+ return columnCode(this, t, `box()`, m);
4374
4571
  }
4375
4572
  }
4376
4573
  class PathColumn extends ColumnType {
@@ -4379,8 +4576,8 @@ class PathColumn extends ColumnType {
4379
4576
  this.dataType = "path";
4380
4577
  this.operators = Operators.text;
4381
4578
  }
4382
- toCode(t) {
4383
- return columnCode(this, t, `path()`);
4579
+ toCode(t, m) {
4580
+ return columnCode(this, t, `path()`, m);
4384
4581
  }
4385
4582
  }
4386
4583
  class PolygonColumn extends ColumnType {
@@ -4389,8 +4586,8 @@ class PolygonColumn extends ColumnType {
4389
4586
  this.dataType = "polygon";
4390
4587
  this.operators = Operators.text;
4391
4588
  }
4392
- toCode(t) {
4393
- return columnCode(this, t, `polygon()`);
4589
+ toCode(t, m) {
4590
+ return columnCode(this, t, `polygon()`, m);
4394
4591
  }
4395
4592
  }
4396
4593
  class CircleColumn extends ColumnType {
@@ -4399,8 +4596,8 @@ class CircleColumn extends ColumnType {
4399
4596
  this.dataType = "circle";
4400
4597
  this.operators = Operators.text;
4401
4598
  }
4402
- toCode(t) {
4403
- return columnCode(this, t, `circle()`);
4599
+ toCode(t, m) {
4600
+ return columnCode(this, t, `circle()`, m);
4404
4601
  }
4405
4602
  }
4406
4603
  class MoneyColumn extends NumberBaseColumn {
@@ -4416,8 +4613,8 @@ class MoneyColumn extends NumberBaseColumn {
4416
4613
  }
4417
4614
  );
4418
4615
  }
4419
- toCode(t) {
4420
- return columnCode(this, t, `money()`);
4616
+ toCode(t, m) {
4617
+ return columnCode(this, t, `money()`, m);
4421
4618
  }
4422
4619
  }
4423
4620
  class CidrColumn extends ColumnType {
@@ -4426,8 +4623,8 @@ class CidrColumn extends ColumnType {
4426
4623
  this.dataType = "cidr";
4427
4624
  this.operators = Operators.text;
4428
4625
  }
4429
- toCode(t) {
4430
- return columnCode(this, t, `cidr()`);
4626
+ toCode(t, m) {
4627
+ return columnCode(this, t, `cidr()`, m);
4431
4628
  }
4432
4629
  }
4433
4630
  class InetColumn extends ColumnType {
@@ -4436,8 +4633,8 @@ class InetColumn extends ColumnType {
4436
4633
  this.dataType = "inet";
4437
4634
  this.operators = Operators.text;
4438
4635
  }
4439
- toCode(t) {
4440
- return columnCode(this, t, `inet()`);
4636
+ toCode(t, m) {
4637
+ return columnCode(this, t, `inet()`, m);
4441
4638
  }
4442
4639
  }
4443
4640
  class MacAddrColumn extends ColumnType {
@@ -4446,8 +4643,8 @@ class MacAddrColumn extends ColumnType {
4446
4643
  this.dataType = "macaddr";
4447
4644
  this.operators = Operators.text;
4448
4645
  }
4449
- toCode(t) {
4450
- return columnCode(this, t, `macaddr()`);
4646
+ toCode(t, m) {
4647
+ return columnCode(this, t, `macaddr()`, m);
4451
4648
  }
4452
4649
  }
4453
4650
  class MacAddr8Column extends ColumnType {
@@ -4456,8 +4653,8 @@ class MacAddr8Column extends ColumnType {
4456
4653
  this.dataType = "macaddr8";
4457
4654
  this.operators = Operators.text;
4458
4655
  }
4459
- toCode(t) {
4460
- return columnCode(this, t, `macaddr8()`);
4656
+ toCode(t, m) {
4657
+ return columnCode(this, t, `macaddr8()`, m);
4461
4658
  }
4462
4659
  }
4463
4660
  class BitColumn extends ColumnType {
@@ -4467,9 +4664,9 @@ class BitColumn extends ColumnType {
4467
4664
  this.operators = Operators.text;
4468
4665
  this.data.length = length;
4469
4666
  }
4470
- toCode(t) {
4667
+ toCode(t, m) {
4471
4668
  const { length } = this.data;
4472
- return columnCode(this, t, `bit(${length})`);
4669
+ return columnCode(this, t, `bit(${length})`, m);
4473
4670
  }
4474
4671
  toSQL() {
4475
4672
  return joinTruthy(
@@ -4481,13 +4678,14 @@ class BitColumn extends ColumnType {
4481
4678
  class BitVaryingColumn extends ColumnType {
4482
4679
  constructor(schema, length) {
4483
4680
  super(schema, schema.bit(length));
4484
- this.dataType = "bit varying";
4681
+ this.dataType = "varbit";
4485
4682
  this.operators = Operators.text;
4486
4683
  this.data.length = length;
4684
+ this.data.alias = "bitVarying";
4487
4685
  }
4488
- toCode(t) {
4686
+ toCode(t, m) {
4489
4687
  const { length } = this.data;
4490
- return columnCode(this, t, `bitVarying(${length != null ? length : ""})`);
4688
+ return columnCode(this, t, `bitVarying(${length != null ? length : ""})`, m);
4491
4689
  }
4492
4690
  toSQL() {
4493
4691
  return joinTruthy(
@@ -4503,8 +4701,8 @@ class TsVectorColumn extends ColumnType {
4503
4701
  this.dataType = "tsvector";
4504
4702
  this.operators = Operators.text;
4505
4703
  }
4506
- toCode(t) {
4507
- return columnCode(this, t, `tsvector()`);
4704
+ toCode(t, m) {
4705
+ return columnCode(this, t, `tsvector()`, m);
4508
4706
  }
4509
4707
  /**
4510
4708
  * For `tsvector` column type, it can also accept language (optional) and columns:
@@ -4534,14 +4732,17 @@ class TsVectorColumn extends ColumnType {
4534
4732
  const first = args[0];
4535
4733
  if (typeof first === "string" || !("raw" in first)) {
4536
4734
  const target = typeof first === "string" ? args[1] : first;
4735
+ const language = typeof first === "string" ? first : this.defaultLanguage;
4537
4736
  let sql;
4538
4737
  if (Array.isArray(target)) {
4539
4738
  const columns = target.length === 1 ? `"${target[0]}"` : target.map((column) => `coalesce("${column}", '')`).join(` || ' ' || `);
4540
- sql = `to_tsvector('${typeof first === "string" ? first : this.defaultLanguage}', ${columns})`;
4739
+ sql = `to_tsvector('${language}', ${columns})`;
4541
4740
  } else {
4542
4741
  for (const key in target) {
4543
- sql = (sql ? sql + " || " : "") + `setweight(to_tsvector(coalesce("${key}", '')), '${target[key]}')`;
4742
+ sql = (sql ? sql + " || " : "(") + `setweight(to_tsvector('${language}', coalesce("${key}", '')), '${target[key]}')`;
4544
4743
  }
4744
+ if (sql)
4745
+ sql += ")";
4545
4746
  }
4546
4747
  const arr = [sql];
4547
4748
  arr.raw = arr;
@@ -4556,8 +4757,8 @@ class TsQueryColumn extends ColumnType {
4556
4757
  this.dataType = "tsquery";
4557
4758
  this.operators = Operators.text;
4558
4759
  }
4559
- toCode(t) {
4560
- return columnCode(this, t, `tsquery()`);
4760
+ toCode(t, m) {
4761
+ return columnCode(this, t, `tsquery()`, m);
4561
4762
  }
4562
4763
  }
4563
4764
  const uuidDefaultSQL = "gen_random_uuid()";
@@ -4568,20 +4769,24 @@ class UUIDColumn extends ColumnType {
4568
4769
  this.dataType = "uuid";
4569
4770
  this.operators = Operators.text;
4570
4771
  }
4571
- primaryKey() {
4572
- const column = super.primaryKey();
4772
+ /**
4773
+ * see {@link ColumnType.primaryKey}
4774
+ */
4775
+ primaryKey(name) {
4776
+ const column = super.primaryKey(name);
4573
4777
  if (!column.data.default)
4574
4778
  column.data.default = uuidDefault;
4575
4779
  return column;
4576
4780
  }
4577
- toCode(t) {
4781
+ toCode(t, m) {
4578
4782
  const { data } = this;
4579
4783
  return columnCode(
4580
4784
  this,
4581
4785
  t,
4582
4786
  `uuid()`,
4787
+ m,
4583
4788
  // don't output the default default
4584
- 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
4585
4790
  );
4586
4791
  }
4587
4792
  }
@@ -4591,8 +4796,8 @@ class XMLColumn extends ColumnType {
4591
4796
  this.dataType = "xml";
4592
4797
  this.operators = Operators.text;
4593
4798
  }
4594
- toCode(t) {
4595
- return columnCode(this, t, `xml()`);
4799
+ toCode(t, m) {
4800
+ return columnCode(this, t, `xml()`, m);
4596
4801
  }
4597
4802
  }
4598
4803
  class CitextColumn extends TextBaseColumn {
@@ -4601,20 +4806,21 @@ class CitextColumn extends TextBaseColumn {
4601
4806
  this.dataType = "citext";
4602
4807
  setTextColumnData(this, min, max);
4603
4808
  }
4604
- toCode(t) {
4605
- return textColumnToCode(this, t);
4809
+ toCode(t, m) {
4810
+ return textColumnToCode(this, t, m);
4606
4811
  }
4607
4812
  }
4608
4813
 
4609
4814
  class BooleanColumn extends ColumnType {
4610
4815
  constructor(schema) {
4611
4816
  super(schema, schema.boolean());
4612
- this.dataType = "boolean";
4817
+ this.dataType = "bool";
4613
4818
  this.operators = Operators.boolean;
4614
4819
  this.parseItem = (input) => input[0] === "t";
4820
+ this.data.alias = "boolean";
4615
4821
  }
4616
- toCode(t) {
4617
- return columnCode(this, t, "boolean()");
4822
+ toCode(t, m) {
4823
+ return columnCode(this, t, "boolean()", m);
4618
4824
  }
4619
4825
  }
4620
4826
 
@@ -4630,8 +4836,8 @@ class CustomTypeColumn extends ColumnType {
4630
4836
  this.operators = Operators.any;
4631
4837
  this.data.isOfCustomType = true;
4632
4838
  }
4633
- toCode(t) {
4634
- return columnCode(this, t, `type(${singleQuote(this.dataType)})`);
4839
+ toCode(t, m) {
4840
+ return columnCode(this, t, `type(${singleQuote(this.dataType)})`, m);
4635
4841
  }
4636
4842
  as(column) {
4637
4843
  const c = setColumnData(
@@ -4646,14 +4852,12 @@ class CustomTypeColumn extends ColumnType {
4646
4852
  }
4647
4853
  }
4648
4854
  class DomainColumn extends CustomTypeColumn {
4649
- toCode(t) {
4650
- return columnCode(this, t, `domain(${singleQuote(this.dataType)})`);
4855
+ toCode(t, m) {
4856
+ return columnCode(this, t, `domain(${singleQuote(this.dataType)})`, m);
4651
4857
  }
4652
4858
  }
4653
4859
 
4654
4860
  var __defProp$8 = Object.defineProperty;
4655
- var __defProps$4 = Object.defineProperties;
4656
- var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
4657
4861
  var __getOwnPropSymbols$9 = Object.getOwnPropertySymbols;
4658
4862
  var __hasOwnProp$9 = Object.prototype.hasOwnProperty;
4659
4863
  var __propIsEnum$9 = Object.prototype.propertyIsEnumerable;
@@ -4669,19 +4873,11 @@ var __spreadValues$8 = (a, b) => {
4669
4873
  }
4670
4874
  return a;
4671
4875
  };
4672
- var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
4673
- const newTableData = () => ({});
4674
- let tableData = newTableData();
4675
- const getTableData = () => tableData;
4676
- const resetTableData = (data = newTableData()) => {
4677
- tableData = data;
4678
- };
4679
- const getColumnTypes = (types, fn, nowSQL, language, data = newTableData()) => {
4876
+ const getColumnTypes = (types, fn, nowSQL, language) => {
4680
4877
  if (nowSQL)
4681
4878
  setDefaultNowFn(nowSQL);
4682
4879
  if (language)
4683
4880
  setDefaultLanguage(language);
4684
- resetTableData(data);
4685
4881
  return fn(types);
4686
4882
  };
4687
4883
  const makeColumnTypes = (schema) => {
@@ -4693,20 +4889,7 @@ const makeColumnTypes = (schema) => {
4693
4889
  setCurrentColumnName(name);
4694
4890
  return this;
4695
4891
  },
4696
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
4697
- sql(...args) {
4698
- const arg = args[0];
4699
- if (Array.isArray(arg)) {
4700
- return new RawSQL(args);
4701
- }
4702
- if (typeof args[0] === "string") {
4703
- return new RawSQL(args[0]);
4704
- }
4705
- if (args[1] !== void 0) {
4706
- return new RawSQL(args[1], arg);
4707
- }
4708
- return (...args2) => new RawSQL(args2, arg);
4709
- },
4892
+ sql: sqlFn,
4710
4893
  smallint: schema.smallint,
4711
4894
  integer: schema.integer,
4712
4895
  bigint: schema.bigint,
@@ -4803,66 +4986,6 @@ const makeColumnTypes = (schema) => {
4803
4986
  },
4804
4987
  domain(dataType) {
4805
4988
  return new DomainColumn(schema, dataType);
4806
- },
4807
- primaryKey(columns, options) {
4808
- tableData.primaryKey = { columns, options };
4809
- return emptyObject;
4810
- },
4811
- index(columns, options = {}) {
4812
- var _a;
4813
- const index = {
4814
- columns: toArray(columns).map(
4815
- (column) => typeof column === "string" ? { column } : column
4816
- ),
4817
- options
4818
- };
4819
- ((_a = tableData.indexes) != null ? _a : tableData.indexes = []).push(index);
4820
- return emptyObject;
4821
- },
4822
- unique(columns, options) {
4823
- return this.index(columns, __spreadProps$4(__spreadValues$8({}, options), { unique: true }));
4824
- },
4825
- /**
4826
- * See {@link ColumnType.searchIndex}
4827
- */
4828
- searchIndex(columns, options) {
4829
- return this.index(columns, __spreadProps$4(__spreadValues$8({}, options), { tsVector: true }));
4830
- },
4831
- constraint({ name, references, check, dropMode }) {
4832
- var _a;
4833
- ((_a = tableData.constraints) != null ? _a : tableData.constraints = []).push({
4834
- name,
4835
- references: references ? {
4836
- columns: references[0],
4837
- fnOrTable: references[1],
4838
- foreignColumns: references[2],
4839
- options: references[3]
4840
- } : void 0,
4841
- check,
4842
- dropMode
4843
- });
4844
- return emptyObject;
4845
- },
4846
- foreignKey(columns, fnOrTable, foreignColumns, options) {
4847
- var _a;
4848
- ((_a = tableData.constraints) != null ? _a : tableData.constraints = []).push({
4849
- name: options == null ? void 0 : options.name,
4850
- references: {
4851
- columns,
4852
- fnOrTable,
4853
- foreignColumns,
4854
- options
4855
- },
4856
- dropMode: options == null ? void 0 : options.dropMode
4857
- });
4858
- return emptyObject;
4859
- },
4860
- check(check) {
4861
- var _a;
4862
- ((_a = tableData.constraints) != null ? _a : tableData.constraints = []).push({
4863
- check
4864
- });
4865
- return emptyObject;
4866
4989
  }
4867
4990
  }, makeTimestampsHelpers(makeRegexToFindInSql));
4868
4991
  };
@@ -4980,6 +5103,8 @@ for (const key in types.builtins) {
4980
5103
  delete defaultTypeParsers[id];
4981
5104
  });
4982
5105
  const returnArg = (arg) => arg;
5106
+ const rollbackSql$1 = { text: "ROLLBACK" };
5107
+ const commitSql$1 = { text: "COMMIT" };
4983
5108
  class Adapter {
4984
5109
  constructor(_a) {
4985
5110
  var _b = _a, { types: types2 = defaultTypeParsers } = _b, config = __objRest$1(_b, ["types"]);
@@ -5021,7 +5146,7 @@ class Adapter {
5021
5146
  arrays(query, types2) {
5022
5147
  return performQuery$1(this, query, types2, "array");
5023
5148
  }
5024
- async transaction(begin, cb) {
5149
+ async transaction(begin, cb, end = commitSql$1) {
5025
5150
  const client = await this.connect();
5026
5151
  try {
5027
5152
  await setSearchPath(client, this.schema);
@@ -5030,10 +5155,10 @@ class Adapter {
5030
5155
  try {
5031
5156
  result = await cb(new TransactionAdapter(this, client, this.types));
5032
5157
  } catch (err) {
5033
- await performQueryOnClient(client, { text: "ROLLBACK" }, this.types);
5158
+ await performQueryOnClient(client, rollbackSql$1, this.types);
5034
5159
  throw err;
5035
5160
  }
5036
- await performQueryOnClient(client, { text: "COMMIT" }, this.types);
5161
+ await performQueryOnClient(client, end, this.types);
5037
5162
  return result;
5038
5163
  } finally {
5039
5164
  client.release();
@@ -5107,8 +5232,8 @@ class TransactionAdapter {
5107
5232
  }
5108
5233
 
5109
5234
  var __defProp$7 = Object.defineProperty;
5110
- var __defProps$3 = Object.defineProperties;
5111
- var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
5235
+ var __defProps$2 = Object.defineProperties;
5236
+ var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
5112
5237
  var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
5113
5238
  var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
5114
5239
  var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
@@ -5124,7 +5249,7 @@ var __spreadValues$7 = (a, b) => {
5124
5249
  }
5125
5250
  return a;
5126
5251
  };
5127
- var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
5252
+ var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
5128
5253
  class FnExpression extends Expression {
5129
5254
  /**
5130
5255
  * @param q - query object.
@@ -5181,7 +5306,7 @@ class FnExpression extends Expression {
5181
5306
  sql.push(" ");
5182
5307
  if (options.order) {
5183
5308
  pushOrderBySql(
5184
- __spreadProps$3(__spreadValues$7({}, ctx), { sql }),
5309
+ __spreadProps$2(__spreadValues$7({}, ctx), { sql }),
5185
5310
  this.q.q,
5186
5311
  quotedAs,
5187
5312
  toArray(options.order)
@@ -6112,9 +6237,9 @@ class Create {
6112
6237
  * password: '1234',
6113
6238
  * });
6114
6239
  *
6115
- * // When using `.onConflict().ignore()`,
6240
+ * // When using `.onConflictIgnore()`,
6116
6241
  * // the record may be not created and the `createdCount` will be 0.
6117
- * const createdCount = await db.table.insert(data).onConflict().ignore();
6242
+ * const createdCount = await db.table.insert(data).onConflictIgnore();
6118
6243
  *
6119
6244
  * await db.table.create({
6120
6245
  * // raw SQL
@@ -6328,32 +6453,44 @@ class Create {
6328
6453
  return _queryDefaults(this.clone(), data);
6329
6454
  }
6330
6455
  /**
6331
- * A modifier for creating queries that specify alternative behavior in the case of a conflict.
6332
- * A conflict occurs when a table has a `PRIMARY KEY` or a `UNIQUE` index on a column
6333
- * (or a composite index on a set of columns) and a row being created has the same value as a row
6334
- * that already exists in the table in this column(s).
6335
- * 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.
6336
6465
  *
6337
- * Use `onConflict` to either ignore the error by using `.onConflict().ignore()`,
6338
- * or to update the existing row with new data (perform an "UPSERT") by using `.onConflict().merge()`.
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.
6468
+ *
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.
6339
6474
  *
6340
6475
  * ```ts
6341
6476
  * // leave `onConflict` without argument to ignore or merge on any conflict
6342
- * db.table.create(data).onConflict().ignore();
6477
+ * db.table.create(data).onConflictIgnore();
6343
6478
  *
6344
6479
  * // single column:
6345
- * db.table.create(data).onConfict('email');
6480
+ * db.table.create(data).onConfict('email').merge();
6346
6481
  *
6347
6482
  * // array of columns:
6348
- * db.table.create(data).onConfict(['email', 'name']);
6483
+ * db.table.create(data).onConfict(['email', 'name']).merge();
6349
6484
  *
6350
- * // raw expression:
6351
- * db.table.create(data).onConfict(db.table.sql`(email) where condition`);
6352
- * ```
6485
+ * // constraint name
6486
+ * db.table.create(data).onConfict({ constraint: 'unique_index_name' }).merge();
6353
6487
  *
6354
- * ::: info
6355
- * 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.
6356
- * 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
+ * ```
6357
6494
  *
6358
6495
  * You can use the db.table.sql function in onConflict.
6359
6496
  * It can be useful to specify a condition when you have a partial index:
@@ -6370,29 +6507,17 @@ class Create {
6370
6507
  * .ignore();
6371
6508
  * ```
6372
6509
  *
6373
- * :::
6374
- *
6375
- * See the documentation on the .ignore() and .merge() methods for more details.
6376
- *
6377
6510
  * @param arg - optionally provide an array of columns
6378
6511
  */
6379
6512
  onConflict(arg) {
6380
6513
  return new OnConflictQueryBuilder(this, arg);
6381
6514
  }
6382
- }
6383
- class OnConflictQueryBuilder {
6384
- constructor(query, onConflict) {
6385
- this.query = query;
6386
- this.onConflict = onConflict;
6387
- }
6388
6515
  /**
6389
- * Available only after `onConflict`.
6390
- *
6391
- * `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.
6392
6517
  *
6393
- * 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.
6394
6519
  *
6395
- * It produces `ON CONFLICT DO NOTHING` when no `onConflict` argument provided.
6520
+ * Can also accept a constraint name.
6396
6521
  *
6397
6522
  * ```ts
6398
6523
  * db.table
@@ -6400,40 +6525,39 @@ class OnConflictQueryBuilder {
6400
6525
  * email: 'ignore@example.com',
6401
6526
  * name: 'John Doe',
6402
6527
  * })
6403
- * .onConflict('email')
6404
- * .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' });
6405
6534
  * ```
6406
6535
  *
6407
- *
6408
- * 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.
6409
- *
6410
- * `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.
6411
6537
  *
6412
6538
  * ```ts
6413
6539
  * const maybeRecord: RecordType | undefined = await db.table
6414
6540
  * .create(data)
6415
- * .onConflict()
6416
- * .ignore();
6541
+ * .onConflictIgnore();
6417
6542
  *
6418
6543
  * const maybeId: number | undefined = await db.table
6419
6544
  * .get('id')
6420
6545
  * .create(data)
6421
- * .onConflict()
6422
- * .ignore();
6546
+ * .onConflictIgnore();
6423
6547
  * ```
6424
6548
  *
6425
- * 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:
6426
6550
  *
6427
6551
  * ```ts
6428
6552
  * // array can be empty
6429
- * const arr = await db.table.createMany([data, data, data]).onConflict().ignore();
6553
+ * const arr = await db.table.createMany([data, data, data]).onConflictIgnore();
6430
6554
  * ```
6431
6555
  */
6432
- ignore() {
6433
- const q = this.query;
6556
+ onConflictIgnore(arg) {
6557
+ const q = this.clone();
6434
6558
  q.q.onConflict = {
6435
6559
  type: "ignore",
6436
- expr: this.onConflict
6560
+ expr: arg
6437
6561
  };
6438
6562
  if (q.q.returnType === "oneOrThrow") {
6439
6563
  q.q.returnType = "one";
@@ -6442,23 +6566,27 @@ class OnConflictQueryBuilder {
6442
6566
  }
6443
6567
  return q;
6444
6568
  }
6569
+ }
6570
+ class OnConflictQueryBuilder {
6571
+ constructor(query, onConflict) {
6572
+ this.query = query;
6573
+ this.onConflict = onConflict;
6574
+ }
6445
6575
  /**
6446
- * Available only after `onConflict`.
6447
- *
6448
- * Modifies a create query, to turn it into an 'upsert' operation.
6576
+ * Available only after [onConflict](#onconflict).
6449
6577
  *
6450
6578
  * Adds an `ON CONFLICT (columns) DO UPDATE` clause to the insert statement.
6451
6579
  *
6452
- * When no `onConflict` argument provided,
6453
- * it will automatically collect all table columns that have unique index and use them as a conflict target.
6454
- *
6455
6580
  * ```ts
6456
6581
  * db.table
6457
6582
  * .create({
6458
6583
  * email: 'ignore@example.com',
6459
6584
  * name: 'John Doe',
6460
6585
  * })
6586
+ * // for a specific column:
6461
6587
  * .onConflict('email')
6588
+ * // or, for a specific constraint:
6589
+ * .onConflict({ constraint: 'unique_constraint_name' })
6462
6590
  * .merge();
6463
6591
  * ```
6464
6592
  *
@@ -6489,15 +6617,15 @@ class OnConflictQueryBuilder {
6489
6617
  * updatedAt: timestamp,
6490
6618
  * })
6491
6619
  * .onConflict('email')
6492
- * // string argument for a single column:
6620
+ * // update only a single column
6493
6621
  * .merge('email')
6494
- * // array of strings for multiple columns:
6622
+ * // or, update multiple columns
6495
6623
  * .merge(['email', 'name', 'updatedAt']);
6496
6624
  * ```
6497
6625
  *
6498
- * 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.
6499
6627
  * This is useful if you want to make an update with different data than in creating.
6500
- * 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:
6501
6629
  *
6502
6630
  * ```ts
6503
6631
  * const timestamp = Date.now();
@@ -6515,7 +6643,7 @@ class OnConflictQueryBuilder {
6515
6643
  * });
6516
6644
  * ```
6517
6645
  *
6518
- * 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:
6519
6647
  *
6520
6648
  * ```ts
6521
6649
  * const timestamp = Date.now();
@@ -6535,7 +6663,7 @@ class OnConflictQueryBuilder {
6535
6663
  * .where({ updatedAt: { lt: timestamp } });
6536
6664
  * ```
6537
6665
  *
6538
- * `merge` also accepts raw expression:
6666
+ * `merge` can take a raw SQL expression:
6539
6667
  *
6540
6668
  * ```ts
6541
6669
  * db.table
@@ -7771,10 +7899,7 @@ class JsonModifiers {
7771
7899
  options
7772
7900
  ]
7773
7901
  };
7774
- return Object.assign(
7775
- pushQueryValue(q, "select", json),
7776
- json
7777
- );
7902
+ return Object.assign(pushQueryValue(q, "select", json), json);
7778
7903
  }
7779
7904
  /**
7780
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.
@@ -7822,10 +7947,7 @@ class JsonModifiers {
7822
7947
  options
7823
7948
  ]
7824
7949
  };
7825
- return Object.assign(
7826
- pushQueryValue(q, "select", json),
7827
- json
7828
- );
7950
+ return Object.assign(pushQueryValue(q, "select", json), json);
7829
7951
  }
7830
7952
  /**
7831
7953
  * Return a JSON value/object/array where a given value is removed at the given JSON path.
@@ -7864,10 +7986,7 @@ class JsonModifiers {
7864
7986
  path
7865
7987
  ]
7866
7988
  };
7867
- return Object.assign(
7868
- pushQueryValue(q, "select", json),
7869
- json
7870
- );
7989
+ return Object.assign(pushQueryValue(q, "select", json), json);
7871
7990
  }
7872
7991
  /**
7873
7992
  * Selects a value from JSON data using a JSON path.
@@ -7913,10 +8032,7 @@ class JsonModifiers {
7913
8032
  const json = {
7914
8033
  __json: ["pathQuery", as, type, column, path, options]
7915
8034
  };
7916
- return Object.assign(
7917
- pushQueryValue(q, "select", json),
7918
- json
7919
- );
8035
+ return Object.assign(pushQueryValue(q, "select", json), json);
7920
8036
  }
7921
8037
  }
7922
8038
  class JsonMethods {
@@ -7933,10 +8049,7 @@ class JsonMethods {
7933
8049
  * @param coalesce
7934
8050
  */
7935
8051
  json(coalesce) {
7936
- return queryJson(
7937
- this.clone(),
7938
- coalesce
7939
- );
8052
+ return queryJson(this.clone(), coalesce);
7940
8053
  }
7941
8054
  }
7942
8055
 
@@ -7951,7 +8064,7 @@ const makeMessage = (colors, timeColor, time, sqlColor, sql, valuesColor, values
7951
8064
  const elapsed = process.hrtime(time);
7952
8065
  const formattedTime = `(${elapsed[0] ? `${elapsed[0]}s ` : ""}${(elapsed[1] / 1e6).toFixed(1)}ms)`;
7953
8066
  const result = `${colors ? timeColor(formattedTime) : formattedTime} ${colors ? sqlColor(sql) : sql}`;
7954
- if (!values.length) {
8067
+ if (!(values == null ? void 0 : values.length)) {
7955
8068
  return result;
7956
8069
  }
7957
8070
  const formattedValues = `[${values.map(quote).join(", ")}]`;
@@ -8063,8 +8176,8 @@ class MergeQueryMethods {
8063
8176
  }
8064
8177
 
8065
8178
  var __defProp$4 = Object.defineProperty;
8066
- var __defProps$2 = Object.defineProperties;
8067
- var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
8179
+ var __defProps$1 = Object.defineProperties;
8180
+ var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
8068
8181
  var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
8069
8182
  var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
8070
8183
  var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
@@ -8080,7 +8193,7 @@ var __spreadValues$4 = (a, b) => {
8080
8193
  }
8081
8194
  return a;
8082
8195
  };
8083
- var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
8196
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
8084
8197
  class With {
8085
8198
  /**
8086
8199
  * Add Common Table Expression (CTE) to the query.
@@ -8155,7 +8268,7 @@ class With {
8155
8268
  const query = typeof last === "function" ? last(q.queryBuilder) : last;
8156
8269
  const shape = args.length === 4 ? args[2] : isExpression(query) ? args[1] : query.q.shape;
8157
8270
  if ((options == null ? void 0 : options.columns) === true) {
8158
- options = __spreadProps$2(__spreadValues$4({}, options), {
8271
+ options = __spreadProps$1(__spreadValues$4({}, options), {
8159
8272
  columns: Object.keys(shape)
8160
8273
  });
8161
8274
  }
@@ -9097,9 +9210,9 @@ const _queryUpdate = (query, arg) => {
9097
9210
  if (queries) {
9098
9211
  q.patchResult = async (_, queryResult) => {
9099
9212
  await Promise.all(queries.map(callWithThis, queryResult));
9100
- if (ctx.updateData) {
9213
+ if (ctx.collect) {
9101
9214
  const t = query.baseQuery.clone();
9102
- const keys = query.primaryKeys;
9215
+ const { keys } = ctx.collect;
9103
9216
  _queryWhereIn(
9104
9217
  t,
9105
9218
  keys,
@@ -9107,10 +9220,10 @@ const _queryUpdate = (query, arg) => {
9107
9220
  );
9108
9221
  _queryUpdate(
9109
9222
  t,
9110
- ctx.updateData
9223
+ ctx.collect.data
9111
9224
  );
9112
9225
  for (const row of queryResult.rows) {
9113
- Object.assign(row, ctx.updateData);
9226
+ Object.assign(row, ctx.collect.data);
9114
9227
  }
9115
9228
  }
9116
9229
  };
@@ -9543,8 +9656,8 @@ class Transaction {
9543
9656
  }
9544
9657
 
9545
9658
  var __defProp$2 = Object.defineProperty;
9546
- var __defProps$1 = Object.defineProperties;
9547
- var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
9659
+ var __defProps = Object.defineProperties;
9660
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
9548
9661
  var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
9549
9662
  var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
9550
9663
  var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
@@ -9560,7 +9673,7 @@ var __spreadValues$2 = (a, b) => {
9560
9673
  }
9561
9674
  return a;
9562
9675
  };
9563
- var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
9676
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
9564
9677
  class Headline extends Expression {
9565
9678
  constructor(q, source, params) {
9566
9679
  super();
@@ -9782,7 +9895,7 @@ class SearchMethods {
9782
9895
  const q = this.clone();
9783
9896
  if (!arg.as) {
9784
9897
  const as = saveSearchAlias(q, "@q", "joinedShapes");
9785
- arg = __spreadProps$1(__spreadValues$2({}, arg), {
9898
+ arg = __spreadProps(__spreadValues$2({}, arg), {
9786
9899
  as
9787
9900
  });
9788
9901
  }
@@ -10371,20 +10484,11 @@ class QueryMethods {
10371
10484
  );
10372
10485
  }
10373
10486
  /**
10374
- * The `find` method is available only for tables which has exactly one primary key.
10375
- * And also it can accept raw SQL template literal, then the primary key is not required.
10376
- *
10377
- * 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.
10378
10489
  *
10379
10490
  * ```ts
10380
- * await db.table.find(1);
10381
- * ```
10382
- *
10383
- * ```ts
10384
- * await db.user.find`
10385
- * age = ${age} AND
10386
- * name = ${name}
10387
- * `;
10491
+ * const result: TableType = await db.table.find(1);
10388
10492
  * ```
10389
10493
  *
10390
10494
  * @param value - primary key value to find by
@@ -10400,7 +10504,7 @@ class QueryMethods {
10400
10504
  return _queryTake(
10401
10505
  _queryWhere(q, [
10402
10506
  {
10403
- [q.singlePrimaryKey]: value
10507
+ [q.internal.singlePrimaryKey]: value
10404
10508
  }
10405
10509
  ])
10406
10510
  );
@@ -10422,8 +10526,8 @@ class QueryMethods {
10422
10526
  return _queryTake(_queryWhereSql(q, args));
10423
10527
  }
10424
10528
  /**
10425
- * Find a single record by the primary key (id), adds `LIMIT 1`.
10426
- * 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.
10427
10531
  *
10428
10532
  * ```ts
10429
10533
  * const result: TableType | undefined = await db.table.find(123);
@@ -10453,40 +10557,40 @@ class QueryMethods {
10453
10557
  );
10454
10558
  }
10455
10559
  /**
10456
- * The same as `where(conditions).take()`, takes the same arguments as {@link Where.where}, it will filter records and add a `LIMIT 1`.
10457
- * 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.
10458
10565
  *
10459
10566
  * ```ts
10460
- * const result: TableType = await db.table.findBy({ key: 'value' });
10461
- * // is equivalent to:
10462
- * db.table.where({ key: 'value' }).take()
10567
+ * await db.table.findBy({ key: 'value' });
10463
10568
  * ```
10464
10569
  *
10465
- * @param args - `where` conditions
10570
+ * @param uniqueColumnValues - is derived from primary keys and unique indexes in the table
10466
10571
  */
10467
- findBy(...args) {
10468
- return _queryFindBy(
10469
- this.clone(),
10470
- args
10471
- );
10572
+ findBy(uniqueColumnValues) {
10573
+ return _queryFindBy(this.clone(), [
10574
+ uniqueColumnValues
10575
+ ]);
10472
10576
  }
10473
10577
  /**
10474
- * The same as `where(conditions).takeOptional()`, it will filter records and add a `LIMIT 1`.
10475
- * 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.
10476
10583
  *
10477
10584
  * ```ts
10478
- * const result: TableType | undefined = await db.table.findByOptional({
10479
- * key: 'value',
10480
- * });
10585
+ * await db.table.findByOptional({ key: 'value' });
10481
10586
  * ```
10482
10587
  *
10483
- * @param args - `where` conditions
10588
+ * @param uniqueColumnValues - is derived from primary keys and unique indexes in the table
10484
10589
  */
10485
- findByOptional(...args) {
10486
- return _queryFindByOptional(
10487
- this.clone(),
10488
- args
10489
- );
10590
+ findByOptional(uniqueColumnValues) {
10591
+ return _queryFindByOptional(this.clone(), [
10592
+ uniqueColumnValues
10593
+ ]);
10490
10594
  }
10491
10595
  /**
10492
10596
  * Specifies the schema to be used as a prefix of a table name.
@@ -10632,9 +10736,9 @@ class QueryMethods {
10632
10736
  * Order by raw SQL expression.
10633
10737
  *
10634
10738
  * ```ts
10635
- * db.table.order`raw sql`;
10739
+ * db.table.orderSql`raw sql`;
10636
10740
  * // or
10637
- * db.table.order(db.table.sql`raw sql`);
10741
+ * db.table.orderSql(db.table.sql`raw sql`);
10638
10742
  * ```
10639
10743
  *
10640
10744
  * @param args - SQL expression
@@ -10876,9 +10980,86 @@ applyMixins(QueryMethods, [
10876
10980
  SoftDeleteMethods
10877
10981
  ]);
10878
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
+
10879
11062
  var __defProp = Object.defineProperty;
10880
- var __defProps = Object.defineProperties;
10881
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
10882
11063
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
10883
11064
  var __hasOwnProp = Object.prototype.hasOwnProperty;
10884
11065
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
@@ -10894,7 +11075,6 @@ var __spreadValues = (a, b) => {
10894
11075
  }
10895
11076
  return a;
10896
11077
  };
10897
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
10898
11078
  var __objRest = (source, exclude) => {
10899
11079
  var target = {};
10900
11080
  for (var prop in source)
@@ -10909,22 +11089,24 @@ var __objRest = (source, exclude) => {
10909
11089
  };
10910
11090
  const anyShape = {};
10911
11091
  class Db {
10912
- constructor(adapter, queryBuilder, table = void 0, shape = anyShape, columnTypes, transactionStorage, options) {
11092
+ constructor(adapter, queryBuilder, table = void 0, shape = anyShape, columnTypes, transactionStorage, options, tableData = emptyObject) {
10913
11093
  this.adapter = adapter;
10914
11094
  this.queryBuilder = queryBuilder;
10915
11095
  this.table = table;
10916
11096
  this.shape = shape;
10917
11097
  this.columnTypes = columnTypes;
10918
- var _a, _b;
11098
+ var _a;
10919
11099
  const self = this;
10920
11100
  const { softDelete } = options;
10921
11101
  const scopes = options.scopes || softDelete ? {} : emptyObject;
10922
- const tableData = getTableData();
10923
- this.internal = __spreadProps(__spreadValues({}, tableData), {
11102
+ this.internal = {
10924
11103
  transactionStorage,
10925
11104
  scopes,
10926
- snakeCase: options.snakeCase
10927
- });
11105
+ snakeCase: options.snakeCase,
11106
+ noPrimaryKey: options.noPrimaryKey === "ignore",
11107
+ comment: options.comment,
11108
+ tableData
11109
+ };
10928
11110
  this.baseQuery = this;
10929
11111
  const logger = options.logger || console;
10930
11112
  const parsers = {};
@@ -10985,20 +11167,21 @@ class Db {
10985
11167
  log: logParamToLogObject(logger, options.log),
10986
11168
  autoPreparedStatements: (_a = options.autoPreparedStatements) != null ? _a : false,
10987
11169
  parsers: hasParsers ? parsers : void 0,
10988
- language: options.language
11170
+ language: options.language,
11171
+ schema: options == null ? void 0 : options.schema
10989
11172
  };
10990
- if (options == null ? void 0 : options.schema) {
10991
- 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
+ }
10992
11183
  }
10993
- this.primaryKeys = Object.keys(shape).filter(
10994
- (key) => shape[key].data.isPrimaryKey
10995
- );
10996
- const primaryKeysFromData = (_b = getTableData().primaryKey) == null ? void 0 : _b.columns;
10997
- if (primaryKeysFromData)
10998
- this.primaryKeys.push(...primaryKeysFromData);
10999
- if (this.primaryKeys.length === 1) {
11000
- this.singlePrimaryKey = this.primaryKeys[0];
11001
- } else if (this.primaryKeys.length === 0 && shape !== anyShape && options.noPrimaryKey !== "ignore") {
11184
+ if (!shapeHasPrimaryKey && !tableData.primaryKey && shape !== anyShape && options.noPrimaryKey !== "ignore") {
11002
11185
  const message = `Table ${table} has no primary key`;
11003
11186
  if (options.noPrimaryKey === "error")
11004
11187
  throw new Error(message);
@@ -11187,24 +11370,22 @@ const createDb = (_a) => {
11187
11370
  ct[snakeCaseKey] = true;
11188
11371
  }
11189
11372
  const transactionStorage = new AsyncLocalStorage();
11190
- const qb = new Db(
11373
+ const qb = _initQueryBuilder(
11191
11374
  adapter,
11192
- void 0,
11193
- void 0,
11194
- anyShape,
11195
11375
  ct,
11196
11376
  transactionStorage,
11197
- commonOptions
11377
+ commonOptions,
11378
+ options
11198
11379
  );
11199
- qb.queryBuilder = qb;
11200
- const tableConstructor = (table, shape, options2) => new Db(
11380
+ const tableConstructor = (table, shape, dataFn, options2) => new Db(
11201
11381
  adapter,
11202
11382
  qb,
11203
11383
  table,
11204
11384
  typeof shape === "function" ? getColumnTypes(ct, shape, nowSQL, options2 == null ? void 0 : options2.language) : shape,
11205
11385
  ct,
11206
11386
  transactionStorage,
11207
- __spreadValues(__spreadValues({}, commonOptions), options2)
11387
+ __spreadValues(__spreadValues({}, commonOptions), options2),
11388
+ parseTableData(dataFn)
11208
11389
  );
11209
11390
  const db = Object.assign(tableConstructor, qb, {
11210
11391
  adapter,
@@ -11215,6 +11396,32 @@ const createDb = (_a) => {
11215
11396
  }
11216
11397
  return db;
11217
11398
  };
11399
+ const _initQueryBuilder = (adapter, columnTypes, transactionStorage, commonOptions, options) => {
11400
+ const qb = new Db(
11401
+ adapter,
11402
+ void 0,
11403
+ void 0,
11404
+ anyShape,
11405
+ columnTypes,
11406
+ transactionStorage,
11407
+ commonOptions
11408
+ );
11409
+ if (options.extensions) {
11410
+ const arr = [];
11411
+ for (const x of options.extensions) {
11412
+ if (typeof x === "string") {
11413
+ arr.push({ name: x });
11414
+ } else {
11415
+ for (const key in x) {
11416
+ arr.push({ name: key, version: x[key] });
11417
+ }
11418
+ }
11419
+ }
11420
+ qb.internal.extensions = arr;
11421
+ }
11422
+ qb.internal.domains = options.domains;
11423
+ return qb.queryBuilder = qb;
11424
+ };
11218
11425
 
11219
11426
  class Rollback extends Error {
11220
11427
  }
@@ -11347,5 +11554,5 @@ function copyTableData(query, arg) {
11347
11554
  return q;
11348
11555
  }
11349
11556
 
11350
- 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, _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, constraintPropsToCode, constraintToCode, copyTableData, countSelect, createDb, defaultSchemaConfig, extendQuery, foreignKeyArgumentToCode, getClonedQueryData, getColumnInfo, getColumnTypes, getConstraintKind, getQueryAs, getShapeFromSelect, getTableData, handleResult, identityToCode, indexToCode, instantiateColumn, isDefaultTimeStamp, isQueryReturnsAll, isSelectingCount, joinSubQuery, logColors, logParamToLogObject, makeColumnTypes, makeColumnsByType, makeExpression, makeFnExpression, makeRegexToFindInSql, makeSQL, newTableData, parseRecord, parseResult, 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 };
11351
11558
  //# sourceMappingURL=index.mjs.map