pqb 0.27.5 → 0.27.7

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';
@@ -139,9 +139,12 @@ class ColumnType extends ColumnTypeBase {
139
139
  * // primary key can be used by `find` later:
140
140
  * db.table.find('97ba9e78-7510-415a-9c03-23d440aec443');
141
141
  * ```
142
+ *
143
+ * @param options - to specify a constraint name
142
144
  */
143
- primaryKey() {
144
- return setColumnData(this, "isPrimaryKey", true);
145
+ primaryKey(options) {
146
+ var _a;
147
+ return setColumnData(this, "primaryKey", (_a = options == null ? void 0 : options.name) != null ? _a : true);
145
148
  }
146
149
  foreignKey(fnOrTable, column, options = emptyObject) {
147
150
  const item = typeof fnOrTable === "string" ? __spreadValues$h({ table: fnOrTable, columns: [column] }, options) : __spreadValues$h({ fn: fnOrTable, columns: [column] }, options);
@@ -154,9 +157,9 @@ class ColumnType extends ColumnTypeBase {
154
157
  return pushColumnData(this, "indexes", options);
155
158
  }
156
159
  /**
157
- * `searchIndex` is designed for full text search.
160
+ * `searchIndex` is designed for [full text search](/guide/text-search).
158
161
  *
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`.
162
+ * 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
163
  *
161
164
  * ```ts
162
165
  * import { change } from '../dbScript';
@@ -164,8 +167,8 @@ class ColumnType extends ColumnTypeBase {
164
167
  * change(async (db) => {
165
168
  * await db.createTable('table', (t) => ({
166
169
  * id: t.identity().primaryKey(),
167
- * title: t.string(),
168
- * body: t.string(),
170
+ * title: t.text(),
171
+ * body: t.text(),
169
172
  * ...t.searchIndex(['title', 'body']),
170
173
  * }));
171
174
  * });
@@ -174,10 +177,29 @@ class ColumnType extends ColumnTypeBase {
174
177
  * Produces the following index ('english' is a default language, see [full text search](/guide/text-search.html#language) for changing it):
175
178
  *
176
179
  * ```sql
177
- * CREATE INDEX "table_title_body_idx" ON "table" USING GIN (to_tsvector('english', concat_ws(' ', "title", "body")))
180
+ * CREATE INDEX "table_title_body_idx" ON "table" USING GIN (to_tsvector('english', "title" || ' ' || "body"))
181
+ * ```
182
+ *
183
+ * You can set different search weights (`A` to `D`) on different columns inside the index:
184
+ *
185
+ * ```ts
186
+ * import { change } from '../dbScript';
187
+ *
188
+ * change(async (db) => {
189
+ * await db.createTable('table', (t) => ({
190
+ * id: t.identity().primaryKey(),
191
+ * title: t.text(),
192
+ * body: t.text(),
193
+ * ...t.searchIndex([
194
+ * { column: 'title', weight: 'A' },
195
+ * { column: 'body', weight: 'B' },
196
+ * ]),
197
+ * }));
198
+ * });
178
199
  * ```
179
200
  *
180
- * Also, it works well with a generated `tsvector` column:
201
+ * When the table has localized columns,
202
+ * you can define different indexes for different languages by setting the `language` parameter:
181
203
  *
182
204
  * ```ts
183
205
  * import { change } from '../dbScript';
@@ -185,8 +207,44 @@ class ColumnType extends ColumnTypeBase {
185
207
  * change(async (db) => {
186
208
  * await db.createTable('table', (t) => ({
187
209
  * id: t.identity().primaryKey(),
188
- * title: t.string(),
189
- * body: t.string(),
210
+ * titleEn: t.text(),
211
+ * bodyEn: t.text(),
212
+ * titleFr: t.text(),
213
+ * bodyFr: t.text(),
214
+ * ...t.searchIndex(['titleEn', 'bodyEn'], { language: 'english' }),
215
+ * ...t.searchIndex(['titleFr', 'bodyFr'], { language: 'french' }),
216
+ * }));
217
+ * });
218
+ * ```
219
+ *
220
+ * Alternatively, different table records may correspond to a single language,
221
+ * then you can define a search index that relies on a language column by using `languageColumn` parameter:
222
+ *
223
+ * ```ts
224
+ * import { change } from '../dbScript';
225
+ *
226
+ * change(async (db) => {
227
+ * await db.createTable('table', (t) => ({
228
+ * id: t.identity().primaryKey(),
229
+ * lang: t.type('regconfig'),
230
+ * title: t.text(),
231
+ * body: t.text(),
232
+ * ...t.searchIndex(['title', 'body'], { languageColumn: 'lang' }),
233
+ * }));
234
+ * });
235
+ * ```
236
+ *
237
+ * 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,
238
+ * and to set a `searchIndex` on it:
239
+ *
240
+ * ```ts
241
+ * import { change } from '../dbScript';
242
+ *
243
+ * change(async (db) => {
244
+ * await db.createTable('table', (t) => ({
245
+ * id: t.identity().primaryKey(),
246
+ * title: t.text(),
247
+ * body: t.text(),
190
248
  * generatedTsVector: t.tsvector().generated(['title', 'body']).searchIndex(),
191
249
  * }));
192
250
  * });
@@ -267,14 +325,21 @@ const knownDefaults = {
267
325
  };
268
326
  const simplifyColumnDefault = (value) => {
269
327
  if (typeof value === "string") {
270
- const lower = value.toLowerCase();
271
- return new RawSQL(knownDefaults[lower] || value);
328
+ return new RawSQL([
329
+ [knownDefaults[value.toLowerCase()] || value]
330
+ ]);
272
331
  }
273
332
  return;
274
333
  };
275
334
  const instantiateColumn = (typeFn, params) => {
276
335
  const column = typeFn();
336
+ const { dateTimePrecision } = params;
277
337
  Object.assign(column.data, __spreadProps$a(__spreadValues$g({}, params), {
338
+ dateTimePrecision: (
339
+ // 0 is default for date, 6 is default for timestamp
340
+ dateTimePrecision && dateTimePrecision !== 6 ? dateTimePrecision : void 0
341
+ ),
342
+ collate: params.collate,
278
343
  default: simplifyColumnDefault(params.default)
279
344
  }));
280
345
  return column;
@@ -315,7 +380,7 @@ const combineCodeElements = (input) => {
315
380
  }
316
381
  return output;
317
382
  };
318
- const columnsShapeToCode = (shape, tableData, t) => {
383
+ const columnsShapeToCode = (shape, tableData, t, m) => {
319
384
  const hasTimestamps = "createdAt" in shape && isDefaultTimeStamp(shape.createdAt) && "updatedAt" in shape && isDefaultTimeStamp(shape.updatedAt);
320
385
  const code = [];
321
386
  for (const key in shape) {
@@ -343,19 +408,33 @@ const columnsShapeToCode = (shape, tableData, t) => {
343
408
  }
344
409
  if (constraints) {
345
410
  for (const item of constraints) {
346
- code.push(...constraintToCode(item, t));
411
+ code.push(...constraintToCode(item, t, m));
347
412
  }
348
413
  }
349
414
  return code;
350
415
  };
351
416
  const primaryKeyToCode = (primaryKey, t) => {
417
+ return `...${primaryKeyInnerToCode(primaryKey, t)},`;
418
+ };
419
+ const primaryKeyInnerToCode = (primaryKey, t) => {
352
420
  var _a;
353
421
  const name = (_a = primaryKey.options) == null ? void 0 : _a.name;
354
- return `...${t}.primaryKey([${primaryKey.columns.map(singleQuote).join(", ")}]${name ? `, { name: ${singleQuote(name)} }` : ""}),`;
422
+ return `${t}.primaryKey([${primaryKey.columns.map(singleQuote).join(", ")}]${name ? `, { name: ${singleQuote(name)} }` : ""})`;
355
423
  };
356
424
  const indexToCode = (index, t) => {
425
+ const code = indexInnerToCode(index, t);
426
+ code[0] = `...${code[0]}`;
427
+ const last = code[code.length - 1];
428
+ if (typeof last === "string" && !last.endsWith(","))
429
+ addCode(code, ",");
430
+ return code;
431
+ };
432
+ const indexInnerToCode = (index, t) => {
357
433
  const code = [];
358
- code.push(`...${t}.index(`);
434
+ code.push(
435
+ `${t}.${index.options.tsVector ? "searchIndex" : index.options.unique ? "unique" : "index"}(`
436
+ );
437
+ const columnOptions = ["collate", "opclass", "order", "weight"];
359
438
  const columnsMultiline = index.columns.some((column) => {
360
439
  for (const key in column) {
361
440
  if (key !== "column" && column[key] !== void 0)
@@ -367,13 +446,13 @@ const indexToCode = (index, t) => {
367
446
  const objects = [];
368
447
  for (const column of index.columns) {
369
448
  const expr = "column" in column ? column.column : column.expression;
370
- let hasOptions2 = false;
449
+ let hasOptions = false;
371
450
  for (const key in column) {
372
- if (key !== "column" && key !== "expression") {
373
- hasOptions2 = true;
451
+ if (key !== "column") {
452
+ hasOptions = true;
374
453
  }
375
454
  }
376
- if (!hasOptions2) {
455
+ if (!hasOptions) {
377
456
  objects.push(`${singleQuote(expr)},`);
378
457
  } else {
379
458
  const props = [
@@ -381,14 +460,11 @@ const indexToCode = (index, t) => {
381
460
  expr
382
461
  )},`
383
462
  ];
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)},`);
463
+ for (const key of columnOptions) {
464
+ const value = column[key];
465
+ if (value !== void 0) {
466
+ props.push(`${key}: ${singleQuote(value)},`);
467
+ }
392
468
  }
393
469
  objects.push("{", props, "},");
394
470
  }
@@ -400,8 +476,22 @@ const indexToCode = (index, t) => {
400
476
  `[${index.columns.map((it) => singleQuote(it.column)).join(", ")}]`
401
477
  );
402
478
  }
403
- const hasOptions = objectHasValues(index.options);
404
- if (hasOptions) {
479
+ const indexOptionsKeys = [
480
+ "name",
481
+ "using",
482
+ "nullsNotDistinct",
483
+ "include",
484
+ "with",
485
+ "tablespace",
486
+ "where",
487
+ "language",
488
+ "languageColumn",
489
+ "dropMode"
490
+ ];
491
+ if (index.options.tsVector && index.options.unique) {
492
+ indexOptionsKeys.unshift("unique");
493
+ }
494
+ if (indexOptionsKeys.some((key) => index.options[key])) {
405
495
  if (columnsMultiline) {
406
496
  const columns = code[code.length - 1];
407
497
  columns[columns.length - 1] += ",";
@@ -410,7 +500,7 @@ const indexToCode = (index, t) => {
410
500
  addCode(code, ", {");
411
501
  }
412
502
  const options = [];
413
- for (const key in index.options) {
503
+ for (const key of indexOptionsKeys) {
414
504
  const value = index.options[key];
415
505
  if (value === null || value === void 0)
416
506
  continue;
@@ -428,25 +518,35 @@ const indexToCode = (index, t) => {
428
518
  if (columnsMultiline) {
429
519
  code.push("),");
430
520
  } else {
431
- addCode(code, "),");
521
+ addCode(code, ")");
432
522
  }
433
523
  return code;
434
524
  };
435
- const constraintToCode = (item, t) => {
525
+ const constraintToCode = (item, t, m) => {
526
+ const code = constraintInnerToCode(item, t, m);
527
+ code[0] = `...${code[0]}`;
528
+ const last = code[code.length - 1];
529
+ if (typeof last === "string" && !last.endsWith(","))
530
+ code[code.length - 1] += ",";
531
+ return code;
532
+ };
533
+ const constraintInnerToCode = (item, t, m) => {
436
534
  const kind = getConstraintKind(item);
437
535
  if (kind === "foreignKey" && item.references) {
438
536
  return [
439
- `...${t}.foreignKey(`,
440
- referencesArgsToCode(item.references, item.name),
537
+ `${t}.foreignKey(`,
538
+ referencesArgsToCode(item.references, item.name, m),
441
539
  "),"
442
540
  ];
443
541
  } else if (kind === "check" && item.check) {
444
- return [`...${t}.check(${item.check.toCode(t)}),`];
542
+ return [
543
+ `${t}.check(${item.check.toCode(t)}${item.name ? `, { name: '${item.name}' }` : ""})`
544
+ ];
445
545
  } else {
446
- return [`...${t}.constraint({`, constraintPropsToCode(t, item), "}),"];
546
+ return [`${t}.constraint({`, constraintPropsToCode(t, item, m), "}),"];
447
547
  }
448
548
  };
449
- const constraintPropsToCode = (t, item) => {
549
+ const constraintPropsToCode = (t, item, m) => {
450
550
  const props = [];
451
551
  if (item.name) {
452
552
  props.push(`name: ${singleQuote(item.name)},`);
@@ -454,7 +554,7 @@ const constraintPropsToCode = (t, item) => {
454
554
  if (item.references) {
455
555
  props.push(
456
556
  `references: [`,
457
- referencesArgsToCode(item.references, false),
557
+ referencesArgsToCode(item.references, false, m),
458
558
  "],"
459
559
  );
460
560
  }
@@ -468,9 +568,13 @@ const referencesArgsToCode = ({
468
568
  fnOrTable,
469
569
  foreignColumns,
470
570
  options
471
- }, name = (options == null ? void 0 : options.name) || false) => {
571
+ }, name = (options == null ? void 0 : options.name) || false, m) => {
472
572
  const args = [];
473
573
  args.push(`${singleQuoteArray(columns)},`);
574
+ if (m && typeof fnOrTable !== "string") {
575
+ const { schema, table } = new (fnOrTable())();
576
+ fnOrTable = schema ? `${schema}.${table}` : table;
577
+ }
474
578
  args.push(
475
579
  `${typeof fnOrTable === "string" ? singleQuote(fnOrTable) : fnOrTable.toString()},`
476
580
  );
@@ -490,24 +594,27 @@ const referencesArgsToCode = ({
490
594
  }
491
595
  return args;
492
596
  };
493
- const columnForeignKeysToCode = (foreignKeys) => {
597
+ const columnForeignKeysToCode = (foreignKeys, migration) => {
494
598
  const code = [];
495
599
  for (const foreignKey of foreignKeys) {
496
600
  addCode(code, `.foreignKey(`);
497
- for (const part of foreignKeyArgumentToCode(foreignKey)) {
601
+ for (const part of foreignKeyArgumentToCode(foreignKey, migration)) {
498
602
  addCode(code, part);
499
603
  }
500
604
  addCode(code, ")");
501
605
  }
502
606
  return code;
503
607
  };
504
- const foreignKeyArgumentToCode = (foreignKey) => {
608
+ const foreignKeyArgumentToCode = (foreignKey, migration) => {
505
609
  const code = [];
506
- if ("fn" in foreignKey) {
507
- code.push(foreignKey.fn.toString());
508
- } else {
509
- code.push(singleQuote(foreignKey.table));
610
+ let fnOrTable = "fn" in foreignKey ? foreignKey.fn : foreignKey.table;
611
+ if (migration && typeof fnOrTable !== "string") {
612
+ const { schema, table } = new (fnOrTable())();
613
+ fnOrTable = schema ? `${schema}.${table}` : table;
510
614
  }
615
+ code.push(
616
+ typeof fnOrTable === "string" ? singleQuote(fnOrTable) : fnOrTable.toString()
617
+ );
511
618
  addCode(code, `, ${singleQuote(foreignKey.columns[0])}`);
512
619
  const hasOptions = foreignKey.name || foreignKey.match || foreignKey.onUpdate || foreignKey.onDelete;
513
620
  if (hasOptions) {
@@ -562,8 +669,8 @@ const columnIndexesToCode = (indexes) => {
562
669
  }
563
670
  return code;
564
671
  };
565
- const columnCheckToCode = (t, check) => {
566
- return `.check(${check.toCode(t)})`;
672
+ const columnCheckToCode = (t, { sql, options }) => {
673
+ return `.check(${sql.toCode(t)}${(options == null ? void 0 : options.name) ? `, { name: '${options.name}' }` : ""})`;
567
674
  };
568
675
  const identityToCode = (identity, dataType) => {
569
676
  const code = [];
@@ -575,16 +682,18 @@ const identityToCode = (identity, dataType) => {
575
682
  const props = [];
576
683
  if (identity.always)
577
684
  props.push(`always: true,`);
578
- if (identity.incrementBy)
579
- props.push(`incrementBy: ${identity.incrementBy},`);
580
- if (identity.startWith)
581
- props.push(`startWith: ${identity.startWith},`);
685
+ if (identity.increment && identity.increment !== 1)
686
+ props.push(`increment: ${identity.increment},`);
687
+ if (identity.start && identity.start !== 1)
688
+ props.push(`start: ${identity.start},`);
582
689
  if (identity.min)
583
690
  props.push(`min: ${identity.min},`);
584
691
  if (identity.max)
585
692
  props.push(`max: ${identity.max},`);
586
- if (identity.cache)
693
+ if (identity.cache && identity.cache !== 1)
587
694
  props.push(`cache: ${identity.cache},`);
695
+ if (identity.cycle)
696
+ props.push(`cycle: true,`);
588
697
  if (props.length) {
589
698
  addCode(code, "{");
590
699
  code.push(props, "}");
@@ -592,7 +701,7 @@ const identityToCode = (identity, dataType) => {
592
701
  addCode(code, ")");
593
702
  return code;
594
703
  };
595
- const columnCode = (type, t, code, data = type.data, skip) => {
704
+ const columnCode = (type, t, code, migration, data = type.data, skip) => {
596
705
  code = toArray(code);
597
706
  let prepend = `${t}.`;
598
707
  if (data.name) {
@@ -603,10 +712,14 @@ const columnCode = (type, t, code, data = type.data, skip) => {
603
712
  } else {
604
713
  code[0].unshift(prepend);
605
714
  }
606
- if (data.isPrimaryKey)
607
- addCode(code, ".primaryKey()");
715
+ if (data.primaryKey) {
716
+ addCode(
717
+ code,
718
+ `.primaryKey(${data.primaryKey === true ? "" : `{ name: '${data.primaryKey}' }`})`
719
+ );
720
+ }
608
721
  if (data.foreignKeys) {
609
- for (const part of columnForeignKeysToCode(data.foreignKeys)) {
722
+ for (const part of columnForeignKeysToCode(data.foreignKeys, migration)) {
610
723
  addCode(code, part);
611
724
  }
612
725
  }
@@ -620,7 +733,7 @@ const columnCode = (type, t, code, data = type.data, skip) => {
620
733
  addCode(code, `.parse(${type.parseFn.toString()})`);
621
734
  if (data.as)
622
735
  addCode(code, `.as(${data.as.toCode(t)})`);
623
- if (data.default !== void 0) {
736
+ if (data.default !== void 0 && (!migration || typeof data.default !== "function")) {
624
737
  addCode(code, `.default(${columnDefaultArgumentToCode(t, data.default)})`);
625
738
  }
626
739
  if (data.indexes) {
@@ -822,8 +935,8 @@ class JSONColumn extends ColumnType {
822
935
  this.dataType = "jsonb";
823
936
  this.operators = Operators.json;
824
937
  }
825
- toCode(t) {
826
- return columnCode(this, t, `json()`, this.data, toCodeSkip);
938
+ toCode(t, m) {
939
+ return columnCode(this, t, `json()`, m, this.data, toCodeSkip);
827
940
  }
828
941
  }
829
942
  JSONColumn.prototype.encodeFn = JSON.stringify;
@@ -833,8 +946,8 @@ class JSONTextColumn extends ColumnType {
833
946
  this.dataType = "json";
834
947
  this.operators = Operators.text;
835
948
  }
836
- toCode(t) {
837
- return columnCode(this, t, `jsonText()`, this.data, toCodeSkip);
949
+ toCode(t, m) {
950
+ return columnCode(this, t, `jsonText()`, m, this.data, toCodeSkip);
838
951
  }
839
952
  }
840
953
 
@@ -1424,8 +1537,9 @@ const processJoinArgs = (joinTo, first, args, joinSubQuery) => {
1424
1537
  };
1425
1538
  const makeJoinQueryBuilder = (joinedQuery, joinedShapes, joinTo) => {
1426
1539
  const q = joinedQuery.baseQuery.clone();
1427
- q.q.joinedShapes = joinedShapes;
1428
1540
  q.baseQuery = q;
1541
+ q.q.as = joinedQuery.q.as;
1542
+ q.q.joinedShapes = joinedShapes;
1429
1543
  q.q.joinTo = joinTo;
1430
1544
  return q;
1431
1545
  };
@@ -1603,11 +1717,12 @@ class DateColumn extends DateBaseColumn {
1603
1717
  super(...arguments);
1604
1718
  this.dataType = "date";
1605
1719
  }
1606
- toCode(t) {
1720
+ toCode(t, m) {
1607
1721
  return columnCode(
1608
1722
  this,
1609
1723
  t,
1610
- `date()${dateDataToCode(this.data)}`,
1724
+ `date()${dateDataToCode(this.data, m)}`,
1725
+ m,
1611
1726
  this.data,
1612
1727
  skipDateMethodsFromToCode
1613
1728
  );
@@ -1634,7 +1749,7 @@ class DateTimeTzBaseClass extends DateTimeBaseClass {
1634
1749
  );
1635
1750
  }
1636
1751
  }
1637
- const timestampToCode = (self, t) => {
1752
+ const timestampToCode = (self, t, m) => {
1638
1753
  const { dateTimePrecision: p } = self.data;
1639
1754
  const { defaultTimestamp } = self.data;
1640
1755
  if (defaultTimestamp) {
@@ -1646,7 +1761,8 @@ const timestampToCode = (self, t) => {
1646
1761
  const code = columnCode(
1647
1762
  self,
1648
1763
  t,
1649
- `timestamps${noTz}(${p && p !== 6 ? p : ""}).${defaultTimestamp}${dateDataToCode(self.data)}`,
1764
+ `timestamps${noTz}(${p && p !== 6 ? p : ""}).${defaultTimestamp}${dateDataToCode(self.data, m)}`,
1765
+ m,
1650
1766
  self.data,
1651
1767
  skipDateMethodsFromToCode
1652
1768
  );
@@ -1657,7 +1773,8 @@ const timestampToCode = (self, t) => {
1657
1773
  return columnCode(
1658
1774
  self,
1659
1775
  t,
1660
- `${self instanceof TimestampColumn ? "timestampNoTZ" : "timestamp"}(${p && p !== 6 ? p : ""})${dateDataToCode(self.data)}`,
1776
+ `${self instanceof TimestampColumn ? "timestampNoTZ" : "timestamp"}(${p && p !== 6 ? p : ""})${dateDataToCode(self.data, m)}`,
1777
+ m,
1661
1778
  self.data,
1662
1779
  skipDateMethodsFromToCode
1663
1780
  );
@@ -1668,8 +1785,8 @@ class TimestampColumn extends DateTimeBaseClass {
1668
1785
  super(...arguments);
1669
1786
  this.dataType = "timestamp";
1670
1787
  }
1671
- toCode(t) {
1672
- return timestampToCode(this, t);
1788
+ toCode(t, m) {
1789
+ return timestampToCode(this, t, m);
1673
1790
  }
1674
1791
  }
1675
1792
  class TimestampTZColumn extends DateTimeTzBaseClass {
@@ -1678,8 +1795,8 @@ class TimestampTZColumn extends DateTimeTzBaseClass {
1678
1795
  this.dataType = "timestamptz";
1679
1796
  this.baseDataType = "timestamp";
1680
1797
  }
1681
- toCode(t) {
1682
- return timestampToCode(this, t);
1798
+ toCode(t, m) {
1799
+ return timestampToCode(this, t, m);
1683
1800
  }
1684
1801
  }
1685
1802
  class TimeColumn extends ColumnType {
@@ -1689,12 +1806,13 @@ class TimeColumn extends ColumnType {
1689
1806
  this.operators = Operators.time;
1690
1807
  this.data.dateTimePrecision = dateTimePrecision;
1691
1808
  }
1692
- toCode(t) {
1809
+ toCode(t, m) {
1693
1810
  const { dateTimePrecision } = this.data;
1694
1811
  return columnCode(
1695
1812
  this,
1696
1813
  t,
1697
- `time(${dateTimePrecision || ""})${dateDataToCode(this.data)}`,
1814
+ `time(${dateTimePrecision || ""})${dateDataToCode(this.data, m)}`,
1815
+ m,
1698
1816
  this.data,
1699
1817
  skipDateMethodsFromToCode
1700
1818
  );
@@ -1708,12 +1826,13 @@ class IntervalColumn extends ColumnType {
1708
1826
  this.data.fields = fields;
1709
1827
  this.data.precision = precision;
1710
1828
  }
1711
- toCode(t) {
1829
+ toCode(t, m) {
1712
1830
  const { fields, precision } = this.data;
1713
1831
  return columnCode(
1714
1832
  this,
1715
1833
  t,
1716
1834
  `interval(${[fields && `'${fields}'`, precision && String(precision)].filter((part) => part).join(", ")})`,
1835
+ m,
1717
1836
  this.data,
1718
1837
  skipDateMethodsFromToCode
1719
1838
  );
@@ -1736,9 +1855,9 @@ class EnumColumn extends ColumnType {
1736
1855
  this.dataType = "enum";
1737
1856
  this.inputSchema = this.outputSchema = this.querySchema = schemaType;
1738
1857
  }
1739
- toCode(t, migration) {
1740
- const options = migration ? "" : `, [${this.options.map((option) => `'${option}'`).join(", ")}]`;
1741
- return columnCode(this, t, `enum('${this.enumName}'${options})`);
1858
+ toCode(t, m) {
1859
+ const options = m ? "" : `, [${this.options.map((option) => `'${option}'`).join(", ")}]`;
1860
+ return columnCode(this, t, `enum('${this.enumName}'${options})`, m);
1742
1861
  }
1743
1862
  toSQL() {
1744
1863
  const name = this.enumName;
@@ -1770,15 +1889,16 @@ class ArrayColumn extends ColumnType {
1770
1889
  }
1771
1890
  );
1772
1891
  this.data.item = item;
1892
+ this.data.name = item.data.name;
1773
1893
  }
1774
1894
  toSQL() {
1775
1895
  return `${this.data.item.toSQL()}[]`;
1776
1896
  }
1777
- toCode(t) {
1897
+ toCode(t, m) {
1778
1898
  const code = ["array("];
1779
1899
  addCode(code, this.data.item.toCode(t));
1780
- addCode(code, `)${arrayDataToCode(this.data)}`);
1781
- return columnCode(this, t, code);
1900
+ addCode(code, `)${arrayDataToCode(this.data, m)}`);
1901
+ return columnCode(this, t, code, m);
1782
1902
  }
1783
1903
  }
1784
1904
  const parseArray = (input, pos, len, entries, nested, item) => {
@@ -4061,16 +4181,18 @@ class DecimalColumn extends ColumnType {
4061
4181
  constructor(schema, numericPrecision, numericScale) {
4062
4182
  super(schema, schema.stringSchema());
4063
4183
  this.operators = Operators.number;
4064
- this.dataType = "decimal";
4184
+ this.dataType = "numeric";
4065
4185
  this.data.numericPrecision = numericPrecision;
4066
4186
  this.data.numericScale = numericScale;
4187
+ this.data.alias = "decimal";
4067
4188
  }
4068
- toCode(t) {
4189
+ toCode(t, m) {
4069
4190
  const { numericPrecision, numericScale } = this.data;
4070
4191
  return columnCode(
4071
4192
  this,
4072
4193
  t,
4073
- `decimal(${numericPrecision || ""}${numericScale ? `, ${numericScale}` : ""})`
4194
+ `decimal(${numericPrecision || ""}${numericScale ? `, ${numericScale}` : ""})`,
4195
+ m
4074
4196
  );
4075
4197
  }
4076
4198
  toSQL() {
@@ -4082,49 +4204,52 @@ class DecimalColumn extends ColumnType {
4082
4204
  }
4083
4205
  }
4084
4206
  const skipNumberMethods = { int: true };
4085
- const intToCode = (column, t) => {
4207
+ const intToCode = (column, t, alias, m) => {
4086
4208
  let code;
4087
4209
  if (column.data.identity) {
4088
- code = identityToCode(column.data.identity, column.dataType);
4210
+ code = identityToCode(column.data.identity, alias);
4089
4211
  } else {
4090
- code = [`${column.dataType}()`];
4212
+ code = [`${alias}()`];
4091
4213
  }
4092
- addCode(code, numberDataToCode(column.data, skipNumberMethods));
4093
- return columnCode(column, t, code);
4214
+ addCode(code, numberDataToCode(column.data, m, skipNumberMethods));
4215
+ return columnCode(column, t, code, m);
4094
4216
  };
4095
4217
  class SmallIntColumn extends IntegerBaseColumn {
4096
- constructor() {
4097
- super(...arguments);
4098
- this.dataType = "smallint";
4218
+ constructor(schema) {
4219
+ super(schema);
4220
+ this.dataType = "int2";
4099
4221
  this.parseItem = parseInt;
4222
+ this.data.alias = "smallint";
4100
4223
  }
4101
- toCode(t) {
4102
- return intToCode(this, t);
4224
+ toCode(t, m) {
4225
+ return intToCode(this, t, "smallint", m);
4103
4226
  }
4104
4227
  identity(options = {}) {
4105
4228
  return setColumnData(this, "identity", options);
4106
4229
  }
4107
4230
  }
4108
4231
  class IntegerColumn extends IntegerBaseColumn {
4109
- constructor() {
4110
- super(...arguments);
4111
- this.dataType = "integer";
4232
+ constructor(schema) {
4233
+ super(schema);
4234
+ this.dataType = "int4";
4112
4235
  this.parseItem = parseInt;
4236
+ this.data.alias = "integer";
4113
4237
  }
4114
- toCode(t) {
4115
- return intToCode(this, t);
4238
+ toCode(t, m) {
4239
+ return intToCode(this, t, "integer", m);
4116
4240
  }
4117
4241
  identity(options = {}) {
4118
4242
  return setColumnData(this, "identity", options);
4119
4243
  }
4120
4244
  }
4121
4245
  class BigIntColumn extends NumberAsStringBaseColumn {
4122
- constructor() {
4123
- super(...arguments);
4124
- this.dataType = "bigint";
4246
+ constructor(schema) {
4247
+ super(schema);
4248
+ this.dataType = "int8";
4249
+ this.data.alias = "bigint";
4125
4250
  }
4126
- toCode(t) {
4127
- return intToCode(this, t);
4251
+ toCode(t, m) {
4252
+ return intToCode(this, t, "bigint", m);
4128
4253
  }
4129
4254
  identity(options = {}) {
4130
4255
  return setColumnData(this, "identity", options);
@@ -4133,68 +4258,75 @@ class BigIntColumn extends NumberAsStringBaseColumn {
4133
4258
  class RealColumn extends NumberBaseColumn {
4134
4259
  constructor(schema) {
4135
4260
  super(schema, schema.number());
4136
- this.dataType = "real";
4261
+ this.dataType = "float4";
4137
4262
  this.parseItem = parseFloat;
4263
+ this.data.alias = "real";
4138
4264
  }
4139
- toCode(t) {
4140
- return columnCode(this, t, `real()${numberDataToCode(this.data)}`);
4265
+ toCode(t, m) {
4266
+ return columnCode(this, t, `real()${numberDataToCode(this.data, m)}`, m);
4141
4267
  }
4142
4268
  }
4143
4269
  class DoublePrecisionColumn extends NumberAsStringBaseColumn {
4144
- constructor() {
4145
- super(...arguments);
4146
- this.dataType = "double precision";
4270
+ constructor(schema) {
4271
+ super(schema);
4272
+ this.dataType = "float8";
4273
+ this.data.alias = "doublePrecision";
4147
4274
  }
4148
- toCode(t) {
4149
- return columnCode(this, t, `doublePrecision()`);
4275
+ toCode(t, m) {
4276
+ return columnCode(this, t, `doublePrecision()`, m);
4150
4277
  }
4151
4278
  }
4152
4279
  class SmallSerialColumn extends IntegerBaseColumn {
4153
4280
  constructor(schema) {
4154
4281
  super(schema);
4155
- this.dataType = "smallint";
4282
+ this.dataType = "int2";
4156
4283
  this.parseItem = parseInt;
4157
4284
  this.data.int = true;
4285
+ this.data.alias = "smallSerial";
4158
4286
  }
4159
4287
  toSQL() {
4160
4288
  return "smallserial";
4161
4289
  }
4162
- toCode(t) {
4290
+ toCode(t, m) {
4163
4291
  return columnCode(
4164
4292
  this,
4165
4293
  t,
4166
- `smallSerial()${numberDataToCode(this.data, skipNumberMethods)}`
4294
+ `smallSerial()${numberDataToCode(this.data, m, skipNumberMethods)}`,
4295
+ m
4167
4296
  );
4168
4297
  }
4169
4298
  }
4170
4299
  class SerialColumn extends IntegerBaseColumn {
4171
4300
  constructor(schema) {
4172
4301
  super(schema);
4173
- this.dataType = "integer";
4302
+ this.dataType = "int4";
4174
4303
  this.parseItem = parseInt;
4175
4304
  this.data.int = true;
4305
+ this.data.alias = "serial";
4176
4306
  }
4177
4307
  toSQL() {
4178
4308
  return "serial";
4179
4309
  }
4180
- toCode(t) {
4310
+ toCode(t, m) {
4181
4311
  return columnCode(
4182
4312
  this,
4183
4313
  t,
4184
- `serial()${numberDataToCode(this.data, skipNumberMethods)}`
4314
+ `serial()${numberDataToCode(this.data, m, skipNumberMethods)}`,
4315
+ m
4185
4316
  );
4186
4317
  }
4187
4318
  }
4188
4319
  class BigSerialColumn extends NumberAsStringBaseColumn {
4189
- constructor() {
4190
- super(...arguments);
4191
- this.dataType = "bigint";
4320
+ constructor(schema) {
4321
+ super(schema);
4322
+ this.dataType = "int8";
4323
+ this.data.alias = "bigint";
4192
4324
  }
4193
4325
  toSQL() {
4194
4326
  return "bigserial";
4195
4327
  }
4196
- toCode(t) {
4197
- return columnCode(this, t, `bigSerial()`);
4328
+ toCode(t, m) {
4329
+ return columnCode(this, t, `bigSerial()`, m);
4198
4330
  }
4199
4331
  }
4200
4332
 
@@ -4243,12 +4375,13 @@ class VarCharColumn extends LimitedTextBaseColumn {
4243
4375
  super(...arguments);
4244
4376
  this.dataType = "varchar";
4245
4377
  }
4246
- toCode(t) {
4378
+ toCode(t, m) {
4247
4379
  const { maxChars } = this.data;
4248
4380
  return columnCode(
4249
4381
  this,
4250
4382
  t,
4251
- `varchar(${maxChars != null ? maxChars : ""})${stringDataToCode(this.data)}`
4383
+ `varchar(${maxChars != null ? maxChars : ""})${stringDataToCode(this.data, m)}`,
4384
+ m
4252
4385
  );
4253
4386
  }
4254
4387
  }
@@ -4256,14 +4389,15 @@ class StringColumn extends VarCharColumn {
4256
4389
  constructor(schema, limit = 255) {
4257
4390
  super(schema, limit);
4258
4391
  }
4259
- toCode(t) {
4392
+ toCode(t, m) {
4260
4393
  let max = this.data.maxChars;
4261
4394
  if (max === 255)
4262
4395
  max = void 0;
4263
4396
  return columnCode(
4264
4397
  this,
4265
4398
  t,
4266
- `string(${max != null ? max : ""})${stringDataToCode(this.data)}`
4399
+ `string(${max != null ? max : ""})${stringDataToCode(this.data, m)}`,
4400
+ m
4267
4401
  );
4268
4402
  }
4269
4403
  }
@@ -4272,12 +4406,13 @@ class CharColumn extends LimitedTextBaseColumn {
4272
4406
  super(...arguments);
4273
4407
  this.dataType = "char";
4274
4408
  }
4275
- toCode(t) {
4409
+ toCode(t, m) {
4276
4410
  const { maxChars } = this.data;
4277
4411
  return columnCode(
4278
4412
  this,
4279
4413
  t,
4280
- `char(${maxChars != null ? maxChars : ""})${stringDataToCode(this.data)}`
4414
+ `char(${maxChars != null ? maxChars : ""})${stringDataToCode(this.data, m)}`,
4415
+ m
4281
4416
  );
4282
4417
  }
4283
4418
  }
@@ -4289,7 +4424,7 @@ const setTextColumnData = (column, minArg, maxArg) => {
4289
4424
  }
4290
4425
  }
4291
4426
  };
4292
- const textColumnToCode = (column, t) => {
4427
+ const textColumnToCode = (column, t, m) => {
4293
4428
  const data = __spreadValues$9({}, column.data);
4294
4429
  let args = "";
4295
4430
  const hasMax = data.maxArg !== void 0 && data.max === data.maxArg;
@@ -4308,7 +4443,8 @@ const textColumnToCode = (column, t) => {
4308
4443
  return columnCode(
4309
4444
  column,
4310
4445
  t,
4311
- `${column.dataType}(${args})${stringDataToCode(data)}`
4446
+ `${column.dataType}(${args})${stringDataToCode(data, m)}`,
4447
+ m
4312
4448
  );
4313
4449
  };
4314
4450
  const minMaxToSchema = (schema, min, max) => min ? max ? schema.stringMinMax(min, max) : schema.stringMin(min) : schema.stringSchema();
@@ -4318,8 +4454,8 @@ class TextColumn extends TextBaseColumn {
4318
4454
  this.dataType = "text";
4319
4455
  setTextColumnData(this, min, max);
4320
4456
  }
4321
- toCode(t) {
4322
- return textColumnToCode(this, t);
4457
+ toCode(t, m) {
4458
+ return textColumnToCode(this, t, m);
4323
4459
  }
4324
4460
  }
4325
4461
  class ByteaColumn extends ColumnType {
@@ -4328,8 +4464,8 @@ class ByteaColumn extends ColumnType {
4328
4464
  this.dataType = "bytea";
4329
4465
  this.operators = Operators.text;
4330
4466
  }
4331
- toCode(t) {
4332
- return columnCode(this, t, `bytea()`);
4467
+ toCode(t, m) {
4468
+ return columnCode(this, t, `bytea()`, m);
4333
4469
  }
4334
4470
  }
4335
4471
  class PointColumn extends ColumnType {
@@ -4338,8 +4474,8 @@ class PointColumn extends ColumnType {
4338
4474
  this.dataType = "point";
4339
4475
  this.operators = Operators.text;
4340
4476
  }
4341
- toCode(t) {
4342
- return columnCode(this, t, `point()`);
4477
+ toCode(t, m) {
4478
+ return columnCode(this, t, `point()`, m);
4343
4479
  }
4344
4480
  }
4345
4481
  class LineColumn extends ColumnType {
@@ -4348,8 +4484,8 @@ class LineColumn extends ColumnType {
4348
4484
  this.dataType = "line";
4349
4485
  this.operators = Operators.text;
4350
4486
  }
4351
- toCode(t) {
4352
- return columnCode(this, t, `line()`);
4487
+ toCode(t, m) {
4488
+ return columnCode(this, t, `line()`, m);
4353
4489
  }
4354
4490
  }
4355
4491
  class LsegColumn extends ColumnType {
@@ -4358,8 +4494,8 @@ class LsegColumn extends ColumnType {
4358
4494
  this.dataType = "lseg";
4359
4495
  this.operators = Operators.text;
4360
4496
  }
4361
- toCode(t) {
4362
- return columnCode(this, t, `lseg()`);
4497
+ toCode(t, m) {
4498
+ return columnCode(this, t, `lseg()`, m);
4363
4499
  }
4364
4500
  }
4365
4501
  class BoxColumn extends ColumnType {
@@ -4368,8 +4504,8 @@ class BoxColumn extends ColumnType {
4368
4504
  this.dataType = "box";
4369
4505
  this.operators = Operators.text;
4370
4506
  }
4371
- toCode(t) {
4372
- return columnCode(this, t, `box()`);
4507
+ toCode(t, m) {
4508
+ return columnCode(this, t, `box()`, m);
4373
4509
  }
4374
4510
  }
4375
4511
  class PathColumn extends ColumnType {
@@ -4378,8 +4514,8 @@ class PathColumn extends ColumnType {
4378
4514
  this.dataType = "path";
4379
4515
  this.operators = Operators.text;
4380
4516
  }
4381
- toCode(t) {
4382
- return columnCode(this, t, `path()`);
4517
+ toCode(t, m) {
4518
+ return columnCode(this, t, `path()`, m);
4383
4519
  }
4384
4520
  }
4385
4521
  class PolygonColumn extends ColumnType {
@@ -4388,8 +4524,8 @@ class PolygonColumn extends ColumnType {
4388
4524
  this.dataType = "polygon";
4389
4525
  this.operators = Operators.text;
4390
4526
  }
4391
- toCode(t) {
4392
- return columnCode(this, t, `polygon()`);
4527
+ toCode(t, m) {
4528
+ return columnCode(this, t, `polygon()`, m);
4393
4529
  }
4394
4530
  }
4395
4531
  class CircleColumn extends ColumnType {
@@ -4398,8 +4534,8 @@ class CircleColumn extends ColumnType {
4398
4534
  this.dataType = "circle";
4399
4535
  this.operators = Operators.text;
4400
4536
  }
4401
- toCode(t) {
4402
- return columnCode(this, t, `circle()`);
4537
+ toCode(t, m) {
4538
+ return columnCode(this, t, `circle()`, m);
4403
4539
  }
4404
4540
  }
4405
4541
  class MoneyColumn extends NumberBaseColumn {
@@ -4415,8 +4551,8 @@ class MoneyColumn extends NumberBaseColumn {
4415
4551
  }
4416
4552
  );
4417
4553
  }
4418
- toCode(t) {
4419
- return columnCode(this, t, `money()`);
4554
+ toCode(t, m) {
4555
+ return columnCode(this, t, `money()`, m);
4420
4556
  }
4421
4557
  }
4422
4558
  class CidrColumn extends ColumnType {
@@ -4425,8 +4561,8 @@ class CidrColumn extends ColumnType {
4425
4561
  this.dataType = "cidr";
4426
4562
  this.operators = Operators.text;
4427
4563
  }
4428
- toCode(t) {
4429
- return columnCode(this, t, `cidr()`);
4564
+ toCode(t, m) {
4565
+ return columnCode(this, t, `cidr()`, m);
4430
4566
  }
4431
4567
  }
4432
4568
  class InetColumn extends ColumnType {
@@ -4435,8 +4571,8 @@ class InetColumn extends ColumnType {
4435
4571
  this.dataType = "inet";
4436
4572
  this.operators = Operators.text;
4437
4573
  }
4438
- toCode(t) {
4439
- return columnCode(this, t, `inet()`);
4574
+ toCode(t, m) {
4575
+ return columnCode(this, t, `inet()`, m);
4440
4576
  }
4441
4577
  }
4442
4578
  class MacAddrColumn extends ColumnType {
@@ -4445,8 +4581,8 @@ class MacAddrColumn extends ColumnType {
4445
4581
  this.dataType = "macaddr";
4446
4582
  this.operators = Operators.text;
4447
4583
  }
4448
- toCode(t) {
4449
- return columnCode(this, t, `macaddr()`);
4584
+ toCode(t, m) {
4585
+ return columnCode(this, t, `macaddr()`, m);
4450
4586
  }
4451
4587
  }
4452
4588
  class MacAddr8Column extends ColumnType {
@@ -4455,8 +4591,8 @@ class MacAddr8Column extends ColumnType {
4455
4591
  this.dataType = "macaddr8";
4456
4592
  this.operators = Operators.text;
4457
4593
  }
4458
- toCode(t) {
4459
- return columnCode(this, t, `macaddr8()`);
4594
+ toCode(t, m) {
4595
+ return columnCode(this, t, `macaddr8()`, m);
4460
4596
  }
4461
4597
  }
4462
4598
  class BitColumn extends ColumnType {
@@ -4466,9 +4602,9 @@ class BitColumn extends ColumnType {
4466
4602
  this.operators = Operators.text;
4467
4603
  this.data.length = length;
4468
4604
  }
4469
- toCode(t) {
4605
+ toCode(t, m) {
4470
4606
  const { length } = this.data;
4471
- return columnCode(this, t, `bit(${length})`);
4607
+ return columnCode(this, t, `bit(${length})`, m);
4472
4608
  }
4473
4609
  toSQL() {
4474
4610
  return joinTruthy(
@@ -4480,13 +4616,14 @@ class BitColumn extends ColumnType {
4480
4616
  class BitVaryingColumn extends ColumnType {
4481
4617
  constructor(schema, length) {
4482
4618
  super(schema, schema.bit(length));
4483
- this.dataType = "bit varying";
4619
+ this.dataType = "varbit";
4484
4620
  this.operators = Operators.text;
4485
4621
  this.data.length = length;
4622
+ this.data.alias = "bitVarying";
4486
4623
  }
4487
- toCode(t) {
4624
+ toCode(t, m) {
4488
4625
  const { length } = this.data;
4489
- return columnCode(this, t, `bitVarying(${length != null ? length : ""})`);
4626
+ return columnCode(this, t, `bitVarying(${length != null ? length : ""})`, m);
4490
4627
  }
4491
4628
  toSQL() {
4492
4629
  return joinTruthy(
@@ -4502,8 +4639,8 @@ class TsVectorColumn extends ColumnType {
4502
4639
  this.dataType = "tsvector";
4503
4640
  this.operators = Operators.text;
4504
4641
  }
4505
- toCode(t) {
4506
- return columnCode(this, t, `tsvector()`);
4642
+ toCode(t, m) {
4643
+ return columnCode(this, t, `tsvector()`, m);
4507
4644
  }
4508
4645
  /**
4509
4646
  * For `tsvector` column type, it can also accept language (optional) and columns:
@@ -4533,14 +4670,17 @@ class TsVectorColumn extends ColumnType {
4533
4670
  const first = args[0];
4534
4671
  if (typeof first === "string" || !("raw" in first)) {
4535
4672
  const target = typeof first === "string" ? args[1] : first;
4673
+ const language = typeof first === "string" ? first : this.defaultLanguage;
4536
4674
  let sql;
4537
4675
  if (Array.isArray(target)) {
4538
4676
  const columns = target.length === 1 ? `"${target[0]}"` : target.map((column) => `coalesce("${column}", '')`).join(` || ' ' || `);
4539
- sql = `to_tsvector('${typeof first === "string" ? first : this.defaultLanguage}', ${columns})`;
4677
+ sql = `to_tsvector('${language}', ${columns})`;
4540
4678
  } else {
4541
4679
  for (const key in target) {
4542
- sql = (sql ? sql + " || " : "") + `setweight(to_tsvector(coalesce("${key}", '')), '${target[key]}')`;
4680
+ sql = (sql ? sql + " || " : "(") + `setweight(to_tsvector('${language}', coalesce("${key}", '')), '${target[key]}')`;
4543
4681
  }
4682
+ if (sql)
4683
+ sql += ")";
4544
4684
  }
4545
4685
  const arr = [sql];
4546
4686
  arr.raw = arr;
@@ -4555,8 +4695,8 @@ class TsQueryColumn extends ColumnType {
4555
4695
  this.dataType = "tsquery";
4556
4696
  this.operators = Operators.text;
4557
4697
  }
4558
- toCode(t) {
4559
- return columnCode(this, t, `tsquery()`);
4698
+ toCode(t, m) {
4699
+ return columnCode(this, t, `tsquery()`, m);
4560
4700
  }
4561
4701
  }
4562
4702
  const uuidDefaultSQL = "gen_random_uuid()";
@@ -4573,12 +4713,13 @@ class UUIDColumn extends ColumnType {
4573
4713
  column.data.default = uuidDefault;
4574
4714
  return column;
4575
4715
  }
4576
- toCode(t) {
4716
+ toCode(t, m) {
4577
4717
  const { data } = this;
4578
4718
  return columnCode(
4579
4719
  this,
4580
4720
  t,
4581
4721
  `uuid()`,
4722
+ m,
4582
4723
  // don't output the default default
4583
4724
  data.default instanceof RawSQLBase && data.default._sql === uuidDefaultSQL ? __spreadProps$5(__spreadValues$9({}, data), { default: void 0 }) : data
4584
4725
  );
@@ -4590,8 +4731,8 @@ class XMLColumn extends ColumnType {
4590
4731
  this.dataType = "xml";
4591
4732
  this.operators = Operators.text;
4592
4733
  }
4593
- toCode(t) {
4594
- return columnCode(this, t, `xml()`);
4734
+ toCode(t, m) {
4735
+ return columnCode(this, t, `xml()`, m);
4595
4736
  }
4596
4737
  }
4597
4738
  class CitextColumn extends TextBaseColumn {
@@ -4600,20 +4741,21 @@ class CitextColumn extends TextBaseColumn {
4600
4741
  this.dataType = "citext";
4601
4742
  setTextColumnData(this, min, max);
4602
4743
  }
4603
- toCode(t) {
4604
- return textColumnToCode(this, t);
4744
+ toCode(t, m) {
4745
+ return textColumnToCode(this, t, m);
4605
4746
  }
4606
4747
  }
4607
4748
 
4608
4749
  class BooleanColumn extends ColumnType {
4609
4750
  constructor(schema) {
4610
4751
  super(schema, schema.boolean());
4611
- this.dataType = "boolean";
4752
+ this.dataType = "bool";
4612
4753
  this.operators = Operators.boolean;
4613
4754
  this.parseItem = (input) => input[0] === "t";
4755
+ this.data.alias = "boolean";
4614
4756
  }
4615
- toCode(t) {
4616
- return columnCode(this, t, "boolean()");
4757
+ toCode(t, m) {
4758
+ return columnCode(this, t, "boolean()", m);
4617
4759
  }
4618
4760
  }
4619
4761
 
@@ -4629,8 +4771,8 @@ class CustomTypeColumn extends ColumnType {
4629
4771
  this.operators = Operators.any;
4630
4772
  this.data.isOfCustomType = true;
4631
4773
  }
4632
- toCode(t) {
4633
- return columnCode(this, t, `type(${singleQuote(this.dataType)})`);
4774
+ toCode(t, m) {
4775
+ return columnCode(this, t, `type(${singleQuote(this.dataType)})`, m);
4634
4776
  }
4635
4777
  as(column) {
4636
4778
  const c = setColumnData(
@@ -4645,8 +4787,8 @@ class CustomTypeColumn extends ColumnType {
4645
4787
  }
4646
4788
  }
4647
4789
  class DomainColumn extends CustomTypeColumn {
4648
- toCode(t) {
4649
- return columnCode(this, t, `domain(${singleQuote(this.dataType)})`);
4790
+ toCode(t, m) {
4791
+ return columnCode(this, t, `domain(${singleQuote(this.dataType)})`, m);
4650
4792
  }
4651
4793
  }
4652
4794
 
@@ -4825,7 +4967,7 @@ const makeColumnTypes = (schema) => {
4825
4967
  * See {@link ColumnType.searchIndex}
4826
4968
  */
4827
4969
  searchIndex(columns, options) {
4828
- return this.index(columns, __spreadProps$4(__spreadValues$8({}, options), { tsVector: true }));
4970
+ return this.index(columns, __spreadProps$4(__spreadValues$8({ using: "gin" }, options), { tsVector: true }));
4829
4971
  },
4830
4972
  constraint({ name, references, check, dropMode }) {
4831
4973
  var _a;
@@ -4856,11 +4998,11 @@ const makeColumnTypes = (schema) => {
4856
4998
  });
4857
4999
  return emptyObject;
4858
5000
  },
4859
- check(check) {
5001
+ check(check, options) {
4860
5002
  var _a;
4861
- ((_a = tableData.constraints) != null ? _a : tableData.constraints = []).push({
5003
+ ((_a = tableData.constraints) != null ? _a : tableData.constraints = []).push(__spreadProps$4(__spreadValues$8({}, options), {
4862
5004
  check
4863
- });
5005
+ }));
4864
5006
  return emptyObject;
4865
5007
  }
4866
5008
  }, makeTimestampsHelpers(makeRegexToFindInSql));
@@ -4979,6 +5121,8 @@ for (const key in types.builtins) {
4979
5121
  delete defaultTypeParsers[id];
4980
5122
  });
4981
5123
  const returnArg = (arg) => arg;
5124
+ const rollbackSql$1 = { text: "ROLLBACK" };
5125
+ const commitSql$1 = { text: "COMMIT" };
4982
5126
  class Adapter {
4983
5127
  constructor(_a) {
4984
5128
  var _b = _a, { types: types2 = defaultTypeParsers } = _b, config = __objRest$1(_b, ["types"]);
@@ -5020,7 +5164,7 @@ class Adapter {
5020
5164
  arrays(query, types2) {
5021
5165
  return performQuery$1(this, query, types2, "array");
5022
5166
  }
5023
- async transaction(begin, cb) {
5167
+ async transaction(begin, cb, end = commitSql$1) {
5024
5168
  const client = await this.connect();
5025
5169
  try {
5026
5170
  await setSearchPath(client, this.schema);
@@ -5029,10 +5173,10 @@ class Adapter {
5029
5173
  try {
5030
5174
  result = await cb(new TransactionAdapter(this, client, this.types));
5031
5175
  } catch (err) {
5032
- await performQueryOnClient(client, { text: "ROLLBACK" }, this.types);
5176
+ await performQueryOnClient(client, rollbackSql$1, this.types);
5033
5177
  throw err;
5034
5178
  }
5035
- await performQueryOnClient(client, { text: "COMMIT" }, this.types);
5179
+ await performQueryOnClient(client, end, this.types);
5036
5180
  return result;
5037
5181
  } finally {
5038
5182
  client.release();
@@ -6044,12 +6188,15 @@ const _queryCreateMany = (q, data) => {
6044
6188
  };
6045
6189
  const _queryInsertMany = (q, data) => {
6046
6190
  const ctx = createCtx();
6047
- return insert(
6191
+ let result = insert(
6048
6192
  q,
6049
6193
  handleManyData(q, data, ctx),
6050
6194
  "object",
6051
6195
  true
6052
6196
  );
6197
+ if (!data.length)
6198
+ result = result.none();
6199
+ return result;
6053
6200
  };
6054
6201
  const _queryCreateRaw = (q, args) => {
6055
6202
  createSelect(q);
@@ -7947,7 +8094,7 @@ const makeMessage = (colors, timeColor, time, sqlColor, sql, valuesColor, values
7947
8094
  const elapsed = process.hrtime(time);
7948
8095
  const formattedTime = `(${elapsed[0] ? `${elapsed[0]}s ` : ""}${(elapsed[1] / 1e6).toFixed(1)}ms)`;
7949
8096
  const result = `${colors ? timeColor(formattedTime) : formattedTime} ${colors ? sqlColor(sql) : sql}`;
7950
- if (!values.length) {
8097
+ if (!(values == null ? void 0 : values.length)) {
7951
8098
  return result;
7952
8099
  }
7953
8100
  const formattedValues = `[${values.map(quote).join(", ")}]`;
@@ -10718,7 +10865,7 @@ class QueryMethods {
10718
10865
  * ```
10719
10866
  */
10720
10867
  none() {
10721
- return extendQuery(this, noneMethods);
10868
+ return this.then === noneMethods.then ? this : extendQuery(this, noneMethods);
10722
10869
  }
10723
10870
  /**
10724
10871
  * `modify` allows modifying the query with your function:
@@ -10905,21 +11052,23 @@ var __objRest = (source, exclude) => {
10905
11052
  };
10906
11053
  const anyShape = {};
10907
11054
  class Db {
10908
- constructor(adapter, queryBuilder, table = void 0, shape = anyShape, columnTypes, transactionStorage, options) {
11055
+ constructor(adapter, queryBuilder, table = void 0, shape = anyShape, columnTypes, transactionStorage, options, tableData = getTableData()) {
10909
11056
  this.adapter = adapter;
10910
11057
  this.queryBuilder = queryBuilder;
10911
11058
  this.table = table;
10912
11059
  this.shape = shape;
10913
11060
  this.columnTypes = columnTypes;
11061
+ this.tableData = tableData;
10914
11062
  var _a, _b;
10915
11063
  const self = this;
10916
11064
  const { softDelete } = options;
10917
11065
  const scopes = options.scopes || softDelete ? {} : emptyObject;
10918
- const tableData = getTableData();
10919
11066
  this.internal = __spreadProps(__spreadValues({}, tableData), {
10920
11067
  transactionStorage,
10921
11068
  scopes,
10922
- snakeCase: options.snakeCase
11069
+ snakeCase: options.snakeCase,
11070
+ noPrimaryKey: options.noPrimaryKey === "ignore",
11071
+ comment: options.comment
10923
11072
  });
10924
11073
  this.baseQuery = this;
10925
11074
  const logger = options.logger || console;
@@ -10987,7 +11136,7 @@ class Db {
10987
11136
  this.q.schema = options.schema;
10988
11137
  }
10989
11138
  this.primaryKeys = Object.keys(shape).filter(
10990
- (key) => shape[key].data.isPrimaryKey
11139
+ (key) => shape[key].data.primaryKey
10991
11140
  );
10992
11141
  const primaryKeysFromData = (_b = getTableData().primaryKey) == null ? void 0 : _b.columns;
10993
11142
  if (primaryKeysFromData)
@@ -11183,16 +11332,13 @@ const createDb = (_a) => {
11183
11332
  ct[snakeCaseKey] = true;
11184
11333
  }
11185
11334
  const transactionStorage = new AsyncLocalStorage();
11186
- const qb = new Db(
11335
+ const qb = _initQueryBuilder(
11187
11336
  adapter,
11188
- void 0,
11189
- void 0,
11190
- anyShape,
11191
11337
  ct,
11192
11338
  transactionStorage,
11193
- commonOptions
11339
+ commonOptions,
11340
+ options
11194
11341
  );
11195
- qb.queryBuilder = qb;
11196
11342
  const tableConstructor = (table, shape, options2) => new Db(
11197
11343
  adapter,
11198
11344
  qb,
@@ -11211,6 +11357,33 @@ const createDb = (_a) => {
11211
11357
  }
11212
11358
  return db;
11213
11359
  };
11360
+ const _initQueryBuilder = (adapter, columnTypes, transactionStorage, commonOptions, options) => {
11361
+ const qb = new Db(
11362
+ adapter,
11363
+ void 0,
11364
+ void 0,
11365
+ anyShape,
11366
+ columnTypes,
11367
+ transactionStorage,
11368
+ commonOptions,
11369
+ emptyObject
11370
+ );
11371
+ if (options.extensions) {
11372
+ const arr = [];
11373
+ for (const x of options.extensions) {
11374
+ if (typeof x === "string") {
11375
+ arr.push({ name: x });
11376
+ } else {
11377
+ for (const key in x) {
11378
+ arr.push({ name: key, version: x[key] });
11379
+ }
11380
+ }
11381
+ }
11382
+ qb.internal.extensions = arr;
11383
+ }
11384
+ qb.internal.domains = options.domains;
11385
+ return qb.queryBuilder = qb;
11386
+ };
11214
11387
 
11215
11388
  class Rollback extends Error {
11216
11389
  }
@@ -11343,5 +11516,5 @@ function copyTableData(query, arg) {
11343
11516
  return q;
11344
11517
  }
11345
11518
 
11346
- 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 };
11519
+ export { Adapter, AggregateMethods, ArrayColumn, AsMethods, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CharColumn, CidrColumn, CircleColumn, CitextColumn, Clear, ColumnRefExpression, ColumnType, Create, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DecimalColumn, Delete, DomainColumn, DoublePrecisionColumn, DynamicRawSQL, EnumColumn, FnExpression, For, From, Having, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, Join, JsonMethods, JsonModifiers, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, OnConflictQueryBuilder, OnMethods, Operators, OrchidOrmError, OrchidOrmInternalError, PathColumn, PointColumn, PolygonColumn, QueryBase, QueryError, QueryGet, QueryHooks, QueryLog, QueryMethods, QueryUpsertOrCreate, RawSQL, RawSqlMethods, RealColumn, SearchMethods, Select, SerialColumn, SmallIntColumn, SmallSerialColumn, StringColumn, TextBaseColumn, TextColumn, Then, TimeColumn, TimestampColumn, TimestampTZColumn, Transaction, TransactionAdapter, TransformMethods, TsQueryColumn, TsVectorColumn, UUIDColumn, UnhandledTypeError, Union, UnknownColumn, Update, VarCharColumn, VirtualColumn, Where, With, XMLColumn, _initQueryBuilder, _queryAfterSaveCommit, _queryAll, _queryAs, _queryChangeCounter, _queryCreate, _queryCreateFrom, _queryCreateMany, _queryCreateManyFrom, _queryCreateManyRaw, _queryCreateRaw, _queryDefaults, _queryDelete, _queryExec, _queryFindBy, _queryFindByOptional, _queryGet, _queryGetOptional, _queryHookAfterCreate, _queryHookAfterCreateCommit, _queryHookAfterDelete, _queryHookAfterDeleteCommit, _queryHookAfterQuery, _queryHookAfterSave, _queryHookAfterUpdate, _queryHookAfterUpdateCommit, _queryHookBeforeCreate, _queryHookBeforeDelete, _queryHookBeforeQuery, _queryHookBeforeSave, _queryHookBeforeUpdate, _queryInsert, _queryInsertFrom, _queryInsertMany, _queryInsertManyFrom, _queryInsertManyRaw, _queryInsertRaw, _queryJoinOn, _queryJoinOnJsonPathEquals, _queryJoinOrOn, _queryOr, _queryOrNot, _queryRows, _querySelect, _queryTake, _queryTakeOptional, _queryUpdate, _queryUpdateOrThrow, _queryUpdateRaw, _queryWhere, _queryWhereExists, _queryWhereIn, _queryWhereNot, _queryWhereNotSql, _queryWhereSql, addComputedColumns, addParserForRawExpression, addParserForSelectItem, addQueryOn, anyShape, checkIfASimpleQuery, cloneQuery, cloneQueryBaseUnscoped, columnCheckToCode, columnCode, columnForeignKeysToCode, columnIndexesToCode, columnsShapeToCode, constraintInnerToCode, constraintPropsToCode, constraintToCode, copyTableData, countSelect, createDb, defaultSchemaConfig, extendQuery, foreignKeyArgumentToCode, getClonedQueryData, getColumnInfo, getColumnTypes, getConstraintKind, getQueryAs, getShapeFromSelect, getTableData, handleResult, identityToCode, indexInnerToCode, indexToCode, instantiateColumn, isDefaultTimeStamp, isQueryReturnsAll, isSelectingCount, joinSubQuery, logColors, logParamToLogObject, makeColumnTypes, makeColumnsByType, makeExpression, makeFnExpression, makeRegexToFindInSql, makeSQL, newTableData, parseRecord, parseResult, primaryKeyInnerToCode, primaryKeyToCode, processSelectArg, pushLimitSQL, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, queryFrom, queryFromSql, queryJson, queryMethodByReturnType, queryTypeWithLimitOne, queryWrap, quote, quoteString, raw, referencesArgsToCode, resetTableData, resolveSubQueryCallback, saveSearchAlias, setParserForSelectedString, setQueryObjectValue, setQueryOperators, simplifyColumnDefault, sqlQueryArgsToExpression, templateLiteralToSQL, testTransaction, throwIfNoWhere, toSQL, toSQLCacheKey };
11347
11520
  //# sourceMappingURL=index.mjs.map