pqb 0.67.2 → 0.67.4

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.d.ts CHANGED
@@ -6255,6 +6255,14 @@ declare abstract class QueryHooks {
6255
6255
  */
6256
6256
  catchAfterCommitError<T>(this: T, fn: AfterCommitErrorHandler): T;
6257
6257
  }
6258
+ interface ColumnDataSelectSqlProp {
6259
+ selectSql?: Expression;
6260
+ selectSqlFn?: SelectSqlCallback;
6261
+ }
6262
+ interface SelectSqlCallback {
6263
+ (column: ColumnRefExpression<Column.Pick.QueryColumn>): Expression;
6264
+ }
6265
+ type SelectSqlColumn<T extends Column.Pick.DataAndDataType, Expr extends Expression> = unknown extends Expr['result']['value']['outputType'] ? T : { [K in keyof T]: K extends 'outputType' ? Expr['result']['value']['outputType'] : T[K] };
6258
6266
  declare namespace Column {
6259
6267
  export namespace Modifiers {
6260
6268
  export interface IsPrimaryKey<Name extends string> {
@@ -6895,6 +6903,13 @@ declare abstract class Column<Schema extends ColumnTypeSchemaArg = ColumnTypeSch
6895
6903
  * ```
6896
6904
  */
6897
6905
  select<T extends Column.Pick.Data, Value extends boolean>(this: T, value: Value): Column.Modifiers.DefaultSelect<T, Value>;
6906
+ /**
6907
+ * Set SQL to use when selecting this column.
6908
+ *
6909
+ * The column remains a regular writable database column. Create, update,
6910
+ * filters, ordering, grouping, and migrations still use the physical column.
6911
+ */
6912
+ selectSql<T extends Column.Pick.DataAndDataType, Expr extends Expression>(this: T, fn: (column: ColumnRefExpression<T & Column.Pick.QueryColumn>) => Expr): SelectSqlColumn<T, Expr>;
6898
6913
  /**
6899
6914
  * Forbid the column to be used in [create](/guide/create-update-delete.html#create-insert) and [update](/guide/create-update-delete.html#update) methods.
6900
6915
  *
@@ -8369,7 +8384,7 @@ declare const setColumnParse: (column: Column.Pick.Data, fn: (input: any) => unk
8369
8384
  declare const setColumnParseNull: (column: Column.Pick.Data, fn: () => unknown, nullSchema?: unknown) => any;
8370
8385
  declare const setColumnEncode: (column: Column.Pick.Data, fn: (input: any) => unknown, inputSchema?: unknown) => any;
8371
8386
  declare const getColumnBaseType: (column: Column.Pick.Data, domainsMap: DbStructureDomainsMap, type: string) => string;
8372
- interface ColumnDataComputedProp {
8387
+ interface ColumnDataComputedProp extends ColumnDataSelectSqlProp {
8373
8388
  computed?: Expression;
8374
8389
  }
8375
8390
  type ComputedColumnsFromOptions<T extends ComputedOptionsFactory<never, never> | undefined> = T extends ((...args: any[]) => infer R extends ComputedOptionsConfig) ? { [K in keyof R]: R[K] extends QueryOrExpression<unknown> ? R[K]['result']['value'] : R[K] extends (() => {
@@ -8590,6 +8605,10 @@ type QueryType = undefined | null | 'upsert' | 'insert' | 'update' | 'delete';
8590
8605
  interface AsFn {
8591
8606
  (as: string): void;
8592
8607
  }
8608
+ interface SelectAllColumnExpression {
8609
+ (ctx: ToSQLCtx, quotedAs?: string): string;
8610
+ }
8611
+ type SelectAllColumn = string | SelectAllColumnExpression;
8593
8612
  interface QueryData extends QueryDataAliases, PickQueryDataParsers, HasHookSelect, MutativeQueriesSelectRelationsQueryData {
8594
8613
  type: QueryType;
8595
8614
  adapter: Adapter;
@@ -8625,7 +8644,7 @@ interface QueryData extends QueryDataAliases, PickQueryDataParsers, HasHookSelec
8625
8644
  sql: string;
8626
8645
  aliases: string[];
8627
8646
  };
8628
- selectAllColumns?: string[];
8647
+ selectAllColumns?: SelectAllColumn[];
8629
8648
  /**
8630
8649
  * Subset of the `shape` that only includes columns with no `data.explicitSelect`.
8631
8650
  */
@@ -8713,6 +8732,8 @@ interface QueryData extends QueryDataAliases, PickQueryDataParsers, HasHookSelec
8713
8732
  /** upsert **/
8714
8733
  upsertUpdate?: boolean;
8715
8734
  upsertSecond?: boolean;
8735
+ upsertCreateAppendQueries?: SubQueryForSql[];
8736
+ upsertCreateAsFns?: AsFn[];
8716
8737
  upsertInsert?(): unknown;
8717
8738
  /** insert **/
8718
8739
  columns: string[];
@@ -10539,6 +10560,7 @@ declare abstract class QueryAsMethods {
10539
10560
  as<T extends AsQueryArg, As extends string>(this: T, as: As): SetQueryTableAlias<T, As>;
10540
10561
  }
10541
10562
  declare const _appendQuery: (main: Query, append: Query, asFn: (as: string) => void) => Query;
10563
+ declare const _appendQueryOnUpsertCreate: (main: Query, append: Query, asFn: (as: string) => void) => Query;
10542
10564
  declare const getPrimaryKeys: (q: Query) => string[];
10543
10565
  /**
10544
10566
  * Set value into the object in query data, create the object if it doesn't yet exist.
@@ -10694,4 +10716,4 @@ declare const testTransaction: {
10694
10716
  */
10695
10717
  close(arg: Arg$1): Promise<void>;
10696
10718
  };
10697
- export { type Adapter, AdapterClass, type AdapterConfigBase, type AdapterParams, type AdapterSchemaConfigOptions, type AfterCommitStandaloneHook, type AfterHook, ArrayColumn, type ArrayColumnValue, type ArrayData, type AsyncState, type BaseNumberData, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CidrColumn, CircleColumn, CitextColumn, type Code, type Codes, Column, type ColumnFromDbParams, type ColumnSchemaConfig, type ColumnSchemaGetterColumns, type ColumnSchemaGetterTableClass, type ColumnToCodeCtx, type ColumnTypeSchemaArg, type ColumnsByType, type ColumnsShape, type ComputedColumnsFromOptions, type ComputedOptionsConfig, type ComputedOptionsFactory, type CreateCtx, type CreateData, type CreateManyMethodsNames, type CreateMethodsNames, type CreateSelf, CustomTypeColumn, DateBaseColumn, DateColumn, type DateColumnData, DateTimeBaseClass, DateTimeTzBaseClass, Db, type DbDomainArg, type DbExtension, type DbOptions, type DbResult, type DbSharedOptions, type DbSqlMethod, type DbStructureDomainsMap, type DbTableOptionScopes, type DbTableOptions, DecimalColumn, type DecimalColumnData, type DefaultColumnTypes, type DefaultPrivileges, type DefaultSchemaConfig, type DeleteMethodsNames, DomainColumn, DoublePrecisionColumn, type DriverAdapter, DynamicRawSQL, type EmptyObject, type EmptyTuple, EnumColumn, Expression, type FromArg, type FromResult, type GeneratorIgnore, type Grant, type HookSelectValue, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, type IsQuery, type IsolationLevel, JSONColumn, JSONTextColumn, type JoinQueryMethod, type JoinedShapes, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, type MapTableScopesOption, type MaybeArray, type MaybePromise, type MergeQuery, MoneyColumn, type NoPrimaryKeyOption, type NonUniqDataItem, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, type NumberColumnData, Operators, type OperatorsArray, type OperatorsJson, type OperatorsOrdinalText, OrchidOrmInternalError, type Ord, PathColumn, type PickQueryInputType, type PickQueryInternal, type PickQueryQ, type PickQueryRelations, type PickQuerySelectableRelations, type PickQueryShape, PointColumn, PolygonColumn, PostgisGeographyPointColumn, type Query, type QueryAfterHook, type QueryBeforeActionHook, type QueryBeforeHook, type QueryData, QueryError, type QueryHasWhere, type QueryHelperResult, QueryHookUtils, QueryHooks, type QueryInternal, type QueryLogObject, type QueryLogOptions, type QueryLogger, type QueryManyTake, type QueryManyTakeOptional, type QueryOrExpression, type QueryResult, type QueryResultRow, type QueryReturnType, type QuerySchema, type QueryScopes, RawSql, type RawSqlBase, RealColumn, type RecordKeyTrue, type RecordOptionalString, type RecordString, type RecordStringOrNumber, type RecordUnknown, type RelationConfigBase, type RelationJoinQuery, type RelationsBase, type Rls, type RlsPolicy, type SchemaConfigFnWithOptions, type SearchWeight, type SelectableFromShape, SerialColumn, type SerialColumnData, type ShallowSimplify, type ShapeColumnPrimaryKeys, type ShapeUniqueColumns, type SingleSql, type SingleSqlItem, SmallIntColumn, SmallSerialColumn, type Sql, type SqlFn, type SqlSessionState, type StorageOptions, StringColumn, type StringData, type TableData, type TableDataFn, type TableDataInput, type TableDataItem, type TableDataItemsUniqueColumnTuples, type TableDataItemsUniqueColumns, type TableDataItemsUniqueConstraints, type TableDataMethods, type TemplateLiteralArgs, TextBaseColumn, TextColumn, TimeColumn, TimestampColumn, TimestampTZColumn, type Timestamps, type TransactionAdapter, TransactionAdapterClass, type TransactionOptions, TsQueryColumn, TsVectorColumn, UUIDColumn, type UniqueConstraints, type UniqueTableDataItem, UnknownColumn, type UpdateData, type UpsertData, type UpsertThis, VarCharColumn, VirtualColumn, type WhereArg, XMLColumn, _appendQuery, _clone, _createDbSqlMethod, _hookSelectColumns, _initQueryBuilder, _orCreate, _prependWith, _queryCreate, _queryCreateMany, _queryCreateManyFrom, _queryDefaults, _queryDelete, _queryFindBy, _queryFindByOptional, _queryHookAfterCreate, _queryHookAfterUpdate, _queryInsert, _queryInsertMany, _queryJoinOn, _queryRows, _querySelect, _queryTake, _queryTakeOptional, _queryUpdate, _queryUpdateOrThrow, _queryUpsert, _queryWhere, _queryWhereExists, _queryWhereIn, addCode, addTopCte, addTopCteSql, applyMixins, assignDbDataToColumn, backtickQuote, cloneQueryBaseUnscoped, codeToString, colors, columnsShapeToCode, constraintInnerToCode, consumeColumnName, copyTableData, createDbWithAdapter, deepCompare, defaultSchemaConfig, emptyArray, emptyObject, escapeForMigration, escapeString, excludeInnerToCode, exhaustive, getCallerFilePath, getClonedQueryData, getColumnBaseType, getColumnInfo, getColumnTypes, getDateAsDateFn, getDateAsNumberFn, getDriverErrorCode, getFreeAlias, getFreeSetAlias, getImportPath, getPrimaryKeys, getQueryAs, getQuerySchema, getShapeFromSelect, getSqlText, getStackTrace, getSupportedDefaultPrivileges, indexInnerToCode, internalSchemaConfig, isExpression, isQueryReturnsAll, isRawSQL, logColors, logParamToLogObject, makeColumnNullable, makeColumnTypes, makeColumnsByType, makeConnectRetryConfig, noop, objectHasValues, omit, parseTableData, parseTableDataInput, pathToLog, pick, pluralize, prepareSubQueryForSql, primaryKeyInnerToCode, pushQueryOnForOuter, pushQueryValueImmutable, pushTableDataCode, quoteIdentifier, quoteObjectKey, quoteTableWithSchema, raw, rawSqlToCode, referencesArgsToCode, returnArg, setColumnData, setColumnEncode, setColumnParse, setColumnParseNull, setCurrentColumnName, setDataValue, setDefaultLanguage, setFreeAlias, setQueryObjectValueImmutable, singleQuote, tableDataMethods, testTransaction, toArray, toCamelCase, toPascalCase, toSnakeCase, wrapAdapterFnWithConnectRetry };
10719
+ export { type Adapter, AdapterClass, type AdapterConfigBase, type AdapterParams, type AdapterSchemaConfigOptions, type AfterCommitStandaloneHook, type AfterHook, ArrayColumn, type ArrayColumnValue, type ArrayData, type AsyncState, type BaseNumberData, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CidrColumn, CircleColumn, CitextColumn, type Code, type Codes, Column, type ColumnFromDbParams, type ColumnSchemaConfig, type ColumnSchemaGetterColumns, type ColumnSchemaGetterTableClass, type ColumnToCodeCtx, type ColumnTypeSchemaArg, type ColumnsByType, type ColumnsShape, type ComputedColumnsFromOptions, type ComputedOptionsConfig, type ComputedOptionsFactory, type CreateCtx, type CreateData, type CreateManyMethodsNames, type CreateMethodsNames, type CreateSelf, CustomTypeColumn, DateBaseColumn, DateColumn, type DateColumnData, DateTimeBaseClass, DateTimeTzBaseClass, Db, type DbDomainArg, type DbExtension, type DbOptions, type DbResult, type DbSharedOptions, type DbSqlMethod, type DbStructureDomainsMap, type DbTableOptionScopes, type DbTableOptions, DecimalColumn, type DecimalColumnData, type DefaultColumnTypes, type DefaultPrivileges, type DefaultSchemaConfig, type DeleteMethodsNames, DomainColumn, DoublePrecisionColumn, type DriverAdapter, DynamicRawSQL, type EmptyObject, type EmptyTuple, EnumColumn, Expression, type ExpressionData, type FromArg, type FromResult, type GeneratorIgnore, type Grant, type HookSelectValue, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, type IsQuery, type IsolationLevel, JSONColumn, JSONTextColumn, type JoinQueryMethod, type JoinedShapes, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, type MapTableScopesOption, type MaybeArray, type MaybePromise, type MergeQuery, MoneyColumn, type NoPrimaryKeyOption, type NonUniqDataItem, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, type NumberColumnData, Operators, type OperatorsArray, type OperatorsJson, type OperatorsOrdinalText, OrchidOrmInternalError, type Ord, PathColumn, type PickQueryInputType, type PickQueryInternal, type PickQueryQ, type PickQueryRelations, type PickQuerySelectableRelations, type PickQueryShape, PointColumn, PolygonColumn, PostgisGeographyPointColumn, type Query, type QueryAfterHook, type QueryBeforeActionHook, type QueryBeforeHook, type QueryData, QueryError, type QueryHasWhere, type QueryHelperResult, QueryHookUtils, QueryHooks, type QueryInternal, type QueryLogObject, type QueryLogOptions, type QueryLogger, type QueryManyTake, type QueryManyTakeOptional, type QueryOrExpression, type QueryResult, type QueryResultRow, type QueryReturnType, type QuerySchema, type QueryScopes, RawSql, type RawSqlBase, RealColumn, type RecordKeyTrue, type RecordOptionalString, type RecordString, type RecordStringOrNumber, type RecordUnknown, type RelationConfigBase, type RelationJoinQuery, type RelationsBase, type Rls, type RlsPolicy, type SchemaConfigFnWithOptions, type SearchWeight, type SelectableFromShape, SerialColumn, type SerialColumnData, type ShallowSimplify, type ShapeColumnPrimaryKeys, type ShapeUniqueColumns, type SingleSql, type SingleSqlItem, SmallIntColumn, SmallSerialColumn, type Sql, type SqlFn, type SqlSessionState, type StorageOptions, StringColumn, type StringData, type TableData, type TableDataFn, type TableDataInput, type TableDataItem, type TableDataItemsUniqueColumnTuples, type TableDataItemsUniqueColumns, type TableDataItemsUniqueConstraints, type TableDataMethods, type TemplateLiteralArgs, TextBaseColumn, TextColumn, TimeColumn, TimestampColumn, TimestampTZColumn, type Timestamps, type ToSQLCtx, type ToSqlValues, type TransactionAdapter, TransactionAdapterClass, type TransactionOptions, TsQueryColumn, TsVectorColumn, UUIDColumn, type UniqueConstraints, type UniqueTableDataItem, UnknownColumn, type UpdateData, type UpsertData, type UpsertThis, VarCharColumn, VirtualColumn, type WhereArg, XMLColumn, _appendQuery, _appendQueryOnUpsertCreate, _clone, _createDbSqlMethod, _hookSelectColumns, _initQueryBuilder, _orCreate, _prependWith, _queryCreate, _queryCreateMany, _queryCreateManyFrom, _queryDefaults, _queryDelete, _queryFindBy, _queryFindByOptional, _queryHookAfterCreate, _queryHookAfterUpdate, _queryInsert, _queryInsertMany, _queryJoinOn, _queryRows, _querySelect, _queryTake, _queryTakeOptional, _queryUpdate, _queryUpdateOrThrow, _queryUpsert, _queryWhere, _queryWhereExists, _queryWhereIn, addCode, addTopCte, addTopCteSql, applyMixins, assignDbDataToColumn, backtickQuote, cloneQueryBaseUnscoped, codeToString, colors, columnsShapeToCode, constraintInnerToCode, consumeColumnName, copyTableData, createDbWithAdapter, deepCompare, defaultSchemaConfig, emptyArray, emptyObject, escapeForMigration, escapeString, excludeInnerToCode, exhaustive, getCallerFilePath, getClonedQueryData, getColumnBaseType, getColumnInfo, getColumnTypes, getDateAsDateFn, getDateAsNumberFn, getDriverErrorCode, getFreeAlias, getFreeSetAlias, getImportPath, getPrimaryKeys, getQueryAs, getQuerySchema, getShapeFromSelect, getSqlText, getStackTrace, getSupportedDefaultPrivileges, indexInnerToCode, internalSchemaConfig, isExpression, isQueryReturnsAll, isRawSQL, logColors, logParamToLogObject, makeColumnNullable, makeColumnTypes, makeColumnsByType, makeConnectRetryConfig, noop, objectHasValues, omit, parseTableData, parseTableDataInput, pathToLog, pick, pluralize, prepareSubQueryForSql, primaryKeyInnerToCode, pushQueryOnForOuter, pushQueryValueImmutable, pushTableDataCode, quoteIdentifier, quoteObjectKey, quoteTableWithSchema, raw, rawSqlToCode, referencesArgsToCode, returnArg, setColumnData, setColumnEncode, setColumnParse, setColumnParseNull, setCurrentColumnName, setDataValue, setDefaultLanguage, setFreeAlias, setQueryObjectValueImmutable, singleQuote, tableDataMethods, testTransaction, toArray, toCamelCase, toPascalCase, toSnakeCase, wrapAdapterFnWithConnectRetry };
package/dist/index.js CHANGED
@@ -771,6 +771,15 @@ var Column = class {
771
771
  return setColumnData(this, "explicitSelect", !value);
772
772
  }
773
773
  /**
774
+ * Set SQL to use when selecting this column.
775
+ *
776
+ * The column remains a regular writable database column. Create, update,
777
+ * filters, ordering, grouping, and migrations still use the physical column.
778
+ */
779
+ selectSql(fn) {
780
+ return setColumnData(this, "selectSqlFn", fn);
781
+ }
782
+ /**
774
783
  * Forbid the column to be used in [create](/guide/create-update-delete.html#create-insert) and [update](/guide/create-update-delete.html#update) methods.
775
784
  *
776
785
  * `readOnly` column is still can be set from a [hook](http://localhost:5173/guide/hooks.html#set-values-before-create-or-update).
@@ -3992,6 +4001,7 @@ const applyComputedColumns = (q, fn) => {
3992
4001
  q.shape[key] = col;
3993
4002
  const { data } = col;
3994
4003
  data.computed = item;
4004
+ data.selectSql = item;
3995
4005
  data.explicitSelect = true;
3996
4006
  data.readOnly = true;
3997
4007
  const parse = col._parse;
@@ -4563,7 +4573,11 @@ const loadRelations = async (state, result, savepointState, renames) => {
4563
4573
  const q = state.query;
4564
4574
  const primaryKeys = requirePrimaryKeys(q, "Cannot select a relation of a table that has no primary keys");
4565
4575
  const selectQuery = _unscope(q, "nonDeleted");
4566
- selectQuery.q.type = selectQuery.q.returnType = void 0;
4576
+ selectQuery.q.type = void 0;
4577
+ selectQuery.q.returnType = void 0;
4578
+ selectQuery.q.with = void 0;
4579
+ selectQuery.q.appendQueries = void 0;
4580
+ selectQuery.q.valuesJoinedAs = void 0;
4567
4581
  const matchSourceTableIds = {};
4568
4582
  for (const pkey of primaryKeys) matchSourceTableIds[pkey] = { in: result.map((row) => row[pkey]) };
4569
4583
  (selectQuery.q.and ??= []).push(matchSourceTableIds);
@@ -6523,6 +6537,15 @@ const columnToSql = (ctx, data, shape, column, quotedAs, select) => {
6523
6537
  if (index !== -1) return columnWithDotToSql(ctx, data, shape, column, index, quotedAs, select);
6524
6538
  return simpleColumnToSQL(ctx, column, shape[column], quotedAs);
6525
6539
  };
6540
+ const selectedColumnToSql = (ctx, data, shape, column, quotedAs) => {
6541
+ const index = column.indexOf(".");
6542
+ return index !== -1 ? selectedColumnWithDotToSql(ctx, data, shape, column, index, quotedAs) : selectedSimpleColumnToSql(ctx, column, shape[column], quotedAs);
6543
+ };
6544
+ const selectedSimpleColumnToSql = (ctx, key, column, quotedAs) => {
6545
+ if (!column) return `"${key}"`;
6546
+ const { data } = column;
6547
+ return data.selectSql ? `(${data.selectSql.toSQL(ctx, quotedAs)})` : `${quotedAs ? `${quotedAs}.` : ""}"${data.name || key}"`;
6548
+ };
6526
6549
  /**
6527
6550
  * in a case when ordering or grouping by a column which was selected as expression:
6528
6551
  * ```ts
@@ -6548,7 +6571,7 @@ const columnWithDotToSql = (ctx, data, shape, column, index, quotedAs, select) =
6548
6571
  const key = column.slice(index + 1);
6549
6572
  if (key === "*") {
6550
6573
  const shape = data.joinedShapes?.[table];
6551
- return shape ? select ? makeRowToJson(table, shape, true) : `"${table}".*` : column;
6574
+ return shape ? select ? makeRowToJson(ctx, table, shape, true) : `"${table}".*` : column;
6552
6575
  }
6553
6576
  const tableName = _getQueryAliasOrName(data, table);
6554
6577
  const quoted = `"${table}"`;
@@ -6560,6 +6583,22 @@ const columnWithDotToSql = (ctx, data, shape, column, index, quotedAs, select) =
6560
6583
  }
6561
6584
  return `"${tableName}"."${key}"`;
6562
6585
  };
6586
+ const selectedColumnWithDotToSql = (ctx, data, shape, column, index, quotedAs) => {
6587
+ const table = column.slice(0, index);
6588
+ const key = column.slice(index + 1);
6589
+ if (key === "*") {
6590
+ const shape = data.joinedShapes?.[table];
6591
+ return shape ? makeRowToJson(ctx, table, shape, true) : column;
6592
+ }
6593
+ const tableName = _getQueryAliasOrName(data, table);
6594
+ const quoted = `"${table}"`;
6595
+ const col = quoted === quotedAs ? shape[key] : data.joinedShapes?.[tableName]?.[key];
6596
+ if (col) {
6597
+ if (col.data.selectSql) return `(${col.data.selectSql.toSQL(ctx, quoted)})`;
6598
+ if (col.data.name) return `"${tableName}"."${col.data.name}"`;
6599
+ }
6600
+ return `"${tableName}"."${key}"`;
6601
+ };
6563
6602
  const columnToSqlWithAs = (ctx, data, column, as, quotedAs, select, jsonList) => {
6564
6603
  const index = column.indexOf(".");
6565
6604
  return index !== -1 ? tableColumnToSqlWithAs(ctx, data, column, column.slice(0, index), column.slice(index + 1), as, quotedAs, select, jsonList) : ownColumnToSqlWithAs(ctx, data, column, as, quotedAs, select, jsonList);
@@ -6569,7 +6608,7 @@ const tableColumnToSqlWithAs = (ctx, data, column, table, key, as, quotedAs, sel
6569
6608
  if (jsonList) jsonList[as] = void 0;
6570
6609
  const shape = data.joinedShapes?.[table];
6571
6610
  if (shape) {
6572
- if (select) return makeRowToJson(table, shape, true) + ` "${as}"`;
6611
+ if (select) return makeRowToJson(ctx, table, shape, true) + ` "${as}"`;
6573
6612
  return `"${table}"."${table}" "${as}"`;
6574
6613
  }
6575
6614
  return column;
@@ -6577,10 +6616,10 @@ const tableColumnToSqlWithAs = (ctx, data, column, table, key, as, quotedAs, sel
6577
6616
  const tableName = _getQueryAliasOrName(data, table);
6578
6617
  const quoted = `"${table}"`;
6579
6618
  const col = quoted === quotedAs ? data.shape[key] : data.joinedShapes?.[tableName][key];
6580
- if (jsonList) jsonList[as] = col;
6619
+ if (jsonList) jsonList[as] = col && getSelectedColumnData(col);
6581
6620
  if (col) {
6621
+ if (col.data.selectSql) return `(${col.data.selectSql.toSQL(ctx, quoted)}) "${as}"`;
6582
6622
  if (col.data.name && col.data.name !== key) return `"${tableName}"."${col.data.name}" "${as}"`;
6583
- if (col.data.computed) return `(${col.data.computed.toSQL(ctx, quoted)}) "${as}"`;
6584
6623
  }
6585
6624
  return `"${tableName}"."${key}"${key === as ? "" : ` "${as}"`}`;
6586
6625
  };
@@ -6590,10 +6629,10 @@ const ownColumnToSqlWithAs = (ctx, data, column, as, quotedAs, select, jsonList)
6590
6629
  return `"${column}"."${column}" "${as}"`;
6591
6630
  }
6592
6631
  const col = data.shape[column];
6593
- if (jsonList) jsonList[as] = col;
6632
+ if (jsonList) jsonList[as] = col && getSelectedColumnData(col);
6594
6633
  if (col) {
6634
+ if (col.data.selectSql) return `(${col.data.selectSql.toSQL(ctx, quotedAs)}) "${as}"`;
6595
6635
  if (col.data.name && col.data.name !== column) return `${quotedAs ? `${quotedAs}.` : ""}"${col.data.name}"${col.data.name === as ? "" : ` "${as}"`}`;
6596
- if (col.data.computed) return `(${col.data.computed.toSQL(ctx, quotedAs)}) "${as}"`;
6597
6636
  }
6598
6637
  return `${quotedAs ? `${quotedAs}.` : ""}"${column}"${column === as ? "" : ` "${as}"`}`;
6599
6638
  };
@@ -6749,7 +6788,7 @@ var SelectItemExpression = class extends Expression {
6749
6788
  }
6750
6789
  makeSQL(ctx, quotedAs) {
6751
6790
  const q = this.q;
6752
- return typeof this.item === "string" ? this.item === "*" ? selectAllSql(q, quotedAs).join(", ") : columnToSql(ctx, q, q.shape, this.item, quotedAs, true) : this.item.toSQL(ctx, quotedAs);
6791
+ return typeof this.item === "string" ? this.item === "*" ? selectAllSql(q, quotedAs, void 0, ctx).join(", ") : selectedColumnToSql(ctx, q, q.shape, this.item, quotedAs) : this.item.toSQL(ctx, quotedAs);
6753
6792
  }
6754
6793
  };
6755
6794
  const _getSelectableColumn = (q, arg) => {
@@ -6961,22 +7000,33 @@ const setMutativeQueriesSelectRelationsSqlState = (d, as, rel) => {
6961
7000
  const handleInsertAndUpdateSelectRelationsSqlState = (ctx, state) => {
6962
7001
  if (state) ctx.topCtx.mutativeQueriesSelectRelationsSqlState = state;
6963
7002
  };
7003
+ const unsetValuesJoinedAsForMutativeSelectRelations = (query) => {
7004
+ if (!query.q.selectRelation || !query.q.valuesJoinedAs) return;
7005
+ const { valuesJoinedAs } = query.q;
7006
+ query.q.valuesJoinedAs = void 0;
7007
+ return valuesJoinedAs;
7008
+ };
7009
+ const restoreValuesJoinedAsForMutativeSelectRelations = (query, valuesJoinedAs) => {
7010
+ if (valuesJoinedAs) query.q.valuesJoinedAs = valuesJoinedAs;
7011
+ };
6964
7012
  const handleDeleteSelectRelationsSqlState = (ctx, query, relationSelectState) => {
6965
7013
  const selectRelations = relationSelectState?.value;
6966
7014
  if (!selectRelations) return;
6967
7015
  const selectPrimaryKeysQuery = prepareSubQueryForSql(query, _clone(query));
7016
+ selectPrimaryKeysQuery.q.valuesJoinedAs = void 0;
6968
7017
  const primaryKeys = requirePrimaryKeys(query, "primary keys are required for selecting relation in delete");
6969
7018
  _addToHookSelect(selectPrimaryKeysQuery, primaryKeys, true);
6970
7019
  const { as: cteAs } = moveQueryToCte(ctx, selectPrimaryKeysQuery, void 0, true);
6971
7020
  const relKeys = Object.keys(selectRelations);
6972
7021
  const hookSelect = selectPrimaryKeysQuery.q.hookSelect;
7022
+ const queryAs = getQueryAs(query);
6973
7023
  const join = {
6974
7024
  type: "JOIN",
6975
7025
  args: {
6976
7026
  w: cteAs,
6977
7027
  a: [Object.fromEntries(primaryKeys.map((key) => {
6978
7028
  const selected = hookSelect.get(key);
6979
- return [cteAs + "." + (selected.as || selected.select), key];
7029
+ return [cteAs + "." + (selected.as || selected.select), `${queryAs}.${key}`];
6980
7030
  }))]
6981
7031
  }
6982
7032
  };
@@ -7095,12 +7145,12 @@ const selectToSqlList = (ctx, table, query, quotedAs, hookSelect = query.hookSel
7095
7145
  quotedTable = `"${tableName}"`;
7096
7146
  columnName = select.slice(index + 1);
7097
7147
  col = table.q.joinedShapes?.[tableName]?.[columnName];
7098
- sql = col?.data.computed ? col.data.computed.toSQL(ctx, `"${tableName}"`) : `"${tableName}"."${col?.data.name || columnName}"`;
7148
+ sql = selectedColumnToSql(ctx, table.q, table.q.shape, select, void 0);
7099
7149
  } else {
7100
7150
  quotedTable = quotedAs;
7101
7151
  columnName = select;
7102
7152
  col = query.shape[select];
7103
- sql = simpleColumnToSQL(ctx, select, col, quotedAs);
7153
+ sql = selectedColumnToSql(ctx, table.q, query.shape, select, quotedAs);
7104
7154
  }
7105
7155
  } else {
7106
7156
  columnName = column;
@@ -7140,17 +7190,24 @@ const selectToSql = (ctx, table, query, quotedAs, hookSelect = query.hookSelect,
7140
7190
  return selectToSqlList(ctx, table, query, quotedAs, hookSelect, isSubSql, aliases, jsonList, delayedRelationSelect).join(", ");
7141
7191
  };
7142
7192
  const internalSelectAllSql = (ctx, query, quotedAs, jsonList) => {
7143
- if (jsonList) Object.assign(jsonList, query.selectAllShape);
7193
+ if (jsonList) for (const key in query.selectAllShape) {
7194
+ const column = query.selectAllShape[key];
7195
+ jsonList[key] = getSelectedColumnData(column);
7196
+ }
7144
7197
  let columnsCount;
7145
7198
  if (query.shape !== anyShape) {
7146
7199
  columnsCount = 0;
7147
7200
  for (const key in query.shape) if (!query.shape[key].data.explicitSelect) columnsCount++;
7148
7201
  ctx.selectedCount += columnsCount;
7149
7202
  }
7150
- return selectAllSql(query, quotedAs, columnsCount);
7203
+ return selectAllSql(query, quotedAs, columnsCount, ctx);
7204
+ };
7205
+ const selectAllSql = (q, quotedAs, columnsCount, ctx) => {
7206
+ return q.join?.length || q.updateFrom || q.updateMany ? q.selectAllColumns?.map((item) => selectAllColumnToSql(item, ctx, quotedAs, true)) || (isEmptySelect(q.shape, columnsCount) ? [] : [`${quotedAs}.*`]) : q.selectAllColumns ? q.selectAllColumns.map((item) => selectAllColumnToSql(item, ctx, quotedAs)) : isEmptySelect(q.shape, columnsCount) ? [] : ["*"];
7151
7207
  };
7152
- const selectAllSql = (q, quotedAs, columnsCount) => {
7153
- return q.join?.length || q.updateFrom || q.updateMany ? q.selectAllColumns?.map((item) => `${quotedAs}.${item}`) || (isEmptySelect(q.shape, columnsCount) ? [] : [`${quotedAs}.*`]) : q.selectAllColumns ? [...q.selectAllColumns] : isEmptySelect(q.shape, columnsCount) ? [] : ["*"];
7208
+ const selectAllColumnToSql = (item, ctx, quotedAs, prefix) => {
7209
+ if (typeof item !== "string") return item(ctx, quotedAs);
7210
+ return prefix ? `${quotedAs}.${item}` : item;
7154
7211
  };
7155
7212
  const isEmptySelect = (shape, columnsCount) => columnsCount === void 0 ? shape === anyShape ? false : isObjectEmpty(shape) : !columnsCount;
7156
7213
  const pushSubQuerySql = (ctx, mainQuery, query, as, list, quotedAs, aliases) => {
@@ -7184,7 +7241,7 @@ const pushSubQuerySql = (ctx, mainQuery, query, as, list, quotedAs, aliases) =>
7184
7241
  case "oneOrThrow": {
7185
7242
  const table = query.q.joinedForSelect;
7186
7243
  const shape = mainQuery.joinedShapes?.[as];
7187
- sql = makeRowToJson(table, shape, false);
7244
+ sql = makeRowToJson(ctx, table, shape, false);
7188
7245
  break;
7189
7246
  }
7190
7247
  case "all":
@@ -7711,6 +7768,14 @@ function pushLimitSQL(sql, values, q) {
7711
7768
  }
7712
7769
  }
7713
7770
  const pushUpdateSql = (ctx, query, q, quotedAs, isSubSql) => {
7771
+ const valuesJoinedAs = unsetValuesJoinedAsForMutativeSelectRelations(query);
7772
+ try {
7773
+ return pushUpdateSqlWithoutValuesJoinedAs(ctx, query, q, quotedAs, isSubSql);
7774
+ } finally {
7775
+ restoreValuesJoinedAsForMutativeSelectRelations(query, valuesJoinedAs);
7776
+ }
7777
+ };
7778
+ const pushUpdateSqlWithoutValuesJoinedAs = (ctx, query, q, quotedAs, isSubSql) => {
7714
7779
  const quotedTable = `"${query.table || q.from}"`;
7715
7780
  const from = quoteTableWithSchema(query);
7716
7781
  const set = [];
@@ -9569,6 +9634,8 @@ const toSql = (table, type, topCtx, isSubSql, cteName, calledByThen, dontAddTabl
9569
9634
  _queryInsert(upsertOrCreate, query.upsertInsert());
9570
9635
  upsertOrCreate.q.type = "upsert";
9571
9636
  }
9637
+ upsertOrCreate.q.appendQueries = query.upsertCreateAppendQueries;
9638
+ upsertOrCreate.q.asFns = query.upsertCreateAsFns;
9572
9639
  const { makeSql: makeSecondSql } = moveMutativeQueryToCteBase(toSql, ctx, upsertOrCreate, "insert");
9573
9640
  sql.push(makeFirstSql(isSubSql), "UNION ALL", makeSecondSql(isSubSql));
9574
9641
  } else {
@@ -9642,7 +9709,7 @@ const toSql = (table, type, topCtx, isSubSql, cteName, calledByThen, dontAddTabl
9642
9709
  if (ctx.topCtx.cteHooks.hasSelect) {
9643
9710
  if (prependedSelectParenthesis) result.text += ")";
9644
9711
  const { tableHooks, ensureCount } = ctx.topCtx.cteHooks;
9645
- const keyValues = [...tableHooks ? Object.entries(tableHooks).map(([cteName, data]) => `'${cteName}', (SELECT json_agg(${makeRowToJson(cteName, data.shape, false, true)}) FROM "${cteName}")`) : emptyArray, ...ensureCount ? Object.entries(ensureCount).map(([cteName, item]) => `'#${cteName}', CASE WHEN ${"count" in item ? `(SELECT count(*) FROM "${cteName}") < ${item.count}` : `(SELECT "${cteName}"."${item.jsonNotNull}" FROM "${cteName}") IS NULL`} THEN (SELECT 'not-found')::int END`) : emptyArray];
9712
+ const keyValues = [...tableHooks ? Object.entries(tableHooks).map(([cteName, data]) => `'${cteName}', (SELECT json_agg(${makeRowToJson(ctx, cteName, data.shape, false, true)}) FROM "${cteName}")`) : emptyArray, ...ensureCount ? Object.entries(ensureCount).map(([cteName, item]) => `'#${cteName}', CASE WHEN ${"count" in item ? `(SELECT count(*) FROM "${cteName}") < ${item.count}` : `(SELECT "${cteName}"."${item.jsonNotNull}" FROM "${cteName}") IS NULL`} THEN (SELECT 'not-found')::int END`) : emptyArray];
9646
9713
  result.text += ` UNION ALL SELECT ${"NULL, ".repeat(ctx.selectedCount || 0)}json_build_object(${keyValues.join(", ")})`;
9647
9714
  }
9648
9715
  }
@@ -9724,9 +9791,9 @@ const addTopCteInternal = (place, ctx, item, type, dontAddTableHook) => {
9724
9791
  topCTE.stack.pop();
9725
9792
  };
9726
9793
  const addWithToSql = (ctx, sql, isSubSql) => {
9727
- if (!isSubSql && ctx.topCtx.topCTE) {
9794
+ if (!isSubSql && ctx.topCtx.topCTE?.append.length) {
9728
9795
  const sqls = [];
9729
- if (!isSubSql && ctx.topCtx.topCTE) for (const append of ctx.topCtx.topCTE.append) sqls.push(...append);
9796
+ for (const append of ctx.topCtx.topCTE.append) sqls.push(...append);
9730
9797
  sql.text = "WITH " + sqls.join(", ") + " " + sql.text;
9731
9798
  }
9732
9799
  };
@@ -9770,17 +9837,23 @@ const quoteFromWithSchema = (schema, table) => {
9770
9837
  const s = typeof schema === "function" ? schema() : schema;
9771
9838
  return s ? `"${s}"."${table}"` : `"${table}"`;
9772
9839
  };
9773
- const makeRowToJson = (table, shape, aliasName, includingExplicitSelect) => {
9840
+ const makeRowToJson = (ctx, table, shape, aliasName, includingExplicitSelect) => {
9774
9841
  let isSimple = true;
9775
9842
  const list = [];
9776
9843
  for (const key in shape) {
9777
9844
  const column = shape[key];
9778
9845
  if (!includingExplicitSelect && column.data.explicitSelect) continue;
9779
- if (aliasName && column.data.name || column.data.jsonCast) isSimple = false;
9780
- list.push(`'${key}', "${table}"."${aliasName && column.data.name || key}"${column.data.jsonCast ? `::${column.data.jsonCast}` : ""}`);
9846
+ const selectSql = !column.data.computed ? column.data.selectSql : void 0;
9847
+ const outputColumn = getSelectedColumnData(column);
9848
+ if (aliasName && column.data.name || outputColumn.data.jsonCast || selectSql) isSimple = false;
9849
+ const value = selectSql ? selectSql.toSQL(ctx, `"${table}"`) : `"${table}"."${aliasName && column.data.name || key}"`;
9850
+ list.push(`'${key}', ${value}${outputColumn.data.jsonCast ? `::${outputColumn.data.jsonCast}` : ""}`);
9781
9851
  }
9782
9852
  return isSimple ? `row_to_json("${table}".*)` : `CASE WHEN to_jsonb("${table}") IS NULL THEN NULL ELSE json_build_object(` + list.join(", ") + ") END";
9783
9853
  };
9854
+ const getSelectedColumnData = (column) => {
9855
+ return column.data.selectSql?.result.value || column;
9856
+ };
9784
9857
  const getSqlText = (sql) => {
9785
9858
  if ("text" in sql) return sql.text;
9786
9859
  throw new Error(`Batch SQL is not supported in this query`);
@@ -12370,6 +12443,9 @@ var QueryExpressions = class {
12370
12443
  const _appendQuery = (main, append, asFn) => {
12371
12444
  return pushQueryValueImmutable(pushQueryValueImmutable(main, "appendQueries", prepareSubQueryForSql(main, append)), "asFns", asFn);
12372
12445
  };
12446
+ const _appendQueryOnUpsertCreate = (main, append, asFn) => {
12447
+ return pushQueryValueImmutable(pushQueryValueImmutable(main, "upsertCreateAppendQueries", prepareSubQueryForSql(main, append)), "upsertCreateAsFns", asFn);
12448
+ };
12373
12449
  const mergableObjects = new Set([
12374
12450
  "shape",
12375
12451
  "withShapes",
@@ -12416,6 +12492,10 @@ var MergeQueryMethods = class {
12416
12492
  return query;
12417
12493
  }
12418
12494
  };
12495
+ const applyColumnSelectSql = (column) => {
12496
+ const { selectSqlFn } = column.data;
12497
+ if (selectSqlFn) column.data.selectSql = selectSqlFn(new ColumnRefExpression(column, column.data.key));
12498
+ };
12419
12499
  const DEFAULT_PRIVILEGE = {
12420
12500
  OBJECT_TYPES: [
12421
12501
  "TABLES",
@@ -13786,6 +13866,10 @@ var Db = class extends QueryMethods {
13786
13866
  }
13787
13867
  if (column.data.explicitSelect) prepareSelectAll = true;
13788
13868
  else selectAllCount++;
13869
+ if (column.data.selectSqlFn) {
13870
+ applyColumnSelectSql(column);
13871
+ prepareSelectAll = true;
13872
+ }
13789
13873
  const { modifyQuery: mq } = column.data;
13790
13874
  if (mq) modifyQuery = pushOrNewArray(modifyQuery, (q) => mq(q, column));
13791
13875
  if (typeof column.data.default === "function") {
@@ -13843,7 +13927,12 @@ var Db = class extends QueryMethods {
13843
13927
  for (const key in shape) {
13844
13928
  const column = shape[key];
13845
13929
  if (!column.data.explicitSelect) {
13846
- list.push(column.data.name ? `"${column.data.name}" "${key}"` : `"${key}"`);
13930
+ const { data } = column;
13931
+ const { selectSql } = data;
13932
+ let item;
13933
+ if (selectSql) item = (ctx, quotedAs) => `(${selectSql.toSQL(ctx, quotedAs)}) "${key}"`;
13934
+ else item = data.name ? `"${data.name}" "${key}"` : `"${key}"`;
13935
+ list.push(item);
13847
13936
  selectAllShape[key] = column;
13848
13937
  }
13849
13938
  }
@@ -14401,6 +14490,7 @@ exports.VarCharColumn = VarCharColumn;
14401
14490
  exports.VirtualColumn = VirtualColumn;
14402
14491
  exports.XMLColumn = XMLColumn;
14403
14492
  exports._appendQuery = _appendQuery;
14493
+ exports._appendQueryOnUpsertCreate = _appendQueryOnUpsertCreate;
14404
14494
  exports._clone = _clone;
14405
14495
  exports._createDbSqlMethod = _createDbSqlMethod;
14406
14496
  exports._hookSelectColumns = _hookSelectColumns;