pqb 0.67.3 → 0.67.5

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
@@ -2742,7 +2742,7 @@ type SelectArgs<T extends SelectSelf> = ('*' | keyof T['__selectable'])[];
2742
2742
  interface SubQueryAddition<T extends PickQueryWithData> extends IsSubQuery {
2743
2743
  withData: T['withData'];
2744
2744
  }
2745
- type SelectAsFnArg<T extends PickQueryRelationsWithData> = EmptyObject extends T['relations'] ? T : { [K in keyof T['relations'] | keyof T]: K extends keyof T['relations'] ? T['relations'][K]['maybeSingle'] & SubQueryAddition<T> : K extends keyof T ? T[K] : never };
2745
+ type SelectAsFnArg<T extends PickQueryRelationsWithData> = EmptyObject extends T['relations'] ? T : { [K in keyof T['relations'] | keyof T]: K extends keyof T['relations'] ? RelationQueryMaybeSingle<T['relations'][K]> & SubQueryAddition<T> : K extends keyof T ? T[K] : never };
2746
2746
  interface SelectAsArg<T extends SelectSelf> {
2747
2747
  [K: string]: keyof T['__selectable'] | Expression | ((q: SelectAsFnArg<T>) => unknown);
2748
2748
  }
@@ -4822,6 +4822,7 @@ interface QueryInternal<SinglePrimaryKey = any, UniqueColumns = any, UniqueColum
4822
4822
  noPrimaryKey: boolean;
4823
4823
  comment?: string;
4824
4824
  readOnly?: boolean;
4825
+ materialized?: boolean;
4825
4826
  primaryKeys?: string[];
4826
4827
  singlePrimaryKey: SinglePrimaryKey;
4827
4828
  uniqueColumns: UniqueColumns;
@@ -4835,6 +4836,14 @@ interface QueryInternal<SinglePrimaryKey = any, UniqueColumns = any, UniqueColum
4835
4836
  rls?: Rls.Options;
4836
4837
  tableRls?: Rls.TableConfig;
4837
4838
  tableGrants?: Grant.TableClassGrant[];
4839
+ viewData?: {
4840
+ sql?: string | RawSqlBase;
4841
+ recursive?: boolean;
4842
+ checkOption?: 'LOCAL' | 'CASCADED';
4843
+ securityBarrier?: boolean;
4844
+ securityInvoker?: boolean;
4845
+ withData?: boolean;
4846
+ };
4838
4847
  managedRolesSql?: string;
4839
4848
  defaultGrantedBy?: string;
4840
4849
  grants?: Grant.InternalPrivilege[];
@@ -4915,6 +4924,10 @@ interface DbTableOptions<ColumnTypes, Table extends string | undefined, Shape ex
4915
4924
  * Disallow runtime create, update, and delete operations.
4916
4925
  */
4917
4926
  readOnly?: true | undefined;
4927
+ /**
4928
+ * Mark query objects as backed by a materialized relation.
4929
+ */
4930
+ materialized?: true | undefined;
4918
4931
  /**
4919
4932
  * Computed SQL or JS columns definitions
4920
4933
  */
@@ -4928,7 +4941,7 @@ type DbTableOptionScopes<Table extends string | undefined, Shape extends Column.
4928
4941
  interface QueryBuilder extends Query.NotReadOnlyQuery {
4929
4942
  returnType: undefined;
4930
4943
  }
4931
- declare class Db<Table extends string | undefined = undefined, Shape extends Column.QueryColumnsInit = Column.QueryColumnsInit, PrimaryKeys = never, UniqueColumns = never, UniqueColumnTuples = never, UniqueConstraints = never, ColumnTypes = DefaultColumnTypes<ColumnSchemaConfig>, ShapeWithComputed extends Column.QueryColumnsInit = Shape, Scopes extends RecordUnknown | undefined = EmptyObject, DefaultSelect extends keyof Shape = keyof Shape, ReadOnly extends true | undefined = undefined> extends QueryMethods<ColumnTypes> implements Query {
4944
+ declare class Db<Table extends string | undefined = undefined, Shape extends Column.QueryColumnsInit = Column.QueryColumnsInit, PrimaryKeys = never, UniqueColumns = never, UniqueColumnTuples = never, UniqueConstraints = never, ColumnTypes = DefaultColumnTypes<ColumnSchemaConfig>, ShapeWithComputed extends Column.QueryColumnsInit = Shape, Scopes extends RecordUnknown | undefined = EmptyObject, DefaultSelect extends keyof Shape = keyof Shape, ReadOnly extends true | undefined = undefined, Materialized extends true | undefined = undefined> extends QueryMethods<ColumnTypes> implements Query {
4932
4945
  adapterNotInTransaction: Adapter;
4933
4946
  qb: QueryBuilder;
4934
4947
  table: Table;
@@ -4937,7 +4950,8 @@ declare class Db<Table extends string | undefined = undefined, Shape extends Col
4937
4950
  __isQuery: true;
4938
4951
  __as: Table & string;
4939
4952
  __selectable: SelectableFromShape<ShapeWithComputed, Table>;
4940
- readOnly: ReadOnly;
4953
+ __readOnly: ReadOnly;
4954
+ __materialized: Materialized;
4941
4955
  __hasSelect: boolean;
4942
4956
  __hasWhere: boolean;
4943
4957
  __defaults: { [K in { [K in keyof Shape]: unknown extends Shape[K]['data']['default'] ? never : K }[keyof Shape]]: true };
@@ -4958,7 +4972,7 @@ declare class Db<Table extends string | undefined = undefined, Shape extends Col
4958
4972
  internal: QueryInternal<{ [K in keyof PrimaryKeys]: (keyof PrimaryKeys extends K ? never : keyof PrimaryKeys) extends never ? PrimaryKeys[K] : never }[keyof PrimaryKeys], PrimaryKeys | UniqueColumns, { [K in keyof Shape]: Shape[K]['data']['unique'] extends string ? K : never }[keyof Shape] | keyof PrimaryKeys, UniqueColumnTuples, UniqueConstraints>;
4959
4973
  catch: QueryCatch;
4960
4974
  shape: ShapeWithComputed;
4961
- constructor(adapterNotInTransaction: Adapter, qb: QueryBuilder, table: Table | undefined, shape: ShapeWithComputed, columnTypes: ColumnTypes, asyncStorage: AsyncLocalStorage<AsyncState>, options: DbTableOptions<ColumnTypes, Table, ShapeWithComputed>, tableData?: TableData);
4975
+ constructor(adapterNotInTransaction: Adapter, qb: QueryBuilder, table: Table | undefined, shape: ShapeWithComputed, columnTypes: ColumnTypes, asyncStorage: AsyncLocalStorage<AsyncState>, options: DbTableOptions<ColumnTypes, Table, ShapeWithComputed>, tableData?: TableData, viewData?: QueryInternal['viewData']);
4962
4976
  /**
4963
4977
  * When in transaction, returns a db adapter object for the transaction,
4964
4978
  * returns a default adapter object otherwise.
@@ -5027,7 +5041,7 @@ declare class Db<Table extends string | undefined = undefined, Shape extends Col
5027
5041
  queryArrays<R extends any[] = any[]>(...args: SQLQueryArgs): Promise<QueryResult<R>>;
5028
5042
  }
5029
5043
  interface DbTableConstructor<ColumnTypes> {
5030
- <Table extends string, Shape extends Column.QueryColumnsInit, Data extends MaybeArray<TableDataItem>, Options extends DbTableOptions<ColumnTypes, Table, Shape>>(table: Table, shape?: ((t: ColumnTypes) => Shape) | Shape, tableData?: TableDataFn<Shape, Data>, options?: Options): Db<Table, Shape, keyof ShapeColumnPrimaryKeys<Shape> extends never ? never : ShapeColumnPrimaryKeys<Shape>, ShapeUniqueColumns<Shape> | TableDataItemsUniqueColumns<Shape, Data>, TableDataItemsUniqueColumnTuples<Shape, Data>, UniqueConstraints<Shape> | TableDataItemsUniqueConstraints<Data>, ColumnTypes, Shape & ComputedColumnsFromOptions<Options['computed']>, MapTableScopesOption<Options>, ColumnsShape.DefaultSelectKeys<Shape>, Options['readOnly'] extends true ? true : undefined>;
5044
+ <Table extends string, Shape extends Column.QueryColumnsInit, Data extends MaybeArray<TableDataItem>, Options extends DbTableOptions<ColumnTypes, Table, Shape>>(table: Table, shape?: ((t: ColumnTypes) => Shape) | Shape, tableData?: TableDataFn<Shape, Data>, options?: Options): Db<Table, Shape, keyof ShapeColumnPrimaryKeys<Shape> extends never ? never : ShapeColumnPrimaryKeys<Shape>, ShapeUniqueColumns<Shape> | TableDataItemsUniqueColumns<Shape, Data>, TableDataItemsUniqueColumnTuples<Shape, Data>, UniqueConstraints<Shape> | TableDataItemsUniqueConstraints<Data>, ColumnTypes, Shape & ComputedColumnsFromOptions<Options['computed']>, MapTableScopesOption<Options>, ColumnsShape.DefaultSelectKeys<Shape>, Options['readOnly'] extends true ? true : undefined, Options['materialized'] extends true ? true : undefined>;
5031
5045
  }
5032
5046
  interface DbSqlMethod<ColumnTypes> {
5033
5047
  <T>(...args: StaticSQLArgs): RawSql<Column.Pick.QueryColumnOfType<T>, ColumnTypes>;
@@ -6255,6 +6269,14 @@ declare abstract class QueryHooks {
6255
6269
  */
6256
6270
  catchAfterCommitError<T>(this: T, fn: AfterCommitErrorHandler): T;
6257
6271
  }
6272
+ interface ColumnDataSelectSqlProp {
6273
+ selectSql?: Expression;
6274
+ selectSqlFn?: SelectSqlCallback;
6275
+ }
6276
+ interface SelectSqlCallback {
6277
+ (column: ColumnRefExpression<Column.Pick.QueryColumn>): Expression;
6278
+ }
6279
+ 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
6280
  declare namespace Column {
6259
6281
  export namespace Modifiers {
6260
6282
  export interface IsPrimaryKey<Name extends string> {
@@ -6895,6 +6917,13 @@ declare abstract class Column<Schema extends ColumnTypeSchemaArg = ColumnTypeSch
6895
6917
  * ```
6896
6918
  */
6897
6919
  select<T extends Column.Pick.Data, Value extends boolean>(this: T, value: Value): Column.Modifiers.DefaultSelect<T, Value>;
6920
+ /**
6921
+ * Set SQL to use when selecting this column.
6922
+ *
6923
+ * The column remains a regular writable database column. Create, update,
6924
+ * filters, ordering, grouping, and migrations still use the physical column.
6925
+ */
6926
+ selectSql<T extends Column.Pick.DataAndDataType, Expr extends Expression>(this: T, fn: (column: ColumnRefExpression<T & Column.Pick.QueryColumn>) => Expr): SelectSqlColumn<T, Expr>;
6898
6927
  /**
6899
6928
  * 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
6929
  *
@@ -7496,8 +7525,8 @@ type CreateData<T extends CreateSelf> = EmptyObject extends T['relations'] ? Cre
7496
7525
  type CreateDataWithDefaults<T extends CreateSelf, Defaults extends PropertyKey> = { [K in keyof T['inputType'] as K extends Defaults ? never : K]: K extends Defaults ? never : CreateColumn<T, K> } & { [K in Defaults]?: K extends keyof T['inputType'] ? CreateColumn<T, K> : never };
7497
7526
  type CreateDataWithDefaultsForRelations<T extends CreateSelf, Defaults extends keyof T['inputType'], OmitFKeys extends PropertyKey> = { [K in keyof T['inputType'] as K extends Defaults | OmitFKeys ? never : K]: K extends Defaults | OmitFKeys ? never : CreateColumn<T, K> } & { [K in Defaults as K extends OmitFKeys ? never : K]?: CreateColumn<T, K> };
7498
7527
  type CreateColumn<T extends CreateSelf, K extends keyof T['inputType']> = T['inputType'][K] | ((q: T) => QueryOrExpression<T['inputType'][K]>);
7499
- type CreateRelationsData<T extends CreateSelf> = CreateDataWithDefaultsForRelations<T, keyof T['__defaults'], T['relations'][keyof T['relations']]['omitForeignKeyInCreate']> & CreateRelationsDataOmittingFKeys<T, T['relations'][keyof T['relations']]['dataForCreate']> & T['relations'][keyof T['relations']]['optionalDataForCreate'];
7500
- type CreateRelationsDataOmittingFKeys<T extends CreateSelf, Union> = (Union extends RelationConfigDataForCreate ? (u: Union['columns'] extends keyof T['__defaults'] ? { [P in Exclude<Union['columns'] & keyof T['inputType'], keyof T['__defaults']>]: CreateColumn<T, P> } & { [P in keyof T['__defaults'] & Union['columns']]?: CreateColumn<T, P> } & Partial<Union['nested']> : { [P in Union['columns'] & keyof T['inputType']]: CreateColumn<T, P> } | Union['nested']) => void : never) extends ((u: infer Obj) => void) ? Obj : never;
7528
+ type CreateRelationsData<T extends CreateSelf> = CreateDataWithDefaultsForRelations<T, keyof T['__defaults'], T['relations'][keyof T['relations']]['omitForeignKeyInCreate']> & CreateRelationsDataOmittingFKeys<T, T['relations'][keyof T['relations']]['dataForCreate']>;
7529
+ type CreateRelationsDataOmittingFKeys<T extends CreateSelf, Union> = (Union extends RelationConfigDataForCreate ? (u: Union['columns'] extends keyof T['__defaults'] ? Pick<CreateDataWithDefaults<T, keyof T['__defaults']>, Union['columns']> & Partial<Union['nested']> : (Pick<{ [P in keyof T['inputType']]: CreateColumn<T, P> }, Union['columns'] & keyof T['inputType']> & { [K in keyof Union['nested']]?: never }) | Union['nested']) => void : (u: Union) => void) extends ((u: infer Obj) => void) ? Obj : never;
7501
7530
  type CreateResult<T extends CreateSelf, Data> = T extends {
7502
7531
  isCount: true;
7503
7532
  } ? T : T['returnType'] extends undefined | 'all' ? SetQueryReturnsOneResult<T, NarrowCreateResult<T, Data>> : T['returnType'] extends 'pluck' ? SetQueryReturnsColumnResult<T, NarrowCreateResult<T, Data>> : SetQueryResult<T, NarrowCreateResult<T, Data>>;
@@ -8369,7 +8398,7 @@ declare const setColumnParse: (column: Column.Pick.Data, fn: (input: any) => unk
8369
8398
  declare const setColumnParseNull: (column: Column.Pick.Data, fn: () => unknown, nullSchema?: unknown) => any;
8370
8399
  declare const setColumnEncode: (column: Column.Pick.Data, fn: (input: any) => unknown, inputSchema?: unknown) => any;
8371
8400
  declare const getColumnBaseType: (column: Column.Pick.Data, domainsMap: DbStructureDomainsMap, type: string) => string;
8372
- interface ColumnDataComputedProp {
8401
+ interface ColumnDataComputedProp extends ColumnDataSelectSqlProp {
8373
8402
  computed?: Expression;
8374
8403
  }
8375
8404
  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 +8619,10 @@ type QueryType = undefined | null | 'upsert' | 'insert' | 'update' | 'delete';
8590
8619
  interface AsFn {
8591
8620
  (as: string): void;
8592
8621
  }
8622
+ interface SelectAllColumnExpression {
8623
+ (ctx: ToSQLCtx, quotedAs?: string): string;
8624
+ }
8625
+ type SelectAllColumn = string | SelectAllColumnExpression;
8593
8626
  interface QueryData extends QueryDataAliases, PickQueryDataParsers, HasHookSelect, MutativeQueriesSelectRelationsQueryData {
8594
8627
  type: QueryType;
8595
8628
  adapter: Adapter;
@@ -8625,7 +8658,7 @@ interface QueryData extends QueryDataAliases, PickQueryDataParsers, HasHookSelec
8625
8658
  sql: string;
8626
8659
  aliases: string[];
8627
8660
  };
8628
- selectAllColumns?: string[];
8661
+ selectAllColumns?: SelectAllColumn[];
8629
8662
  /**
8630
8663
  * Subset of the `shape` that only includes columns with no `data.explicitSelect`.
8631
8664
  */
@@ -10212,8 +10245,8 @@ declare class QueryMethods<ColumnTypes> {
10212
10245
  if<T extends PickQueryResultReturnType, R extends PickQueryResult>(this: T, condition: boolean | null | undefined, fn: (q: T) => R & {
10213
10246
  returnType: T['returnType'];
10214
10247
  }): QueryIfResult<T, R>;
10215
- queryRelated<T extends PickQueryRelations, RelName extends keyof T['relations']>(this: T, relName: RelName, params: T['relations'][RelName]['params']): T['relations'][RelName]['maybeSingle'];
10216
- chain<T extends PickQuerySelectableShapeRelationsReturnTypeIsSubQuery, RelName extends keyof T['relations']>(this: T, relName: RelName): T['__subQuery'] extends true | undefined ? [T['returnType'], T['relations'][RelName]['returnsOne']] extends ['one' | 'oneOrThrow', true] ? { [K in keyof T['relations'][RelName]['maybeSingle']]: K extends '__selectable' ? T['relations'][RelName]['maybeSingle']['__selectable'] & Omit<T['__selectable'], keyof T['shape']> : T['relations'][RelName]['maybeSingle'][K] } & IsSubQuery : JoinResultRequireMain<T['relations'][RelName]['query'], Omit<T['__selectable'], keyof T['shape']>> : T['relations'][RelName]['query'];
10248
+ queryRelated<T extends PickQueryRelations, RelName extends keyof T['relations']>(this: T, relName: RelName, params: T['relations'][RelName]['params']): RelationQueryMaybeSingle<T['relations'][RelName]>;
10249
+ chain<T extends PickQuerySelectableShapeRelationsReturnTypeIsSubQuery, RelName extends keyof T['relations']>(this: T, relName: RelName): T['__subQuery'] extends true | undefined ? [T['returnType'], T['relations'][RelName]['returnsOne']] extends ['one' | 'oneOrThrow', true] ? { [K in keyof RelationQueryMaybeSingle<T['relations'][RelName]>]: K extends '__selectable' ? RelationQueryMaybeSingle<T['relations'][RelName]>['__selectable'] & Omit<T['__selectable'], keyof T['shape']> : RelationQueryMaybeSingle<T['relations'][RelName]>[K] } & IsSubQuery : JoinResultRequireMain<T['relations'][RelName]['query'], Omit<T['__selectable'], keyof T['shape']>> : T['relations'][RelName]['query'];
10217
10250
  }
10218
10251
  interface DbExtension {
10219
10252
  name: string;
@@ -10225,6 +10258,8 @@ interface GeneratorIgnore {
10225
10258
  domains?: string[];
10226
10259
  extensions?: string[];
10227
10260
  tables?: string[];
10261
+ /** Regular views to ignore during migration generation. */
10262
+ views?: (string | RegExp)[];
10228
10263
  grants?: Grant.Ignore;
10229
10264
  }
10230
10265
  interface DbDomainArg<ColumnTypes> {
@@ -10288,11 +10323,15 @@ interface Query extends IsQuery, PickQueryTable, PickQueryShape, PickQuerySelect
10288
10323
  relations: RelationsBase;
10289
10324
  relationQueries: IsQueries;
10290
10325
  error: new (message: string, length: number, name: QueryErrorName) => QueryError;
10291
- readOnly: true | undefined;
10326
+ __readOnly: true | undefined;
10327
+ __materialized: true | undefined;
10292
10328
  }
10293
10329
  declare namespace Query {
10294
10330
  interface NotReadOnlyQuery extends Query {
10295
- readOnly: undefined;
10331
+ __readOnly: undefined;
10332
+ }
10333
+ interface MaterializedQuery extends Query {
10334
+ __materialized: true;
10296
10335
  }
10297
10336
  namespace Order {
10298
10337
  type Arg<T extends Order.ArgThis> = Order.Arg<T>;
@@ -10306,7 +10345,10 @@ declare namespace Query {
10306
10345
  returnType: 'value' | 'valueOrThrow';
10307
10346
  }
10308
10347
  interface IsNotReadOnly {
10309
- readOnly: undefined;
10348
+ __readOnly: undefined;
10349
+ }
10350
+ interface IsMaterialized {
10351
+ __materialized: true;
10310
10352
  }
10311
10353
  }
10312
10354
  }
@@ -10367,19 +10409,18 @@ declare const isQueryReturnsAll: (q: Query) => boolean;
10367
10409
  interface RelationJoinQuery {
10368
10410
  (joiningQuery: IsQuery, baseQuery: IsQuery): IsQuery;
10369
10411
  }
10370
- interface RelationConfigQuery extends PickQueryResult, PickQuerySelectable, PickQueryShape, PickQueryTable, PickQueryAs, PickQueryRelations {}
10412
+ interface RelationConfigQuery extends PickQueryResult, PickQuerySelectable, PickQueryShape, PickQueryTable, PickQueryAs, PickQueryRelations, PickQueryReturnType {}
10371
10413
  interface RelationConfigBase extends IsQuery {
10372
10414
  returnsOne: boolean;
10415
+ required?: unknown;
10373
10416
  query: RelationConfigQuery;
10374
10417
  joinQuery: RelationJoinQuery;
10375
10418
  reverseJoin: RelationJoinQuery;
10376
10419
  params: unknown;
10377
10420
  queryRelated(params: unknown): unknown;
10378
10421
  modifyRelatedQuery?(relatedQuery: IsQuery): (query: IsQuery) => void;
10379
- maybeSingle: PickQuerySelectableReturnType;
10380
10422
  omitForeignKeyInCreate: PropertyKey;
10381
- dataForCreate: RelationConfigDataForCreate | undefined;
10382
- optionalDataForCreate: unknown;
10423
+ dataForCreate: unknown;
10383
10424
  dataForUpdate: unknown;
10384
10425
  dataForUpdateOne: unknown;
10385
10426
  primaryKeys: string[];
@@ -10391,6 +10432,7 @@ interface RelationConfigDataForCreate {
10391
10432
  interface RelationsBase {
10392
10433
  [K: string]: RelationConfigBase;
10393
10434
  }
10435
+ type RelationQueryMaybeSingle<T extends RelationConfigBase> = T['returnsOne'] extends true ? T['required'] extends true ? QueryManyTake<T['query']> : QueryManyTakeOptional<T['query']> : T['query'];
10394
10436
  interface PickQueryTable {
10395
10437
  table?: string;
10396
10438
  }
@@ -10438,7 +10480,6 @@ interface PickQuerySelectableResultRelationsWithDataReturnTypeShapeAs extends Pi
10438
10480
  interface PickQuerySelectableShape extends PickQuerySelectable, PickQueryShape {}
10439
10481
  interface PickQuerySelectableColumnTypes extends PickQuerySelectable, PickQueryColumTypes {}
10440
10482
  interface PickQuerySelectableShapeRelationsReturnTypeIsSubQuery extends PickQueryIsSubQuery, PickQuerySelectable, PickQueryShape, PickQueryRelations, PickQueryReturnType {}
10441
- interface PickQuerySelectableReturnType extends PickQuerySelectable, PickQueryReturnType {}
10442
10483
  interface PickQuerySelectableResultInputTypeAs extends PickQuerySelectableResult, PickQueryInputType, PickQueryAs {}
10443
10484
  interface PickQuerySelectableResultAs extends PickQuerySelectable, PickQueryResult, PickQueryAs {}
10444
10485
  interface PickQueryIsSubQuery {
@@ -10542,6 +10583,20 @@ declare abstract class QueryAsMethods {
10542
10583
  }
10543
10584
  declare const _appendQuery: (main: Query, append: Query, asFn: (as: string) => void) => Query;
10544
10585
  declare const _appendQueryOnUpsertCreate: (main: Query, append: Query, asFn: (as: string) => void) => Query;
10586
+ interface RefreshMaterializedViewOptions {
10587
+ /**
10588
+ * Refresh the materialized view without blocking concurrent selects.
10589
+ */
10590
+ concurrently?: boolean;
10591
+ /**
10592
+ * Use `WITH DATA` or `WITH NO DATA` for the refreshed materialized view.
10593
+ */
10594
+ withData?: boolean;
10595
+ }
10596
+ /**
10597
+ * Refresh a materialized view.
10598
+ */
10599
+ declare const refreshMaterializedView: <T extends Query.MaterializedQuery>(query: T, options?: RefreshMaterializedViewOptions) => Promise<void>;
10545
10600
  declare const getPrimaryKeys: (q: Query) => string[];
10546
10601
  /**
10547
10602
  * Set value into the object in query data, create the object if it doesn't yet exist.
@@ -10697,4 +10752,4 @@ declare const testTransaction: {
10697
10752
  */
10698
10753
  close(arg: Arg$1): Promise<void>;
10699
10754
  };
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 };
10755
+ 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 RefreshMaterializedViewOptions, 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, refreshMaterializedView, 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":
@@ -7991,12 +8033,12 @@ var FnExpression = class extends Expression {
7991
8033
  if (options.distinct && !options.withinGroup) sql.push("DISTINCT ");
7992
8034
  const q = this.q;
7993
8035
  sql.push(this.args.map((arg) => {
7994
- if (typeof arg === "string") return arg === "*" ? "*" : columnToSql(ctx, q, q.shape, arg, quotedAs);
8036
+ if (typeof arg === "string") return arg === "*" ? "*" : fnArgToSql(ctx, q, arg, quotedAs);
7995
8037
  else if (arg instanceof Expression) return arg.toSQL(ctx, quotedAs);
7996
8038
  else if ("pairs" in arg) {
7997
8039
  const args = [];
7998
8040
  const { pairs } = arg;
7999
- for (const key in pairs) args.push(`${addValue(values, key)}::text, ${rawOrColumnToSql(ctx, q, pairs[key], quotedAs)}`);
8041
+ for (const key in pairs) args.push(`${addValue(values, key)}::text, ${fnArgToSql(ctx, q, pairs[key], quotedAs)}`);
8000
8042
  return args.join(", ");
8001
8043
  } else return addValue(values, arg.value);
8002
8044
  }).join(", "));
@@ -8020,6 +8062,13 @@ var FnExpression = class extends Expression {
8020
8062
  return sql.join("");
8021
8063
  }
8022
8064
  };
8065
+ const fnArgToSql = (ctx, data, arg, quotedAs) => {
8066
+ if (typeof arg === "string") {
8067
+ if (arg.endsWith(".*") || data.valuesJoinedAs?.[arg]) return columnToSql(ctx, data, data.shape, arg, quotedAs);
8068
+ return selectedColumnToSql(ctx, data, data.shape, arg, quotedAs);
8069
+ }
8070
+ return arg.toSQL(ctx, quotedAs);
8071
+ };
8023
8072
  function makeFnExpression(self, type, fn, args, options) {
8024
8073
  const q = extendQuery(self, type.operators);
8025
8074
  q.baseQuery.type = ExpressionTypeMethod.prototype.type;
@@ -9667,7 +9716,7 @@ const toSql = (table, type, topCtx, isSubSql, cteName, calledByThen, dontAddTabl
9667
9716
  if (ctx.topCtx.cteHooks.hasSelect) {
9668
9717
  if (prependedSelectParenthesis) result.text += ")";
9669
9718
  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];
9719
+ 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
9720
  result.text += ` UNION ALL SELECT ${"NULL, ".repeat(ctx.selectedCount || 0)}json_build_object(${keyValues.join(", ")})`;
9672
9721
  }
9673
9722
  }
@@ -9795,17 +9844,23 @@ const quoteFromWithSchema = (schema, table) => {
9795
9844
  const s = typeof schema === "function" ? schema() : schema;
9796
9845
  return s ? `"${s}"."${table}"` : `"${table}"`;
9797
9846
  };
9798
- const makeRowToJson = (table, shape, aliasName, includingExplicitSelect) => {
9847
+ const makeRowToJson = (ctx, table, shape, aliasName, includingExplicitSelect) => {
9799
9848
  let isSimple = true;
9800
9849
  const list = [];
9801
9850
  for (const key in shape) {
9802
9851
  const column = shape[key];
9803
9852
  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}` : ""}`);
9853
+ const selectSql = !column.data.computed ? column.data.selectSql : void 0;
9854
+ const outputColumn = getSelectedColumnData(column);
9855
+ if (aliasName && column.data.name || outputColumn.data.jsonCast || selectSql) isSimple = false;
9856
+ const value = selectSql ? selectSql.toSQL(ctx, `"${table}"`) : `"${table}"."${aliasName && column.data.name || key}"`;
9857
+ list.push(`'${key}', ${value}${outputColumn.data.jsonCast ? `::${outputColumn.data.jsonCast}` : ""}`);
9806
9858
  }
9807
9859
  return isSimple ? `row_to_json("${table}".*)` : `CASE WHEN to_jsonb("${table}") IS NULL THEN NULL ELSE json_build_object(` + list.join(", ") + ") END";
9808
9860
  };
9861
+ const getSelectedColumnData = (column) => {
9862
+ return column.data.selectSql?.result.value || column;
9863
+ };
9809
9864
  const getSqlText = (sql) => {
9810
9865
  if ("text" in sql) return sql.text;
9811
9866
  throw new Error(`Batch SQL is not supported in this query`);
@@ -12444,6 +12499,10 @@ var MergeQueryMethods = class {
12444
12499
  return query;
12445
12500
  }
12446
12501
  };
12502
+ const applyColumnSelectSql = (column) => {
12503
+ const { selectSqlFn } = column.data;
12504
+ if (selectSqlFn) column.data.selectSql = selectSqlFn(new ColumnRefExpression(column, column.data.key));
12505
+ };
12447
12506
  const DEFAULT_PRIVILEGE = {
12448
12507
  OBJECT_TYPES: [
12449
12508
  "TABLES",
@@ -12514,6 +12573,25 @@ function getSupportedDefaultPrivileges(version) {
12514
12573
  supportedPrivilegesCache.set(version, result);
12515
12574
  return result;
12516
12575
  }
12576
+ const makeRefreshMaterializedViewSql = (query, options) => {
12577
+ if (options?.concurrently && options.withData === false) throw new Error("Cannot refresh a materialized view concurrently with WITH NO DATA");
12578
+ const sql = ["REFRESH MATERIALIZED VIEW"];
12579
+ if (options?.concurrently) sql.push("CONCURRENTLY");
12580
+ sql.push(quoteTableWithSchema(query));
12581
+ if (options?.withData === true) sql.push("WITH DATA");
12582
+ else if (options?.withData === false) sql.push("WITH NO DATA");
12583
+ return {
12584
+ text: sql.join(" "),
12585
+ values: []
12586
+ };
12587
+ };
12588
+ /**
12589
+ * Refresh a materialized view.
12590
+ */
12591
+ const refreshMaterializedView = async (query, options) => {
12592
+ const sql = makeRefreshMaterializedViewSql(query, options);
12593
+ await (query.internal.asyncStorage.getStore()?.transactionAdapter || query.q.adapter).query(sql.text, sql.values);
12594
+ };
12517
12595
  var QueryJsonMethods = class {
12518
12596
  /**
12519
12597
  * Wraps the query in a way to select a single JSON string.
@@ -13772,7 +13850,7 @@ const performQuery = async (q, args, method) => {
13772
13850
  }
13773
13851
  };
13774
13852
  var Db = class extends QueryMethods {
13775
- constructor(adapterNotInTransaction, qb, table = void 0, shape, columnTypes, asyncStorage, options, tableData = {}) {
13853
+ constructor(adapterNotInTransaction, qb, table = void 0, shape, columnTypes, asyncStorage, options, tableData = {}, viewData) {
13776
13854
  super();
13777
13855
  this.adapterNotInTransaction = adapterNotInTransaction;
13778
13856
  this.qb = qb;
@@ -13814,6 +13892,10 @@ var Db = class extends QueryMethods {
13814
13892
  }
13815
13893
  if (column.data.explicitSelect) prepareSelectAll = true;
13816
13894
  else selectAllCount++;
13895
+ if (column.data.selectSqlFn) {
13896
+ applyColumnSelectSql(column);
13897
+ prepareSelectAll = true;
13898
+ }
13817
13899
  const { modifyQuery: mq } = column.data;
13818
13900
  if (mq) modifyQuery = pushOrNewArray(modifyQuery, (q) => mq(q, column));
13819
13901
  if (typeof column.data.default === "function") {
@@ -13834,7 +13916,9 @@ var Db = class extends QueryMethods {
13834
13916
  noPrimaryKey: options.noPrimaryKey === "ignore",
13835
13917
  comment: options.comment,
13836
13918
  readOnly: options.readOnly,
13919
+ materialized: options.materialized,
13837
13920
  nowSQL: options.nowSQL,
13921
+ viewData,
13838
13922
  tableData,
13839
13923
  selectAllCount
13840
13924
  };
@@ -13871,7 +13955,12 @@ var Db = class extends QueryMethods {
13871
13955
  for (const key in shape) {
13872
13956
  const column = shape[key];
13873
13957
  if (!column.data.explicitSelect) {
13874
- list.push(column.data.name ? `"${column.data.name}" "${key}"` : `"${key}"`);
13958
+ const { data } = column;
13959
+ const { selectSql } = data;
13960
+ let item;
13961
+ if (selectSql) item = (ctx, quotedAs) => `(${selectSql.toSQL(ctx, quotedAs)}) "${key}"`;
13962
+ else item = data.name ? `"${data.name}" "${key}"` : `"${key}"`;
13963
+ list.push(item);
13875
13964
  selectAllShape[key] = column;
13876
13965
  }
13877
13966
  }
@@ -14528,6 +14617,7 @@ exports.quoteTableWithSchema = quoteTableWithSchema;
14528
14617
  exports.raw = raw;
14529
14618
  exports.rawSqlToCode = rawSqlToCode;
14530
14619
  exports.referencesArgsToCode = referencesArgsToCode;
14620
+ exports.refreshMaterializedView = refreshMaterializedView;
14531
14621
  exports.returnArg = returnArg;
14532
14622
  exports.setColumnData = setColumnData;
14533
14623
  exports.setColumnEncode = setColumnEncode;