pqb 0.56.4 → 0.56.6

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, emptyObject, isTemplateLiteralArgs, ColumnTypeBase, setColumnData, pushColumnData, templateLiteralSQLToCode, quoteObjectKey, toArray, emptyArray, singleQuote, addCode, singleQuoteArray, objectHasValues, toSnakeCase, columnDefaultArgumentToCode, columnErrorMessagesToCode, setObjectValueImmutable, getValueKey, addValue, isExpression, dateDataToCode, joinTruthy, arrayDataToCode, numberDataToCode, noop, stringDataToCode, getDefaultLanguage, setDefaultNowFn, setDefaultLanguage, setCurrentColumnName, timestampHelpers, _getQueryAliasOrName, _getQueryOuterAliases, returnArg, pushQueryValueImmutable, NotFoundError, OrchidOrmInternalError, _setSubQueryAliases, _applyRelationAliases, isRelationQuery, _checkIfAliased, logColors, OrchidOrmError, applyTransforms, callWithThis, requirePrimaryKeys, pick, getFreeAlias, _setQueryAs, _copyQueryAliasToQuery, setParserToQuery, newDelayedRelationSelect, pushOrNewArray, getPrimaryKeys, setDelayedRelation, UnhandledTypeError, isRawSQL, pushOrNewArrayToObjectImmutable, QueryHookUtils, MoreThanOneRowError, isObjectEmpty, ValExpression, applyMixins, _getQueryAs, _setQueryAlias, QueryError, snakeCaseKey } from 'orchid-core';
1
+ import { ExpressionTypeMethod, Expression, RawSQLBase, emptyObject, isTemplateLiteralArgs, ColumnTypeBase, setColumnData, pushColumnData, templateLiteralSQLToCode, quoteObjectKey, toArray, emptyArray, singleQuote, addCode, singleQuoteArray, objectHasValues, toSnakeCase, columnDefaultArgumentToCode, columnErrorMessagesToCode, setObjectValueImmutable, getValueKey, addValue, isExpression, dateDataToCode, joinTruthy, arrayDataToCode, numberDataToCode, noop, stringDataToCode, getDefaultLanguage, setDefaultNowFn, setDefaultLanguage, setCurrentColumnName, timestampHelpers, _getQueryAliasOrName, _getQueryOuterAliases, returnArg, pushQueryValueImmutable, NotFoundError, OrchidOrmInternalError, _setSubQueryAliases, _applyRelationAliases, isRelationQuery, getFreeAlias, _checkIfAliased, logColors, OrchidOrmError, applyTransforms, callWithThis, requirePrimaryKeys, pick, _setQueryAs, _copyQueryAliasToQuery, setParserToQuery, newDelayedRelationSelect, pushOrNewArray, getPrimaryKeys, setDelayedRelation, UnhandledTypeError, isRawSQL, pushOrNewArrayToObjectImmutable, _getQueryFreeAlias, _setQueryAlias, QueryHookUtils, MoreThanOneRowError, isObjectEmpty, ValExpression, applyMixins, _getQueryAs, QueryError, snakeCaseKey } from 'orchid-core';
2
2
  import { inspect } from 'node:util';
3
3
  import { AsyncLocalStorage } from 'node:async_hooks';
4
4
  import { templateLiteralToSQL as templateLiteralToSQL$1 } from 'pqb';
@@ -167,9 +167,7 @@ class ColumnType extends ColumnTypeBase {
167
167
  * // options are described below:
168
168
  * name: t.text().index({ ...options }),
169
169
  * // with a database-level name:
170
- * name: t.text().index('custom_index_name'),
171
- * // with name and options:
172
- * name: t.text().index('custom_index_name', { ...options }),
170
+ * name: t.text().index({ name: 'custom_index_name', ...indexOptions }),
173
171
  * }));
174
172
  * });
175
173
  * ```
@@ -178,6 +176,7 @@ class ColumnType extends ColumnTypeBase {
178
176
  *
179
177
  * ```ts
180
178
  * type IndexOptions = {
179
+ * name?: string,
181
180
  * // NULLS NOT DISTINCT: availabe in Postgres 15+, makes sense only for unique index
182
181
  * nullsNotDistinct?: true;
183
182
  * // index algorithm to use such as GIST, GIN
@@ -204,9 +203,9 @@ class ColumnType extends ColumnTypeBase {
204
203
  * @param args
205
204
  */
206
205
  index(...args) {
206
+ const a = args;
207
207
  return pushColumnData(this, "indexes", {
208
- options: (typeof args[0] === "string" ? args[1] : args[0]) ?? emptyObject,
209
- name: typeof args[0] === "string" ? args[0] : void 0
208
+ options: (typeof a[0] === "string" ? { ...a[1], name: a[0] } : a[0]) ?? emptyObject
210
209
  });
211
210
  }
212
211
  /**
@@ -312,21 +311,21 @@ class ColumnType extends ColumnTypeBase {
312
311
  * @param options - index options
313
312
  */
314
313
  searchIndex(...args) {
314
+ const a = args;
315
315
  return pushColumnData(this, "indexes", {
316
316
  options: {
317
- ...typeof args[0] === "string" ? args[1] : args[0],
317
+ ...typeof a[0] === "string" ? { ...a[1], name: a[0] } : a[0],
318
318
  ...this.dataType === "tsvector" ? { using: "GIN" } : { tsVector: true }
319
- },
320
- name: typeof args[0] === "string" ? args[0] : void 0
319
+ }
321
320
  });
322
321
  }
323
322
  unique(...args) {
323
+ const a = args;
324
324
  return pushColumnData(this, "indexes", {
325
325
  options: {
326
- ...typeof args[0] === "string" ? args[1] : args[0],
326
+ ...typeof a[0] === "string" ? { ...a[1], name: a[0] } : a[0],
327
327
  unique: true
328
- },
329
- name: typeof args[0] === "string" ? args[0] : void 0
328
+ }
330
329
  });
331
330
  }
332
331
  /**
@@ -374,11 +373,11 @@ class ColumnType extends ColumnTypeBase {
374
373
  * }
375
374
  * ```
376
375
  */
377
- exclude(...args) {
376
+ exclude(op, ...args) {
377
+ const a = args;
378
378
  return pushColumnData(this, "excludes", {
379
- with: args[0],
380
- options: (typeof args[1] === "string" ? args[2] : args[1]) ?? emptyObject,
381
- name: typeof args[1] === "string" ? args[1] : void 0
379
+ with: op,
380
+ options: (typeof a[0] === "string" ? { ...a[1], name: a[0] } : a[0]) ?? emptyObject
382
381
  });
383
382
  }
384
383
  comment(comment) {
@@ -539,6 +538,7 @@ const indexInnerToCode = (index, t) => {
539
538
  const columnOptions = ["collate", "opclass", "order", "weight"];
540
539
  const indexOptionsKeys = [
541
540
  index.options.tsVector ? "unique" : void 0,
541
+ "name",
542
542
  "using",
543
543
  "nullsNotDistinct",
544
544
  "include",
@@ -584,18 +584,12 @@ const indexInnerToCode = (index, t) => {
584
584
  objects.push("{", props, "},");
585
585
  }
586
586
  }
587
- code.push(["[", objects, hasOptions || index.name ? "]," : "]"]);
588
- if (index.name) {
589
- addCode(code, ` ${singleQuote(index.name)},`);
590
- }
587
+ code.push(["[", objects, hasOptions ? "]," : "]"]);
591
588
  } else {
592
589
  addCode(
593
590
  code,
594
591
  `[${index.columns.map((it) => singleQuote(it.column)).join(", ")}]`
595
592
  );
596
- if (index.name) {
597
- addCode(code, `, ${singleQuote(index.name)}`);
598
- }
599
593
  }
600
594
  if (hasOptions) {
601
595
  if (columnsMultiline) {
@@ -631,6 +625,7 @@ const excludeInnerToCode = (item, t) => {
631
625
  const code = [`${t}.exclude(`];
632
626
  const columnOptions = ["collate", "opclass", "order", "with"];
633
627
  const optionsKeys = [
628
+ "name",
634
629
  "using",
635
630
  "include",
636
631
  "with",
@@ -655,10 +650,7 @@ const excludeInnerToCode = (item, t) => {
655
650
  }
656
651
  objects.push("{", props, "},");
657
652
  }
658
- code.push(["[", objects, hasOptions || item.name ? "]," : "]"]);
659
- if (item.name) {
660
- addCode(code, ` ${singleQuote(item.name)},`);
661
- }
653
+ code.push(["[", objects, hasOptions ? "]," : "]"]);
662
654
  if (hasOptions) {
663
655
  code.push(["{"]);
664
656
  const options = [];
@@ -766,12 +758,10 @@ const foreignKeyArgumentToCode = ({
766
758
  };
767
759
  const columnIndexesToCode = (items) => {
768
760
  const code = [];
769
- for (const { options, name } of items) {
770
- addCode(
771
- code,
772
- `.${options.unique ? "unique" : "index"}(${name ? `${singleQuote(name)}` : ""}`
773
- );
761
+ for (const { options } of items) {
762
+ addCode(code, `.${options.unique ? "unique" : "index"}(`);
774
763
  const arr = [
764
+ options.name && `name: ${singleQuote(options.name)},`,
775
765
  options.collate && `collate: ${singleQuote(options.collate)},`,
776
766
  options.opclass && `opclass: ${singleQuote(options.opclass)},`,
777
767
  options.order && `order: ${singleQuote(options.order)},`,
@@ -783,7 +773,7 @@ const columnIndexesToCode = (items) => {
783
773
  options.where && `where: ${singleQuote(options.where)},`
784
774
  ].filter((x) => !!x);
785
775
  if (arr.length) {
786
- addCode(code, name ? `, {` : "{");
776
+ addCode(code, "{");
787
777
  addCode(code, arr);
788
778
  addCode(code, "}");
789
779
  }
@@ -793,13 +783,13 @@ const columnIndexesToCode = (items) => {
793
783
  };
794
784
  const columnExcludesToCode = (items) => {
795
785
  const code = [];
796
- for (const { options, name, with: w } of items) {
786
+ for (const { options, with: w } of items) {
797
787
  addCode(code, `.exclude('${w}'`);
798
788
  const arr = [
789
+ options.name && `name: ${singleQuote(options.name)},`,
799
790
  options.collate && `collate: ${singleQuote(options.collate)},`,
800
791
  options.opclass && `opclass: ${singleQuote(options.opclass)},`,
801
792
  options.order && `order: ${singleQuote(options.order)},`,
802
- name && `name: ${singleQuote(name)},`,
803
793
  options.using && `using: ${singleQuote(options.using)},`,
804
794
  options.include && `include: ${typeof options.include === "string" ? singleQuote(options.include) : `[${options.include.map(singleQuote).join(", ")}]`},`,
805
795
  options.with && `with: ${singleQuote(options.with)},`,
@@ -878,7 +868,9 @@ const columnCode = (type, ctx, key, code) => {
878
868
  }
879
869
  if (data.explicitSelect) addCode(code, ".select(false)");
880
870
  if (data.isNullable) addCode(code, ".nullable()");
881
- if (data.as) addCode(code, `.as(${data.as.toCode(ctx, key)})`);
871
+ if (data.as && !ctx.migration) {
872
+ addCode(code, `.as(${data.as.toCode(ctx, key)})`);
873
+ }
882
874
  if (data.default !== void 0 && data.default !== data.defaultDefault && (!ctx.migration || typeof data.default !== "function")) {
883
875
  addCode(
884
876
  code,
@@ -1187,6 +1179,17 @@ const quoteJsonValue = (arg, ctx, quotedAs, IN) => {
1187
1179
  }
1188
1180
  return addValue(ctx.values, JSON.stringify(arg)) + "::jsonb";
1189
1181
  };
1182
+ const serializeJsonValue = (arg, ctx, quotedAs) => {
1183
+ if (arg && typeof arg === "object") {
1184
+ if (isExpression(arg)) {
1185
+ return "to_jsonb(" + arg.toSQL(ctx, quotedAs) + ")";
1186
+ }
1187
+ if ("toSQL" in arg) {
1188
+ return `to_jsonb((${getSqlText(arg.toSQL(ctx))}))`;
1189
+ }
1190
+ }
1191
+ return addValue(ctx.values, JSON.stringify(arg));
1192
+ };
1190
1193
  const json = {
1191
1194
  equals: make(
1192
1195
  (key, value, ctx, quotedAs) => value === null ? `nullif(${key}, 'null'::jsonb) IS NULL` : `${key} = ${quoteJsonValue(value, ctx, quotedAs)}`
@@ -1229,21 +1232,24 @@ const json = {
1229
1232
  (key, value, ctx, quotedAs) => `${key} <@ ${quoteValue(value, ctx, quotedAs)}`
1230
1233
  ),
1231
1234
  jsonSet: makeVarArg(
1232
- (key, [path, value], ctx) => `jsonb_set(${key}, ${encodeJsonPath(ctx, path)}, ${addValue(
1233
- ctx.values,
1234
- JSON.stringify(value)
1235
+ (key, [path, value], ctx, quotedAs) => `jsonb_set(${key}, ${encodeJsonPath(ctx, path)}, ${serializeJsonValue(
1236
+ value,
1237
+ ctx,
1238
+ quotedAs
1235
1239
  )})`
1236
1240
  ),
1237
1241
  jsonReplace: makeVarArg(
1238
- (key, [path, value], ctx) => `jsonb_set(${key}, ${encodeJsonPath(ctx, path)}, ${addValue(
1239
- ctx.values,
1240
- JSON.stringify(value)
1242
+ (key, [path, value], ctx, quotedAs) => `jsonb_set(${key}, ${encodeJsonPath(ctx, path)}, ${serializeJsonValue(
1243
+ value,
1244
+ ctx,
1245
+ quotedAs
1241
1246
  )}, false)`
1242
1247
  ),
1243
1248
  jsonInsert: makeVarArg(
1244
- (key, [path, value, options], ctx) => `jsonb_insert(${key}, ${encodeJsonPath(ctx, path)}, ${addValue(
1245
- ctx.values,
1246
- JSON.stringify(value)
1249
+ (key, [path, value, options], ctx, quotedAs) => `jsonb_insert(${key}, ${encodeJsonPath(ctx, path)}, ${serializeJsonValue(
1250
+ value,
1251
+ ctx,
1252
+ quotedAs
1247
1253
  )}${options?.after ? ", true" : ""})`
1248
1254
  ),
1249
1255
  jsonRemove: makeVarArg(
@@ -4233,14 +4239,7 @@ const throwIfJoinLateral = (q, method) => {
4233
4239
  };
4234
4240
  const saveAliasedShape = (q, as, key) => {
4235
4241
  const shapes = q.q[key];
4236
- if (shapes?.[as]) {
4237
- let suffix = 2;
4238
- let name;
4239
- while (shapes[name = `${as}${suffix}`]) {
4240
- suffix++;
4241
- }
4242
- as = name;
4243
- }
4242
+ as = getFreeAlias(shapes, as);
4244
4243
  setQueryObjectValueImmutable(q, key, as, emptyObject);
4245
4244
  return as;
4246
4245
  };
@@ -6352,15 +6351,26 @@ const pushWithSql = (ctx, items) => {
6352
6351
  const sql = withToSql(ctx, items);
6353
6352
  if (sql) ctx.sql.push("WITH", sql);
6354
6353
  };
6354
+ const pushOrAppendWithSql = (ctx, query, items) => {
6355
+ const sql = withToSql(ctx, items);
6356
+ if (sql) {
6357
+ if (query.with) {
6358
+ ctx.sql[ctx.sql.length - 1] += ",";
6359
+ } else {
6360
+ ctx.sql.push("WITH");
6361
+ }
6362
+ ctx.sql.push(sql);
6363
+ }
6364
+ };
6355
6365
 
6356
6366
  const makeInsertSql = (ctx, q, query, quotedAs) => {
6357
6367
  let { columns } = query;
6358
6368
  const { shape, inCTE, hookCreateSet } = query;
6359
6369
  const QueryClass = ctx.qb.constructor;
6360
- let values = query.values;
6370
+ let { insertFrom, queryColumnsCount, values } = query;
6361
6371
  let hookSetSql;
6362
6372
  if (hookCreateSet) {
6363
- ({ hookSetSql, columns, values } = processHookSet(
6373
+ ({ hookSetSql, columns, insertFrom, queryColumnsCount, values } = processHookSet(
6364
6374
  ctx,
6365
6375
  q,
6366
6376
  values,
@@ -6379,6 +6389,7 @@ const makeInsertSql = (ctx, q, query, quotedAs) => {
6379
6389
  for (const key of q.internal.runtimeDefaultColumns) {
6380
6390
  if (!columns.includes(key)) {
6381
6391
  const column = shape[key];
6392
+ columns.push(key);
6382
6393
  quotedColumns.push(`"${column.data.name || key}"`);
6383
6394
  runtimeDefaults.push(column.data.runtimeDefault);
6384
6395
  }
@@ -6396,8 +6407,22 @@ const makeInsertSql = (ctx, q, query, quotedAs) => {
6396
6407
  }
6397
6408
  const insertSql = `INSERT INTO ${quotedAs}${quotedColumns.length ? "(" + quotedColumns.join(", ") + ")" : ""}`;
6398
6409
  const hasNonSelect = ctx.hasNonSelect;
6399
- if ("from" in values && query.insertWith) {
6400
- pushWithSql(ctx, Object.values(query.insertWith).flat());
6410
+ let hasWith = !!query.with;
6411
+ if (insertFrom) {
6412
+ if (values.length < 2) {
6413
+ if (query.insertWith) {
6414
+ hasWith = true;
6415
+ pushOrAppendWithSql(ctx, query, Object.values(query.insertWith).flat());
6416
+ }
6417
+ } else {
6418
+ hasWith = true;
6419
+ pushOrAppendWithSql(ctx, query, [
6420
+ {
6421
+ n: getQueryAs(insertFrom),
6422
+ q: insertFrom
6423
+ }
6424
+ ]);
6425
+ }
6401
6426
  }
6402
6427
  const valuesPos = ctx.sql.length + 1;
6403
6428
  ctx.sql.push(insertSql, null);
@@ -6473,28 +6498,38 @@ const makeInsertSql = (ctx, q, query, quotedAs) => {
6473
6498
  );
6474
6499
  }
6475
6500
  if (returning.select) ctx.sql.push("RETURNING", returning.select);
6476
- if ("from" in values) {
6477
- const { from, values: v } = values;
6478
- const q2 = from.clone();
6479
- if (v) {
6480
- pushQueryValueImmutable(
6481
- q2,
6482
- "select",
6483
- new RawSQL(
6484
- encodeRow(
6485
- ctx,
6486
- ctx.values,
6487
- q2,
6488
- QueryClass,
6489
- v,
6490
- runtimeDefaults,
6491
- quotedAs
6501
+ let insertManyFromValuesAs;
6502
+ if (insertFrom) {
6503
+ if (values.length < 2) {
6504
+ const q2 = insertFrom.clone();
6505
+ if (values[0]?.length) {
6506
+ pushQueryValueImmutable(
6507
+ q2,
6508
+ "select",
6509
+ new RawSQL(
6510
+ encodeRow(
6511
+ ctx,
6512
+ ctx.values,
6513
+ q2,
6514
+ QueryClass,
6515
+ values[0],
6516
+ runtimeDefaults,
6517
+ quotedAs
6518
+ )
6492
6519
  )
6493
- )
6494
- );
6520
+ );
6521
+ }
6522
+ ctx.sql[valuesPos] = getSqlText(toSQL(q2, ctx));
6523
+ } else {
6524
+ insertManyFromValuesAs = query.insertValuesAs;
6525
+ const queryAs = getQueryAs(insertFrom);
6526
+ ctx.sql[valuesPos - 1] += ` SELECT "${queryAs}".*, ${columns.slice(queryColumnsCount || 0).map((key) => {
6527
+ const column = shape[key];
6528
+ return column ? `${insertManyFromValuesAs}."${column.data.name || key}"::${column.dataType}` : `${insertManyFromValuesAs}."${key}"`;
6529
+ }).join(", ")} FROM "${queryAs}",`;
6495
6530
  }
6496
- ctx.sql[valuesPos] = getSqlText(toSQL(q2, ctx));
6497
- } else {
6531
+ }
6532
+ if (!insertFrom || insertManyFromValuesAs) {
6498
6533
  const valuesSql = [];
6499
6534
  let ctxValues = ctx.values;
6500
6535
  const restValuesLen = ctxValues.length;
@@ -6503,6 +6538,8 @@ const makeInsertSql = (ctx, q, query, quotedAs) => {
6503
6538
  const { insertWith } = query;
6504
6539
  const { skipBatchCheck } = ctx;
6505
6540
  const withSqls = [];
6541
+ const startingKeyword = (insertManyFromValuesAs ? "(" : "") + (inCTE ? "SELECT " : "VALUES ");
6542
+ const valuesAppend = insertManyFromValuesAs ? `) ${insertManyFromValuesAs}(${quotedColumns.slice(queryColumnsCount || 0).join(", ")})` : "";
6506
6543
  for (let i = 0; i < values.length; i++) {
6507
6544
  const withes = insertWith?.[i];
6508
6545
  ctx.skipBatchCheck = true;
@@ -6526,11 +6563,8 @@ const makeInsertSql = (ctx, q, query, quotedAs) => {
6526
6563
  );
6527
6564
  }
6528
6565
  if (!skipBatchCheck) {
6529
- if (withSqls.length) {
6530
- ctx.sql[valuesPos - 1] = "WITH " + withSqls.join(", ") + " " + insertSql;
6531
- withSqls.length = 0;
6532
- }
6533
- ctx.sql[valuesPos] = (inCTE ? "SELECT " : "VALUES ") + valuesSql.join(", ");
6566
+ addWithSqls(ctx, hasWith, withSqls, valuesPos, insertSql);
6567
+ ctx.sql[valuesPos] = startingKeyword + valuesSql.join(", ") + valuesAppend;
6534
6568
  ctxValues.length = currentValuesLen;
6535
6569
  batch = pushOrNewArray(batch, {
6536
6570
  text: ctx.sql.join(" "),
@@ -6546,9 +6580,7 @@ const makeInsertSql = (ctx, q, query, quotedAs) => {
6546
6580
  if (withSql) withSqls.push(withSql);
6547
6581
  valuesSql.push(encodedRow);
6548
6582
  }
6549
- if (withSqls.length) {
6550
- ctx.sql[valuesPos - 1] = "WITH " + withSqls.join(", ") + " " + insertSql;
6551
- }
6583
+ addWithSqls(ctx, hasWith, withSqls, valuesPos, insertSql);
6552
6584
  if (batch) {
6553
6585
  if (hasNonSelect) {
6554
6586
  throw new OrchidOrmInternalError(
@@ -6556,7 +6588,7 @@ const makeInsertSql = (ctx, q, query, quotedAs) => {
6556
6588
  `Cannot insert many records when having a non-select sub-query`
6557
6589
  );
6558
6590
  }
6559
- ctx.sql[valuesPos] = (inCTE ? "SELECT " : "VALUES ") + valuesSql.join(", ");
6591
+ ctx.sql[valuesPos] = startingKeyword + valuesSql.join(", ") + valuesAppend;
6560
6592
  batch.push({
6561
6593
  text: ctx.sql.join(" "),
6562
6594
  values: ctxValues
@@ -6567,7 +6599,7 @@ const makeInsertSql = (ctx, q, query, quotedAs) => {
6567
6599
  batch
6568
6600
  };
6569
6601
  } else {
6570
- ctx.sql[valuesPos] = (inCTE ? "SELECT " : "VALUES ") + valuesSql.join(", ");
6602
+ ctx.sql[valuesPos] = startingKeyword + valuesSql.join(", ") + valuesAppend;
6571
6603
  }
6572
6604
  if (inCTE) {
6573
6605
  ctx.sql[valuesPos] += ' WHERE NOT EXISTS (SELECT 1 FROM "f")';
@@ -6580,6 +6612,15 @@ const makeInsertSql = (ctx, q, query, quotedAs) => {
6580
6612
  values: ctx.values
6581
6613
  };
6582
6614
  };
6615
+ const addWithSqls = (ctx, hasWith, withSqls, valuesPos, insertSql) => {
6616
+ if (withSqls.length) {
6617
+ if (hasWith) {
6618
+ ctx.sql[valuesPos - 2] += ",";
6619
+ }
6620
+ ctx.sql[valuesPos - 1] = (hasWith ? "" : "WITH ") + withSqls.join(", ") + " " + insertSql;
6621
+ withSqls.length = 0;
6622
+ }
6623
+ };
6583
6624
  const processHookSet = (ctx, q, values, hookCreateSet, columns, QueryClass, quotedAs) => {
6584
6625
  const hookSet = {};
6585
6626
  for (const item of hookCreateSet) {
@@ -6588,48 +6629,54 @@ const processHookSet = (ctx, q, values, hookCreateSet, columns, QueryClass, quot
6588
6629
  const addHookSetColumns = Object.keys(hookSet).filter(
6589
6630
  (key) => !columns.includes(key)
6590
6631
  );
6591
- if ("from" in values) {
6592
- const v = { ...values };
6593
- const newColumns = [];
6594
- const originalSelect = v.from.q.select;
6632
+ let insertFrom = q.q.insertFrom;
6633
+ if (insertFrom) {
6634
+ const newColumns = /* @__PURE__ */ new Set();
6635
+ const originalSelect = insertFrom.q.select;
6595
6636
  if (originalSelect) {
6596
- v.from = _clone(v.from);
6637
+ insertFrom = _clone(insertFrom);
6597
6638
  const select = [];
6598
6639
  for (const s of originalSelect) {
6599
6640
  if (typeof s === "string" && !hookSet[s]) {
6600
6641
  select.push(s);
6601
- newColumns.push(s);
6642
+ newColumns.add(s);
6602
6643
  } else if (typeof s === "object" && "selectAs" in s) {
6603
6644
  const filtered = {};
6604
6645
  for (const key in s.selectAs) {
6605
6646
  if (!hookSet[key]) {
6606
6647
  filtered[key] = s.selectAs[key];
6607
- newColumns.push(key);
6648
+ newColumns.add(key);
6608
6649
  }
6609
6650
  }
6610
6651
  select.push({ selectAs: filtered });
6611
6652
  }
6612
6653
  }
6613
- v.from.q.select = select;
6614
- }
6615
- let row;
6616
- if (v.values) {
6617
- const originalRow = v.values;
6618
- const valuesColumns = columns.slice(-originalRow.length);
6619
- row = [];
6620
- valuesColumns.forEach((c, i) => {
6621
- if (!hookSet[c]) {
6622
- newColumns.push(c);
6623
- row.push(originalRow[i]);
6624
- }
6654
+ insertFrom.q.select = select;
6655
+ }
6656
+ if (values.length) {
6657
+ const newValues = [];
6658
+ const valuesColumnsSet = /* @__PURE__ */ new Set();
6659
+ values.forEach((originalRow, i) => {
6660
+ const valuesColumns = columns.slice(-originalRow.length);
6661
+ const row = [];
6662
+ newValues[i] = row;
6663
+ valuesColumns.forEach((c, i2) => {
6664
+ if (!hookSet[c] && !newColumns.has(c)) {
6665
+ valuesColumnsSet.add(c);
6666
+ row.push(originalRow[i2]);
6667
+ }
6668
+ });
6625
6669
  });
6670
+ for (const valueColumn of valuesColumnsSet) {
6671
+ newColumns.add(valueColumn);
6672
+ }
6673
+ values = newValues;
6626
6674
  } else {
6627
- row = [];
6675
+ values = [[]];
6628
6676
  }
6629
- v.values = row;
6630
6677
  columns.forEach((column) => {
6631
6678
  if (column in hookSet) {
6632
- newColumns.push(column);
6679
+ newColumns.add(column);
6633
6680
  const fromHook = {
6634
6681
  fromHook: encodeValue(
6635
6682
  ctx,
@@ -6640,28 +6687,35 @@ const processHookSet = (ctx, q, values, hookCreateSet, columns, QueryClass, quot
6640
6687
  quotedAs
6641
6688
  )
6642
6689
  };
6643
- row.push(fromHook);
6690
+ for (const row of values) {
6691
+ row.push(fromHook);
6692
+ }
6644
6693
  }
6645
6694
  });
6695
+ const queryColumnsCount = insertFrom.q.select?.length;
6646
6696
  if (addHookSetColumns) {
6647
6697
  for (const key of addHookSetColumns) {
6648
- row.push({
6649
- fromHook: encodeValue(
6650
- ctx,
6651
- ctx.values,
6652
- q,
6653
- QueryClass,
6654
- hookSet[key],
6655
- quotedAs
6656
- )
6657
- });
6698
+ for (const row of values) {
6699
+ row.push({
6700
+ fromHook: encodeValue(
6701
+ ctx,
6702
+ ctx.values,
6703
+ q,
6704
+ QueryClass,
6705
+ hookSet[key],
6706
+ quotedAs
6707
+ )
6708
+ });
6709
+ }
6658
6710
  }
6659
6711
  return {
6660
6712
  columns: [...newColumns, ...addHookSetColumns],
6661
- values: v
6713
+ insertFrom,
6714
+ queryColumnsCount,
6715
+ values
6662
6716
  };
6663
6717
  }
6664
- return { columns: newColumns, values: v };
6718
+ return { columns: [...newColumns], insertFrom, queryColumnsCount, values };
6665
6719
  }
6666
6720
  columns.forEach((column, i) => {
6667
6721
  if (column in hookSet) {
@@ -6977,8 +7031,7 @@ const selectToSql = (ctx, table, query, quotedAs, hookSelect = query.hookSelect,
6977
7031
  hookSelect.delete(column);
6978
7032
  continue;
6979
7033
  }
6980
- let i = 2;
6981
- while (selected[name = `${column}${i}`]) i++;
7034
+ name = getFreeAlias(selected, column);
6982
7035
  item.as = name;
6983
7036
  item.temp = name;
6984
7037
  sql += ` "${name}"`;
@@ -8621,7 +8674,7 @@ class Union {
8621
8674
  }
8622
8675
  }
8623
8676
 
8624
- const addWith = (q, withStore, item, key = "with") => {
8677
+ const _addWith = (query, withStore, item, key = "with") => {
8625
8678
  if (item.q) {
8626
8679
  item.q.q.with?.forEach((item2, i, arr) => {
8627
8680
  if (item2?.q?.q.type) {
@@ -8632,7 +8685,8 @@ const addWith = (q, withStore, item, key = "with") => {
8632
8685
  if (item.q.q.insertWith) {
8633
8686
  const values = Object.values(item.q.q.insertWith).flat();
8634
8687
  item.q.q.insertWith = void 0;
8635
- q.q.with = q.q.with ? [...q.q.with, ...values] : values;
8688
+ const { q } = query;
8689
+ q.with = q.with ? [...q.with, ...values] : values;
8636
8690
  }
8637
8691
  }
8638
8692
  pushOrNewArrayToObjectImmutable(withStore, key, item);
@@ -8640,7 +8694,7 @@ const addWith = (q, withStore, item, key = "with") => {
8640
8694
  const moveQueryValueToWith = (q, withStore, value, withKey, set, key) => {
8641
8695
  if (value.q.type) {
8642
8696
  const as = saveAliasedShape(q, "q", "withShapes");
8643
- addWith(
8697
+ _addWith(
8644
8698
  q,
8645
8699
  withStore,
8646
8700
  {
@@ -8674,7 +8728,7 @@ class WithMethods {
8674
8728
  columns: Object.keys(query.shape)
8675
8729
  };
8676
8730
  }
8677
- addWith(q, q.q, { n: name, o: options, q: query });
8731
+ _addWith(q, q.q, { n: name, o: options, q: query });
8678
8732
  const shape = getShapeFromSelect(query, true);
8679
8733
  return setQueryObjectValueImmutable(q, "withShapes", name, {
8680
8734
  shape,
@@ -8700,7 +8754,7 @@ class WithMethods {
8700
8754
  columns: Object.keys(shape)
8701
8755
  };
8702
8756
  }
8703
- addWith(q, q.q, { n: name, o: options, q: query });
8757
+ _addWith(q, q.q, { n: name, o: options, q: query });
8704
8758
  return setQueryObjectValueImmutable(q, "withShapes", name, withConfig);
8705
8759
  }
8706
8760
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -8718,6 +8772,248 @@ class WithMethods {
8718
8772
  }
8719
8773
  }
8720
8774
 
8775
+ const insertFrom = (query, from, many, queryMany, data) => {
8776
+ const ctx = createCtx();
8777
+ const obj = data && (Array.isArray(data) ? handleManyData(query, data, ctx) : handleOneData(query, data, ctx));
8778
+ return insert(
8779
+ query,
8780
+ {
8781
+ insertFrom: from,
8782
+ columns: obj?.columns || [],
8783
+ values: obj?.values || []
8784
+ },
8785
+ many,
8786
+ queryMany
8787
+ );
8788
+ };
8789
+ const getFromSelectColumns = (q, from, obj, many) => {
8790
+ if (!many && !queryTypeWithLimitOne[from.q.returnType]) {
8791
+ throw new Error(
8792
+ "Cannot create based on a query which returns multiple records"
8793
+ );
8794
+ }
8795
+ const queryColumns = /* @__PURE__ */ new Set();
8796
+ from.q.select?.forEach((item) => {
8797
+ if (typeof item === "string") {
8798
+ const index = item.indexOf(".");
8799
+ queryColumns.add(index === -1 ? item : item.slice(index + 1));
8800
+ } else if (item && "selectAs" in item) {
8801
+ for (const column in item.selectAs) {
8802
+ queryColumns.add(column);
8803
+ }
8804
+ }
8805
+ });
8806
+ const allColumns = new Set(queryColumns);
8807
+ const queryColumnsCount = queryColumns.size;
8808
+ const allValues = [];
8809
+ if (obj?.columns) {
8810
+ for (const objectValues of obj.values) {
8811
+ const values = [];
8812
+ allValues.push(values);
8813
+ obj.columns.forEach((column, i) => {
8814
+ if (!queryColumns.has(column)) {
8815
+ allColumns.add(column);
8816
+ values.push(objectValues[i]);
8817
+ }
8818
+ });
8819
+ }
8820
+ }
8821
+ for (const key of queryColumns) {
8822
+ const column = q.shape[key];
8823
+ if (column) throwOnReadOnly$1(from, column, key);
8824
+ }
8825
+ return {
8826
+ columns: [...allColumns],
8827
+ queryColumnsCount,
8828
+ values: allValues
8829
+ };
8830
+ };
8831
+ const _queryCreateOneFrom = (q, query, data) => {
8832
+ createSelect(q);
8833
+ return insertFrom(q, query, false, false, data);
8834
+ };
8835
+ const _queryInsertOneFrom = (q, query, data) => {
8836
+ return insertFrom(q, query, false, false, data);
8837
+ };
8838
+ const _queryCreateManyFrom = (q, query, data) => {
8839
+ createSelect(q);
8840
+ return insertFrom(q, query, true, false, data);
8841
+ };
8842
+ const _queryInsertManyFrom = (q, query, data) => {
8843
+ return insertFrom(q, query, true, false, data);
8844
+ };
8845
+ const _queryCreateForEachFrom = (q, query) => {
8846
+ createSelect(q);
8847
+ return insertFrom(q, query, true, true);
8848
+ };
8849
+ const _queryInsertForEachFrom = (q, query) => {
8850
+ return insertFrom(q, query, true, true);
8851
+ };
8852
+ class QueryCreateFrom {
8853
+ /**
8854
+ * Inserts a single record based on a query that selects a single record.
8855
+ *
8856
+ * Performs a single SQL query based on `INSERT ... SELECT ... FROM`.
8857
+ *
8858
+ * See {@link createManyFrom} to insert multiple records based on a single record query,
8859
+ * and {@link createForEachFrom} to insert a record per every one found by the query.
8860
+ *
8861
+ * The first argument is a query of a **single** record, it should have `find`, `take`, or similar.
8862
+ *
8863
+ * The second optional argument is a data which will be merged with columns returned by the query.
8864
+ *
8865
+ * The data for the second argument is the same as in {@link create}.
8866
+ *
8867
+ * Columns with runtime defaults (defined with a callback) are supported here.
8868
+ * The value for such a column will be injected unless selected from a related table or provided in a data object.
8869
+ *
8870
+ * ```ts
8871
+ * const oneRecord = await db.table.createOneFrom(
8872
+ * db.relatedTable
8873
+ * // use select to map columns from one table to another
8874
+ * .select({
8875
+ * // relatedTable's id will be inserted as "relatedId"
8876
+ * relatedId: 'id',
8877
+ * })
8878
+ * .findBy({ key: 'value' }),
8879
+ * // optional argument:
8880
+ * {
8881
+ * key: 'value',
8882
+ * // supports sql, nested select, create, update, delete queries
8883
+ * fromSql: () => sql`custom sql`,
8884
+ * fromQuery: () => db.otherTable.find(id).update(data).get('column'),
8885
+ * fromRelated: (q) => q.relatedTable.create(data).get('column'),
8886
+ * },
8887
+ * );
8888
+ * ```
8889
+ *
8890
+ * The query above will produce such a SQL (omitting `from*` values):
8891
+ *
8892
+ * ```sql
8893
+ * INSERT INTO "table"("relatedId", "key")
8894
+ * SELECT "relatedTable"."id" AS "relatedId", 'value'
8895
+ * FROM "relatedTable"
8896
+ * WHERE "relatedTable"."key" = 'value'
8897
+ * LIMIT 1
8898
+ * RETURNING *
8899
+ * ```
8900
+ *
8901
+ * @param query - query to create new records from
8902
+ * @param data - additionally you can set some columns
8903
+ */
8904
+ createOneFrom(query, data) {
8905
+ return _queryCreateOneFrom(_clone(this), query, data);
8906
+ }
8907
+ /**
8908
+ * Works exactly as {@link createOneFrom}, except that it returns inserted row count by default.
8909
+ *
8910
+ * @param query - query to create new records from
8911
+ * @param data - additionally you can set some columns
8912
+ */
8913
+ insertOneFrom(query, data) {
8914
+ return _queryInsertOneFrom(_clone(this), query, data);
8915
+ }
8916
+ /**
8917
+ * Inserts multiple records based on a query that selects a single record.
8918
+ *
8919
+ * Performs a single SQL query based on `INSERT ... SELECT ... FROM`.
8920
+ *
8921
+ * See {@link createOneFrom} to insert a single record based on a single record query,
8922
+ * and {@link createForEachFrom} to insert a record per every one found by the query.
8923
+ *
8924
+ * The first argument is a query of a **single** record, it should have `find`, `take`, or similar.
8925
+ *
8926
+ * The second argument is array of objects to be merged with columns returned by the query.
8927
+ *
8928
+ * The data for the second argument is the same as in {@link createMany}.
8929
+ *
8930
+ * Columns with runtime defaults (defined with a callback) are supported here.
8931
+ * The value for such a column will be injected unless selected from a related table or provided in a data object.
8932
+ *
8933
+ * ```ts
8934
+ * const twoRecords = await db.table.createManyFrom(
8935
+ * db.relatedTable
8936
+ * // use select to map columns from one table to another
8937
+ * .select({
8938
+ * // relatedTable's id will be inserted as "relatedId"
8939
+ * relatedId: 'id',
8940
+ * })
8941
+ * .findBy({ key: 'value' }),
8942
+ * [
8943
+ * {
8944
+ * key: 'value 1',
8945
+ * // supports sql, nested select, create, update, delete queries
8946
+ * fromSql: () => sql`custom sql`,
8947
+ * fromQuery: () => db.otherTable.find(id).update(data).get('column'),
8948
+ * fromRelated: (q) => q.relatedTable.create(data).get('column'),
8949
+ * },
8950
+ * {
8951
+ * key: 'value 2',
8952
+ * },
8953
+ * ],
8954
+ * );
8955
+ * ```
8956
+ *
8957
+ * The query above will produce such a SQL (omitting `from*` values):
8958
+ *
8959
+ * ```sql
8960
+ * WITH "relatedTable" AS (
8961
+ * SELECT "relatedTable"."id" AS "relatedId", 'value'
8962
+ * FROM "relatedTable"
8963
+ * WHERE "relatedTable"."key" = 'value'
8964
+ * LIMIT 1
8965
+ * )
8966
+ * INSERT INTO "table"("relatedId", "key")
8967
+ * SELECT "relatedTable".*, v."key"::text
8968
+ * FROM "relatedTable", (VALUES ('value1'), ('value2')) v("key")
8969
+ * RETURNING *
8970
+ * ```
8971
+ *
8972
+ * @param query - query to create new records from
8973
+ * @param data - array of records to create
8974
+ */
8975
+ createManyFrom(query, data) {
8976
+ return _queryCreateManyFrom(_clone(this), query, data);
8977
+ }
8978
+ /**
8979
+ * Works exactly as {@link createManyFrom}, except that it returns inserted row count by default.
8980
+ *
8981
+ * @param query - query to create new records from
8982
+ * @param data - array of records to create
8983
+ */
8984
+ insertManyFrom(query, data) {
8985
+ return _queryInsertManyFrom(_clone(this), query, data);
8986
+ }
8987
+ /**
8988
+ * Inserts a single record per every record found in a given query.
8989
+ *
8990
+ * Performs a single SQL query based on `INSERT ... SELECT ... FROM`.
8991
+ *
8992
+ * Unlike {@link createOneFrom}, it doesn't accept second argument with data.
8993
+ *
8994
+ * Runtime defaults cannot work with it.
8995
+ *
8996
+ * ```ts
8997
+ * const manyRecords = await db.table.createForEachFrom(
8998
+ * RelatedTable.select({ relatedId: 'id' }).where({ key: 'value' }),
8999
+ * );
9000
+ * ```
9001
+ *
9002
+ * @param query - query to create new records from
9003
+ */
9004
+ createForEachFrom(query) {
9005
+ return _queryCreateForEachFrom(_clone(this), query);
9006
+ }
9007
+ /**
9008
+ * Works exactly as {@link createForEachFrom}, except that it returns inserted row count by default.
9009
+ *
9010
+ * @param query - query to create new records from
9011
+ */
9012
+ insertForEachFrom(query) {
9013
+ return _queryInsertForEachFrom(_clone(this), query);
9014
+ }
9015
+ }
9016
+
8721
9017
  const createSelect = (q) => {
8722
9018
  if (q.q.returnType === "void" || isSelectingCount(q)) {
8723
9019
  q.q.select = void 0;
@@ -8816,8 +9112,9 @@ const handleManyData = (q, data, ctx) => {
8816
9112
  };
8817
9113
  const insert = (self, {
8818
9114
  columns,
9115
+ insertFrom,
8819
9116
  values
8820
- }, many) => {
9117
+ }, many, queryMany) => {
8821
9118
  const { q } = self;
8822
9119
  if (!q.select?.length) {
8823
9120
  q.returning = true;
@@ -8826,6 +9123,28 @@ const insert = (self, {
8826
9123
  delete q.or;
8827
9124
  delete q.scopes;
8828
9125
  q.type = "insert";
9126
+ insertFrom = insertFrom ? q.insertFrom = insertFrom : q.insertFrom;
9127
+ if (insertFrom) {
9128
+ if (q.insertFrom) {
9129
+ const obj = getFromSelectColumns(
9130
+ self,
9131
+ q.insertFrom,
9132
+ {
9133
+ columns,
9134
+ values
9135
+ },
9136
+ queryMany
9137
+ );
9138
+ columns = obj.columns;
9139
+ values = obj.values;
9140
+ q.queryColumnsCount = obj.queryColumnsCount;
9141
+ }
9142
+ if (values.length > 1) {
9143
+ const insertValuesAs = _getQueryFreeAlias(q, "v");
9144
+ _setQueryAlias(self, "v", insertValuesAs);
9145
+ q.insertValuesAs = insertValuesAs;
9146
+ }
9147
+ }
8829
9148
  q.columns = columns;
8830
9149
  q.values = values;
8831
9150
  const { select, returnType } = q;
@@ -8841,63 +9160,20 @@ const insert = (self, {
8841
9160
  q.returnType = "pluck";
8842
9161
  }
8843
9162
  } else if (!returnType || returnType === "all") {
8844
- q.returnType = "from" in values ? values.from.q.returnType : "one";
9163
+ q.returnType = insertFrom ? insertFrom.q.returnType : "one";
8845
9164
  } else if (returnType === "pluck") {
8846
9165
  q.returnType = "valueOrThrow";
8847
9166
  }
8848
9167
  return self;
8849
9168
  };
8850
- const getFromSelectColumns = (q, from, obj, many) => {
8851
- if (!many && !queryTypeWithLimitOne[from.q.returnType]) {
8852
- throw new Error(
8853
- "Cannot create based on a query which returns multiple records"
8854
- );
8855
- }
8856
- const queryColumns = [];
8857
- from.q.select?.forEach((item) => {
8858
- if (typeof item === "string") {
8859
- const index = item.indexOf(".");
8860
- queryColumns.push(index === -1 ? item : item.slice(index + 1));
8861
- } else if (item && "selectAs" in item) {
8862
- queryColumns.push(...Object.keys(item.selectAs));
8863
- }
8864
- });
8865
- if (obj?.columns) {
8866
- queryColumns.push(...obj.columns);
8867
- }
8868
- for (const key of queryColumns) {
8869
- const column = q.shape[key];
8870
- if (column) throwOnReadOnly$1(from, column, key);
8871
- }
8872
- return queryColumns;
8873
- };
8874
- const insertFromQuery = (q, from, many, data) => {
8875
- const ctx = createCtx();
8876
- const obj = data && handleOneData(q, data, ctx);
8877
- const columns = getFromSelectColumns(q, from, obj, many);
8878
- return insert(
8879
- q,
8880
- {
8881
- columns,
8882
- values: { from, values: obj?.values[0] }
8883
- },
8884
- many
8885
- );
8886
- };
8887
9169
  const _queryCreate = (q, data) => {
8888
9170
  createSelect(q);
8889
9171
  return _queryInsert(q, data);
8890
9172
  };
8891
- const _queryInsert = (q, data) => {
9173
+ const _queryInsert = (query, data) => {
8892
9174
  const ctx = createCtx();
8893
- const obj = handleOneData(q, data, ctx);
8894
- const values = q.q.values;
8895
- if (values && "from" in values) {
8896
- obj.columns = getFromSelectColumns(q, values.from, obj);
8897
- values.values = obj.values[0];
8898
- obj.values = values;
8899
- }
8900
- return insert(q, obj);
9175
+ const obj = handleOneData(query, data, ctx);
9176
+ return insert(query, obj);
8901
9177
  };
8902
9178
  const _queryCreateMany = (q, data) => {
8903
9179
  createSelect(q);
@@ -8909,20 +9185,6 @@ const _queryInsertMany = (q, data) => {
8909
9185
  if (!data.length) result = result.none();
8910
9186
  return result;
8911
9187
  };
8912
- const _queryCreateFrom = (q, query, data) => {
8913
- createSelect(q);
8914
- return insertFromQuery(q, query, false, data);
8915
- };
8916
- const _queryInsertFrom = (q, query, data) => {
8917
- return insertFromQuery(q, query, false, data);
8918
- };
8919
- const _queryCreateManyFrom = (q, query) => {
8920
- createSelect(q);
8921
- return insertFromQuery(q, query, true);
8922
- };
8923
- const _queryInsertManyFrom = (q, query) => {
8924
- return insertFromQuery(q, query, true);
8925
- };
8926
9188
  const _queryDefaults = (q, data) => {
8927
9189
  q.q.defaults = data;
8928
9190
  return q;
@@ -9040,85 +9302,6 @@ class QueryCreate {
9040
9302
  insertMany(data) {
9041
9303
  return _queryInsertMany(_clone(this), data);
9042
9304
  }
9043
- /**
9044
- * These methods are for creating a single record, for batch creating see {@link createManyFrom}.
9045
- *
9046
- * `createFrom` is to perform the `INSERT ... SELECT ...` SQL statement, it does select and insert by performing a single query.
9047
- *
9048
- * The first argument is a query for a **single** record, it should have `find`, `take`, or similar.
9049
- *
9050
- * The second optional argument is a data which will be merged with columns returned from the select query.
9051
- *
9052
- * The data for the second argument is the same as in {@link create}.
9053
- *
9054
- * Columns with runtime defaults (defined with a callback) are supported here.
9055
- * The value for such a column will be injected unless selected from a related table or provided in a data object.
9056
- *
9057
- * ```ts
9058
- * const oneRecord = await db.table.createFrom(
9059
- * // In the select, key is a related table column, value is a column to insert as
9060
- * RelatedTable.select({ relatedId: 'id' }).findBy({ key: 'value' }),
9061
- * // optional argument:
9062
- * {
9063
- * key: 'value',
9064
- * // supports sql, nested select, create, update, delete queries
9065
- * fromSql: () => sql`custom sql`,
9066
- * fromQuery: () => db.otherTable.find(id).update(data).get('column'),
9067
- * fromRelated: (q) => q.relatedTable.create(data).get('column'),
9068
- * },
9069
- * );
9070
- * ```
9071
- *
9072
- * The query above will produce such SQL:
9073
- *
9074
- * ```sql
9075
- * INSERT INTO "table"("relatedId", "key")
9076
- * SELECT "relatedTable"."id" AS "relatedId", 'value'
9077
- * FROM "relatedTable"
9078
- * WHERE "relatedTable"."key" = 'value'
9079
- * LIMIT 1
9080
- * RETURNING *
9081
- * ```
9082
- *
9083
- * @param query - query to create new records from
9084
- * @param data - additionally you can set some columns
9085
- */
9086
- createFrom(query, data) {
9087
- return _queryCreateFrom(_clone(this), query, data);
9088
- }
9089
- /**
9090
- * Works exactly as {@link createFrom}, except that it returns inserted row count by default.
9091
- *
9092
- * @param query - query to create new records from
9093
- * @param data - additionally you can set some columns
9094
- */
9095
- insertFrom(query, data) {
9096
- return _queryInsertFrom(_clone(this), query, data);
9097
- }
9098
- /**
9099
- * Similar to `createFrom`, but intended to create many records.
9100
- *
9101
- * Unlike `createFrom`, it doesn't accept second argument with data, and runtime defaults cannot work with it.
9102
- *
9103
- * ```ts
9104
- * const manyRecords = await db.table.createManyFrom(
9105
- * RelatedTable.select({ relatedId: 'id' }).where({ key: 'value' }),
9106
- * );
9107
- * ```
9108
- *
9109
- * @param query - query to create new records from
9110
- */
9111
- createManyFrom(query) {
9112
- return _queryCreateManyFrom(_clone(this), query);
9113
- }
9114
- /**
9115
- * Works exactly as {@link createManyFrom}, except that it returns inserted row count by default.
9116
- *
9117
- * @param query - query to create new records from
9118
- */
9119
- insertManyFrom(query) {
9120
- return _queryInsertManyFrom(_clone(this), query);
9121
- }
9122
9305
  /**
9123
9306
  * `defaults` allows setting values that will be used later in `create`.
9124
9307
  *
@@ -10503,9 +10686,9 @@ class Join {
10503
10686
  }
10504
10687
  /**
10505
10688
  * This method may be useful
10506
- * for combining with [createManyFrom](/guide/create-update-delete.html#createmanyfrom-insertmanyfrom).
10689
+ * for combining with [createForEachFrom](/guide/create-update-delete.html#createForEachFrom-insertForEachFrom).
10507
10690
  *
10508
- * `createManyFrom` creates multiple record based on a selecting query:
10691
+ * `createForEachFrom` creates multiple record based on a selecting query:
10509
10692
  *
10510
10693
  * ```sql
10511
10694
  * INSERT INTO t1(c1, c2)
@@ -10519,7 +10702,7 @@ class Join {
10519
10702
  * ```ts
10520
10703
  * const data = [{ column2: 'one' }, { column2: 'two' }, { column2: 'three' }];
10521
10704
  *
10522
- * await db.table.createManyFrom(
10705
+ * await db.table.createForEachFrom(
10523
10706
  * db.otherTable
10524
10707
  * .joinData('data', (t) => ({ column2: t.text() }), data)
10525
10708
  * .select('otherTable.column1', 'data.column2'),
@@ -12616,6 +12799,7 @@ applyMixins(QueryMethods, [
12616
12799
  Union,
12617
12800
  JsonMethods,
12618
12801
  QueryCreate,
12802
+ QueryCreateFrom,
12619
12803
  Update,
12620
12804
  Delete,
12621
12805
  Transaction,
@@ -12639,9 +12823,9 @@ applyMixins(QueryMethods, [
12639
12823
 
12640
12824
  const makeIndex = (columns, first, second) => {
12641
12825
  if (typeof first === "string") {
12642
- const options = second ?? {};
12826
+ const options = { ...second, name: first };
12643
12827
  return {
12644
- index: { columns, options, name: first }
12828
+ index: { columns, options }
12645
12829
  };
12646
12830
  } else {
12647
12831
  const options = first ?? {};
@@ -12654,24 +12838,27 @@ const tableDataMethods = {
12654
12838
  primaryKey(columns, name) {
12655
12839
  return { primaryKey: { columns, name } };
12656
12840
  },
12657
- unique(columns, ...[first, second]) {
12841
+ unique(columns, ...args) {
12842
+ const [first, second] = args;
12658
12843
  const input = makeIndex(columns, first, second);
12659
12844
  input.index.options.unique = true;
12660
12845
  return input;
12661
12846
  },
12662
12847
  index: makeIndex,
12663
- searchIndex(columns, ...[first, second]) {
12848
+ searchIndex(columns, ...args) {
12664
12849
  var _a;
12850
+ const [first, second] = args;
12665
12851
  const input = makeIndex(columns, first, second);
12666
12852
  (_a = input.index.options).using ?? (_a.using = "gin");
12667
12853
  input.index.options.tsVector = true;
12668
12854
  return input;
12669
12855
  },
12670
- exclude(columns, ...[first, second]) {
12856
+ exclude(columns, ...args) {
12857
+ const [first, second] = args;
12671
12858
  if (typeof first === "string") {
12672
12859
  const options = second ?? {};
12673
12860
  return {
12674
- exclude: { columns, options, name: first }
12861
+ exclude: { columns, options: { ...options, name: first } }
12675
12862
  };
12676
12863
  } else {
12677
12864
  const options = first ?? {};
@@ -13254,5 +13441,5 @@ function copyTableData(query, arg) {
13254
13441
  return q;
13255
13442
  }
13256
13443
 
13257
- export { AfterCommitError, AggregateMethods, ArrayColumn, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CidrColumn, CircleColumn, CitextColumn, Clear, ColumnRefExpression, ColumnType, ComputedColumn, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DecimalColumn, Delete, DomainColumn, DoublePrecisionColumn, DynamicRawSQL, EnumColumn, ExpressionMethods, FnExpression, For, FromMethods, Having, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, Join, JsonMethods, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQueryMethods, MoneyColumn, NumberAsStringBaseColumn, NumberBaseColumn, OnConflictQueryBuilder, OnMethods, Operators, OrExpression, PathColumn, PointColumn, PolygonColumn, PostgisGeographyPointColumn, QueryAsMethods, QueryCreate, QueryGet, QueryHooks, QueryLog, QueryMethods, QueryUpsert, RawSQL, RealColumn, RefExpression, SearchMethods, Select, SerialColumn, SmallIntColumn, SmallSerialColumn, SqlMethod, StringColumn, TextBaseColumn, TextColumn, Then, TimeColumn, TimestampColumn, TimestampTZColumn, Transaction, TransformMethods, TsQueryColumn, TsVectorColumn, UUIDColumn, Union, UnknownColumn, Update, VarCharColumn, VirtualColumn, Where, WithMethods, XMLColumn, _clone, _getSelectableColumn, _initQueryBuilder, _queryAfterSaveCommit, _queryAll, _queryChangeCounter, _queryCreate, _queryCreateFrom, _queryCreateMany, _queryCreateManyFrom, _queryDefaults, _queryDelete, _queryExec, _queryFindBy, _queryFindByOptional, _queryGet, _queryGetOptional, _queryHookAfterCreate, _queryHookAfterCreateCommit, _queryHookAfterDelete, _queryHookAfterDeleteCommit, _queryHookAfterQuery, _queryHookAfterSave, _queryHookAfterUpdate, _queryHookAfterUpdateCommit, _queryHookBeforeCreate, _queryHookBeforeDelete, _queryHookBeforeQuery, _queryHookBeforeSave, _queryHookBeforeUpdate, _queryInsert, _queryInsertFrom, _queryInsertMany, _queryInsertManyFrom, _queryJoinOn, _queryJoinOnJsonPathEquals, _queryJoinOrOn, _queryOr, _queryOrNot, _queryRows, _querySelect, _queryTake, _queryTakeOptional, _queryUnion, _queryUpdate, _queryUpdateOrThrow, _queryWhere, _queryWhereExists, _queryWhereIn, _queryWhereNot, _queryWhereNotOneOf, _queryWhereNotSql, _queryWhereOneOf, _queryWhereSql, _runAfterCommitHooks, addColumnParserToQuery, addParserForRawExpression, addParserForSelectItem, addQueryOn, anyShape, applyComputedColumns, assignDbDataToColumn, checkIfASimpleQuery, cloneQueryBaseUnscoped, columnCheckToCode, columnCode, columnExcludesToCode, columnForeignKeysToCode, columnIndexesToCode, columnsShapeToCode, commitSql, constraintInnerToCode, constraintToCode, copyTableData, countSelect, createDbWithAdapter, defaultSchemaConfig, escapeForLog, escapeForMigration, escapeString, excludeInnerToCode, excludeToCode, extendQuery, filterResult, foreignKeyArgumentToCode, getClonedQueryData, getColumnBaseType, getColumnInfo, getColumnTypes, getFullColumnTable, getQueryAs, getShapeFromSelect, getSqlText, handleResult, identityToCode, indexInnerToCode, indexToCode, isDefaultTimeStamp, isInUserTransaction, isQueryReturnsAll, isSelectingCount, joinSubQuery, logParamToLogObject, makeColumnTypes, makeColumnsByType, makeFnExpression, moveQueryValueToWith, parseRecord, parseTableData, parseTableDataInput, postgisTypmodToSql, primaryKeyInnerToCode, processComputedBatches, processComputedResult, processSelectArg, pushLimitSQL, pushQueryArrayImmutable, pushQueryOn, pushQueryOnForOuter, pushQueryOrOn, pushTableDataCode, queryFrom, queryFromSql, queryJson, queryMethodByReturnType, queryTypeWithLimitOne, queryWrap, raw, referencesArgsToCode, resolveSubQueryCallbackV2, rollbackSql, saveAliasedShape, setColumnDefaultParse, setColumnEncode, setColumnParse, setColumnParseNull, setParserForSelectedString, setQueryObjectValueImmutable, setQueryOperators, simplifyColumnDefault, sqlFn, sqlQueryArgsToExpression, tableDataMethods, templateLiteralToSQL, testTransaction, throwIfJoinLateral, throwIfNoWhere, toSQL };
13444
+ export { AfterCommitError, AggregateMethods, ArrayColumn, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CidrColumn, CircleColumn, CitextColumn, Clear, ColumnRefExpression, ColumnType, ComputedColumn, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DecimalColumn, Delete, DomainColumn, DoublePrecisionColumn, DynamicRawSQL, EnumColumn, ExpressionMethods, FnExpression, For, FromMethods, Having, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, Join, JsonMethods, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQueryMethods, MoneyColumn, NumberAsStringBaseColumn, NumberBaseColumn, OnMethods, Operators, OrExpression, PathColumn, PointColumn, PolygonColumn, PostgisGeographyPointColumn, QueryAsMethods, QueryGet, QueryHooks, QueryLog, QueryMethods, QueryUpsert, RawSQL, RealColumn, RefExpression, SearchMethods, Select, SerialColumn, SmallIntColumn, SmallSerialColumn, SqlMethod, StringColumn, TextBaseColumn, TextColumn, Then, TimeColumn, TimestampColumn, TimestampTZColumn, Transaction, TransformMethods, TsQueryColumn, TsVectorColumn, UUIDColumn, Union, UnknownColumn, Update, VarCharColumn, VirtualColumn, Where, WithMethods, XMLColumn, _addWith, _clone, _getSelectableColumn, _initQueryBuilder, _queryAfterSaveCommit, _queryAll, _queryChangeCounter, _queryCreate, _queryCreateForEachFrom, _queryCreateMany, _queryCreateManyFrom, _queryCreateOneFrom, _queryDefaults, _queryDelete, _queryExec, _queryFindBy, _queryFindByOptional, _queryGet, _queryGetOptional, _queryHookAfterCreate, _queryHookAfterCreateCommit, _queryHookAfterDelete, _queryHookAfterDeleteCommit, _queryHookAfterQuery, _queryHookAfterSave, _queryHookAfterUpdate, _queryHookAfterUpdateCommit, _queryHookBeforeCreate, _queryHookBeforeDelete, _queryHookBeforeQuery, _queryHookBeforeSave, _queryHookBeforeUpdate, _queryInsert, _queryInsertForEachFrom, _queryInsertMany, _queryInsertManyFrom, _queryInsertOneFrom, _queryJoinOn, _queryJoinOnJsonPathEquals, _queryJoinOrOn, _queryOr, _queryOrNot, _queryRows, _querySelect, _queryTake, _queryTakeOptional, _queryUnion, _queryUpdate, _queryUpdateOrThrow, _queryWhere, _queryWhereExists, _queryWhereIn, _queryWhereNot, _queryWhereNotOneOf, _queryWhereNotSql, _queryWhereOneOf, _queryWhereSql, _runAfterCommitHooks, addColumnParserToQuery, addParserForRawExpression, addParserForSelectItem, addQueryOn, anyShape, applyComputedColumns, assignDbDataToColumn, checkIfASimpleQuery, cloneQueryBaseUnscoped, columnCheckToCode, columnCode, columnExcludesToCode, columnForeignKeysToCode, columnIndexesToCode, columnsShapeToCode, commitSql, constraintInnerToCode, constraintToCode, copyTableData, countSelect, createDbWithAdapter, defaultSchemaConfig, escapeForLog, escapeForMigration, escapeString, excludeInnerToCode, excludeToCode, extendQuery, filterResult, foreignKeyArgumentToCode, getClonedQueryData, getColumnBaseType, getColumnInfo, getColumnTypes, getFullColumnTable, getQueryAs, getShapeFromSelect, getSqlText, handleResult, identityToCode, indexInnerToCode, indexToCode, isDefaultTimeStamp, isInUserTransaction, isQueryReturnsAll, isSelectingCount, joinSubQuery, logParamToLogObject, makeColumnTypes, makeColumnsByType, makeFnExpression, moveQueryValueToWith, parseRecord, parseTableData, parseTableDataInput, postgisTypmodToSql, primaryKeyInnerToCode, processComputedBatches, processComputedResult, processSelectArg, pushLimitSQL, pushQueryArrayImmutable, pushQueryOn, pushQueryOnForOuter, pushQueryOrOn, pushTableDataCode, queryFrom, queryFromSql, queryJson, queryMethodByReturnType, queryTypeWithLimitOne, queryWrap, raw, referencesArgsToCode, resolveSubQueryCallbackV2, rollbackSql, saveAliasedShape, setColumnDefaultParse, setColumnEncode, setColumnParse, setColumnParseNull, setParserForSelectedString, setQueryObjectValueImmutable, setQueryOperators, simplifyColumnDefault, sqlFn, sqlQueryArgsToExpression, tableDataMethods, templateLiteralToSQL, testTransaction, throwIfJoinLateral, throwIfNoWhere, toSQL };
13258
13445
  //# sourceMappingURL=index.mjs.map