pqb 0.67.3 → 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
  */
@@ -10697,4 +10716,4 @@ declare const testTransaction: {
10697
10716
  */
10698
10717
  close(arg: Arg$1): Promise<void>;
10699
10718
  };
10700
- 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, _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 };
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;
@@ -6527,6 +6537,15 @@ const columnToSql = (ctx, data, shape, column, quotedAs, select) => {
6527
6537
  if (index !== -1) return columnWithDotToSql(ctx, data, shape, column, index, quotedAs, select);
6528
6538
  return simpleColumnToSQL(ctx, column, shape[column], quotedAs);
6529
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
+ };
6530
6549
  /**
6531
6550
  * in a case when ordering or grouping by a column which was selected as expression:
6532
6551
  * ```ts
@@ -6552,7 +6571,7 @@ const columnWithDotToSql = (ctx, data, shape, column, index, quotedAs, select) =
6552
6571
  const key = column.slice(index + 1);
6553
6572
  if (key === "*") {
6554
6573
  const shape = data.joinedShapes?.[table];
6555
- return shape ? select ? makeRowToJson(table, shape, true) : `"${table}".*` : column;
6574
+ return shape ? select ? makeRowToJson(ctx, table, shape, true) : `"${table}".*` : column;
6556
6575
  }
6557
6576
  const tableName = _getQueryAliasOrName(data, table);
6558
6577
  const quoted = `"${table}"`;
@@ -6564,6 +6583,22 @@ const columnWithDotToSql = (ctx, data, shape, column, index, quotedAs, select) =
6564
6583
  }
6565
6584
  return `"${tableName}"."${key}"`;
6566
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
+ };
6567
6602
  const columnToSqlWithAs = (ctx, data, column, as, quotedAs, select, jsonList) => {
6568
6603
  const index = column.indexOf(".");
6569
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);
@@ -6573,7 +6608,7 @@ const tableColumnToSqlWithAs = (ctx, data, column, table, key, as, quotedAs, sel
6573
6608
  if (jsonList) jsonList[as] = void 0;
6574
6609
  const shape = data.joinedShapes?.[table];
6575
6610
  if (shape) {
6576
- if (select) return makeRowToJson(table, shape, true) + ` "${as}"`;
6611
+ if (select) return makeRowToJson(ctx, table, shape, true) + ` "${as}"`;
6577
6612
  return `"${table}"."${table}" "${as}"`;
6578
6613
  }
6579
6614
  return column;
@@ -6581,10 +6616,10 @@ const tableColumnToSqlWithAs = (ctx, data, column, table, key, as, quotedAs, sel
6581
6616
  const tableName = _getQueryAliasOrName(data, table);
6582
6617
  const quoted = `"${table}"`;
6583
6618
  const col = quoted === quotedAs ? data.shape[key] : data.joinedShapes?.[tableName][key];
6584
- if (jsonList) jsonList[as] = col;
6619
+ if (jsonList) jsonList[as] = col && getSelectedColumnData(col);
6585
6620
  if (col) {
6621
+ if (col.data.selectSql) return `(${col.data.selectSql.toSQL(ctx, quoted)}) "${as}"`;
6586
6622
  if (col.data.name && col.data.name !== key) return `"${tableName}"."${col.data.name}" "${as}"`;
6587
- if (col.data.computed) return `(${col.data.computed.toSQL(ctx, quoted)}) "${as}"`;
6588
6623
  }
6589
6624
  return `"${tableName}"."${key}"${key === as ? "" : ` "${as}"`}`;
6590
6625
  };
@@ -6594,10 +6629,10 @@ const ownColumnToSqlWithAs = (ctx, data, column, as, quotedAs, select, jsonList)
6594
6629
  return `"${column}"."${column}" "${as}"`;
6595
6630
  }
6596
6631
  const col = data.shape[column];
6597
- if (jsonList) jsonList[as] = col;
6632
+ if (jsonList) jsonList[as] = col && getSelectedColumnData(col);
6598
6633
  if (col) {
6634
+ if (col.data.selectSql) return `(${col.data.selectSql.toSQL(ctx, quotedAs)}) "${as}"`;
6599
6635
  if (col.data.name && col.data.name !== column) return `${quotedAs ? `${quotedAs}.` : ""}"${col.data.name}"${col.data.name === as ? "" : ` "${as}"`}`;
6600
- if (col.data.computed) return `(${col.data.computed.toSQL(ctx, quotedAs)}) "${as}"`;
6601
6636
  }
6602
6637
  return `${quotedAs ? `${quotedAs}.` : ""}"${column}"${column === as ? "" : ` "${as}"`}`;
6603
6638
  };
@@ -6753,7 +6788,7 @@ var SelectItemExpression = class extends Expression {
6753
6788
  }
6754
6789
  makeSQL(ctx, quotedAs) {
6755
6790
  const q = this.q;
6756
- 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);
6757
6792
  }
6758
6793
  };
6759
6794
  const _getSelectableColumn = (q, arg) => {
@@ -7110,12 +7145,12 @@ const selectToSqlList = (ctx, table, query, quotedAs, hookSelect = query.hookSel
7110
7145
  quotedTable = `"${tableName}"`;
7111
7146
  columnName = select.slice(index + 1);
7112
7147
  col = table.q.joinedShapes?.[tableName]?.[columnName];
7113
- 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);
7114
7149
  } else {
7115
7150
  quotedTable = quotedAs;
7116
7151
  columnName = select;
7117
7152
  col = query.shape[select];
7118
- sql = simpleColumnToSQL(ctx, select, col, quotedAs);
7153
+ sql = selectedColumnToSql(ctx, table.q, query.shape, select, quotedAs);
7119
7154
  }
7120
7155
  } else {
7121
7156
  columnName = column;
@@ -7155,17 +7190,24 @@ const selectToSql = (ctx, table, query, quotedAs, hookSelect = query.hookSelect,
7155
7190
  return selectToSqlList(ctx, table, query, quotedAs, hookSelect, isSubSql, aliases, jsonList, delayedRelationSelect).join(", ");
7156
7191
  };
7157
7192
  const internalSelectAllSql = (ctx, query, quotedAs, jsonList) => {
7158
- 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
+ }
7159
7197
  let columnsCount;
7160
7198
  if (query.shape !== anyShape) {
7161
7199
  columnsCount = 0;
7162
7200
  for (const key in query.shape) if (!query.shape[key].data.explicitSelect) columnsCount++;
7163
7201
  ctx.selectedCount += columnsCount;
7164
7202
  }
7165
- 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) ? [] : ["*"];
7166
7207
  };
7167
- const selectAllSql = (q, quotedAs, columnsCount) => {
7168
- 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;
7169
7211
  };
7170
7212
  const isEmptySelect = (shape, columnsCount) => columnsCount === void 0 ? shape === anyShape ? false : isObjectEmpty(shape) : !columnsCount;
7171
7213
  const pushSubQuerySql = (ctx, mainQuery, query, as, list, quotedAs, aliases) => {
@@ -7199,7 +7241,7 @@ const pushSubQuerySql = (ctx, mainQuery, query, as, list, quotedAs, aliases) =>
7199
7241
  case "oneOrThrow": {
7200
7242
  const table = query.q.joinedForSelect;
7201
7243
  const shape = mainQuery.joinedShapes?.[as];
7202
- sql = makeRowToJson(table, shape, false);
7244
+ sql = makeRowToJson(ctx, table, shape, false);
7203
7245
  break;
7204
7246
  }
7205
7247
  case "all":
@@ -9667,7 +9709,7 @@ const toSql = (table, type, topCtx, isSubSql, cteName, calledByThen, dontAddTabl
9667
9709
  if (ctx.topCtx.cteHooks.hasSelect) {
9668
9710
  if (prependedSelectParenthesis) result.text += ")";
9669
9711
  const { tableHooks, ensureCount } = ctx.topCtx.cteHooks;
9670
- 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];
9671
9713
  result.text += ` UNION ALL SELECT ${"NULL, ".repeat(ctx.selectedCount || 0)}json_build_object(${keyValues.join(", ")})`;
9672
9714
  }
9673
9715
  }
@@ -9795,17 +9837,23 @@ const quoteFromWithSchema = (schema, table) => {
9795
9837
  const s = typeof schema === "function" ? schema() : schema;
9796
9838
  return s ? `"${s}"."${table}"` : `"${table}"`;
9797
9839
  };
9798
- const makeRowToJson = (table, shape, aliasName, includingExplicitSelect) => {
9840
+ const makeRowToJson = (ctx, table, shape, aliasName, includingExplicitSelect) => {
9799
9841
  let isSimple = true;
9800
9842
  const list = [];
9801
9843
  for (const key in shape) {
9802
9844
  const column = shape[key];
9803
9845
  if (!includingExplicitSelect && column.data.explicitSelect) continue;
9804
- if (aliasName && column.data.name || column.data.jsonCast) isSimple = false;
9805
- 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}` : ""}`);
9806
9851
  }
9807
9852
  return isSimple ? `row_to_json("${table}".*)` : `CASE WHEN to_jsonb("${table}") IS NULL THEN NULL ELSE json_build_object(` + list.join(", ") + ") END";
9808
9853
  };
9854
+ const getSelectedColumnData = (column) => {
9855
+ return column.data.selectSql?.result.value || column;
9856
+ };
9809
9857
  const getSqlText = (sql) => {
9810
9858
  if ("text" in sql) return sql.text;
9811
9859
  throw new Error(`Batch SQL is not supported in this query`);
@@ -12444,6 +12492,10 @@ var MergeQueryMethods = class {
12444
12492
  return query;
12445
12493
  }
12446
12494
  };
12495
+ const applyColumnSelectSql = (column) => {
12496
+ const { selectSqlFn } = column.data;
12497
+ if (selectSqlFn) column.data.selectSql = selectSqlFn(new ColumnRefExpression(column, column.data.key));
12498
+ };
12447
12499
  const DEFAULT_PRIVILEGE = {
12448
12500
  OBJECT_TYPES: [
12449
12501
  "TABLES",
@@ -13814,6 +13866,10 @@ var Db = class extends QueryMethods {
13814
13866
  }
13815
13867
  if (column.data.explicitSelect) prepareSelectAll = true;
13816
13868
  else selectAllCount++;
13869
+ if (column.data.selectSqlFn) {
13870
+ applyColumnSelectSql(column);
13871
+ prepareSelectAll = true;
13872
+ }
13817
13873
  const { modifyQuery: mq } = column.data;
13818
13874
  if (mq) modifyQuery = pushOrNewArray(modifyQuery, (q) => mq(q, column));
13819
13875
  if (typeof column.data.default === "function") {
@@ -13871,7 +13927,12 @@ var Db = class extends QueryMethods {
13871
13927
  for (const key in shape) {
13872
13928
  const column = shape[key];
13873
13929
  if (!column.data.explicitSelect) {
13874
- 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);
13875
13936
  selectAllShape[key] = column;
13876
13937
  }
13877
13938
  }