metal-orm 1.0.62 → 1.0.63

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.cts CHANGED
@@ -1274,6 +1274,16 @@ declare const toColumnRef: (col: ColumnRef | ColumnDef) => ColumnRef;
1274
1274
  */
1275
1275
  declare const toTableRef: (table: TableRef | TableDef) => TableRef;
1276
1276
 
1277
+ /**
1278
+ * Expression AST nodes and builders.
1279
+ * Re-exports components for building and visiting SQL expression trees.
1280
+ */
1281
+
1282
+ type TypedExpression<T> = (FunctionNode | CaseExpressionNode | WindowFunctionNode) & {
1283
+ __tsType: T;
1284
+ };
1285
+ declare const asType: <T>(expr: FunctionNode | CaseExpressionNode | WindowFunctionNode) => TypedExpression<T>;
1286
+
1277
1287
  /**
1278
1288
  * AST node representing a JOIN clause
1279
1289
  */
@@ -3494,7 +3504,12 @@ type RelationCallback = <TChildTable extends TableDef>(qb: SelectQueryBuilder<un
3494
3504
 
3495
3505
  type SelectDialectInput = Dialect | DialectKey;
3496
3506
 
3497
- type ColumnSelectionValue = ColumnDef | FunctionNode | CaseExpressionNode | WindowFunctionNode;
3507
+ type ColumnSelectionValue = ColumnDef | FunctionNode | CaseExpressionNode | WindowFunctionNode | TypedExpression<unknown>;
3508
+ type SelectionValueType<TValue> = TValue extends TypedExpression<infer TRuntime> ? TRuntime : TValue extends ColumnDef ? ColumnToTs<TValue> : unknown;
3509
+ type SelectionResult<TSelection extends Record<string, ColumnSelectionValue>> = {
3510
+ [K in keyof TSelection]: SelectionValueType<TSelection[K]>;
3511
+ };
3512
+ type SelectionFromKeys<TTable extends TableDef, K extends keyof TTable['columns'] & string> = Pick<InferRow<TTable>, K>;
3498
3513
  type DeepSelectEntry<TTable extends TableDef> = {
3499
3514
  type: 'root';
3500
3515
  columns: (keyof TTable['columns'] & string)[];
@@ -3509,7 +3524,7 @@ type DeepSelectConfig<TTable extends TableDef> = DeepSelectEntry<TTable>[];
3509
3524
  * @typeParam T - Result type for projections (unused)
3510
3525
  * @typeParam TTable - Table definition being queried
3511
3526
  */
3512
- declare class SelectQueryBuilder<T = EntityInstance<any>, TTable extends TableDef = TableDef> {
3527
+ declare class SelectQueryBuilder<T = EntityInstance<TableDef>, TTable extends TableDef = TableDef> {
3513
3528
  private readonly env;
3514
3529
  private readonly context;
3515
3530
  private readonly columnSelector;
@@ -3530,7 +3545,7 @@ declare class SelectQueryBuilder<T = EntityInstance<any>, TTable extends TableDe
3530
3545
  * @param hydration - Optional hydration manager
3531
3546
  * @param dependencies - Optional query builder dependencies
3532
3547
  */
3533
- constructor(table: TTable, state?: SelectQueryState, hydration?: HydrationManager, dependencies?: Partial<SelectQueryBuilderDependencies>, lazyRelations?: Set<string>, lazyRelationOptions?: Map<string, RelationIncludeOptions>, entityConstructor?: EntityConstructor<any>);
3548
+ constructor(table: TTable, state?: SelectQueryState, hydration?: HydrationManager, dependencies?: Partial<SelectQueryBuilderDependencies>, lazyRelations?: Set<string>, lazyRelationOptions?: Map<string, RelationIncludeOptions>, entityConstructor?: EntityConstructor);
3534
3549
  /**
3535
3550
  * Creates a new SelectQueryBuilder instance with updated context and lazy relations
3536
3551
  * @param context - Updated query context
@@ -3580,8 +3595,8 @@ declare class SelectQueryBuilder<T = EntityInstance<any>, TTable extends TableDe
3580
3595
  * fullName: concat(userTable.columns.firstName, ' ', userTable.columns.lastName)
3581
3596
  * });
3582
3597
  */
3583
- select<K extends keyof TTable['columns'] & string>(...args: K[]): SelectQueryBuilder<T, TTable>;
3584
- select(columns: Record<string, ColumnSelectionValue>): SelectQueryBuilder<T, TTable>;
3598
+ select<K extends keyof TTable['columns'] & string>(...args: K[]): SelectQueryBuilder<T & SelectionFromKeys<TTable, K>, TTable>;
3599
+ select<TSelection extends Record<string, ColumnSelectionValue>>(columns: TSelection): SelectQueryBuilder<T & SelectionResult<TSelection>, TTable>;
3585
3600
  /**
3586
3601
  * Selects raw column expressions
3587
3602
  * @param cols - Column expressions as strings
@@ -3670,7 +3685,7 @@ declare class SelectQueryBuilder<T = EntityInstance<any>, TTable extends TableDe
3670
3685
  * qb.select('id', 'name')
3671
3686
  * .selectSubquery('postCount', postCount);
3672
3687
  */
3673
- selectSubquery<TSub extends TableDef>(alias: string, sub: SelectQueryBuilder<unknown, TSub> | SelectQueryNode): SelectQueryBuilder<T, TTable>;
3688
+ selectSubquery<TValue = unknown, K extends string = string, TSub extends TableDef = TableDef>(alias: K, sub: SelectQueryBuilder<unknown, TSub> | SelectQueryNode): SelectQueryBuilder<T & Record<K, TValue>, TTable>;
3674
3689
  /**
3675
3690
  * Adds a JOIN against a derived table (subquery with alias)
3676
3691
  * @param subquery - Subquery to join
@@ -6095,6 +6110,14 @@ declare class DefaultManyToManyCollection<TTarget, TPivot extends object | undef
6095
6110
  * @returns Promise resolving to array of entity instances
6096
6111
  */
6097
6112
  declare function executeHydrated<TTable extends TableDef>(session: OrmSession, qb: SelectQueryBuilder<unknown, TTable>): Promise<EntityInstance<TTable>[]>;
6113
+ /**
6114
+ * Executes a hydrated query and returns plain row objects (no entity proxies).
6115
+ * @template TTable - The table type
6116
+ * @param session - The ORM session
6117
+ * @param qb - The select query builder
6118
+ * @returns Promise resolving to array of plain row objects
6119
+ */
6120
+ declare function executeHydratedPlain<TTable extends TableDef>(session: OrmSession, qb: SelectQueryBuilder<unknown, TTable>): Promise<Record<string, unknown>[]>;
6098
6121
  /**
6099
6122
  * Executes a hydrated query using execution and hydration contexts.
6100
6123
  * @template TTable - The table type
@@ -6104,6 +6127,14 @@ declare function executeHydrated<TTable extends TableDef>(session: OrmSession, q
6104
6127
  * @returns Promise resolving to array of entity instances
6105
6128
  */
6106
6129
  declare function executeHydratedWithContexts<TTable extends TableDef>(execCtx: ExecutionContext, hydCtx: HydrationContext, qb: SelectQueryBuilder<unknown, TTable>): Promise<EntityInstance<TTable>[]>;
6130
+ /**
6131
+ * Executes a hydrated query using execution context and returns plain row objects.
6132
+ * @template TTable - The table type
6133
+ * @param execCtx - The execution context
6134
+ * @param qb - The select query builder
6135
+ * @returns Promise resolving to array of plain row objects
6136
+ */
6137
+ declare function executeHydratedPlainWithContexts<TTable extends TableDef>(execCtx: ExecutionContext, qb: SelectQueryBuilder<unknown, TTable>): Promise<Record<string, unknown>[]>;
6107
6138
 
6108
6139
  type JsonifyScalar<T> = T extends Date ? string : T;
6109
6140
  /**
@@ -6253,7 +6284,8 @@ type EntityTable<TEntity extends object> = Omit<TableDef<{
6253
6284
  [K in RelationKeys<TEntity>]: NonNullable<TEntity[K]> extends HasManyCollection<infer TChild> ? HasManyRelation<EntityTable<NonNullable<TChild> & object>> : NonNullable<TEntity[K]> extends ManyToManyCollection<infer TTarget, infer TPivot> ? BelongsToManyRelation<EntityTable<NonNullable<TTarget> & object>, TPivot extends object ? EntityTable<NonNullable<TPivot> & object> : TableDef> : NonNullable<TEntity[K]> extends HasOneReference<infer TChild> ? HasOneRelation<EntityTable<NonNullable<TChild> & object>> : NonNullable<TEntity[K]> extends BelongsToReference<infer TParent> ? BelongsToRelation<EntityTable<NonNullable<TParent> & object>> : NonNullable<TEntity[K]> extends object ? BelongsToRelation<EntityTable<NonNullable<TEntity[K]> & object>> : never;
6254
6285
  };
6255
6286
  };
6256
- declare const selectFromEntity: <TEntity extends object>(ctor: EntityConstructor<TEntity>) => SelectQueryBuilder<TEntity, EntityTable<TEntity>>;
6287
+ type DecoratedEntityInstance<TEntity extends object> = TEntity & EntityInstance<EntityTable<TEntity>>;
6288
+ declare const selectFromEntity: <TEntity extends object>(ctor: EntityConstructor<TEntity>) => SelectQueryBuilder<DecoratedEntityInstance<TEntity>, EntityTable<TEntity>>;
6257
6289
  /**
6258
6290
  * Public API: opt-in ergonomic entity reference (decorator-level).
6259
6291
  *
@@ -6350,6 +6382,7 @@ declare class DefaultEntityMaterializer implements EntityMaterializer {
6350
6382
  * Simple heuristic to check if an object looks like an entity.
6351
6383
  */
6352
6384
  private isEntityLike;
6385
+ private materializeEntityProxy;
6353
6386
  }
6354
6387
  /**
6355
6388
  * Convenience function to materialize query results as real class instances.
@@ -6524,4 +6557,4 @@ type PooledExecutorFactoryOptions<TConn> = {
6524
6557
  */
6525
6558
  declare function createPooledExecutorFactory<TConn>(opts: PooledExecutorFactoryOptions<TConn>): DbExecutorFactory;
6526
6559
 
6527
- export { type AliasRefNode, type AnyDomainEvent, type ArithmeticExpressionNode, type TableRef as AstTableRef, AsyncLocalStorage, BelongsTo, BelongsToMany, type BelongsToManyOptions, type BelongsToManyRelation, type BelongsToOptions, type BelongsToReference, type BelongsToReferenceApi, type BelongsToRelation, type BetweenExpressionNode, type BinaryExpressionNode, type BitwiseExpressionNode, type CascadeMode, type CaseExpressionNode, type CastExpressionNode, type CheckConstraint, type CollateExpressionNode, Column, type ColumnDef, type ColumnDiff, type ColumnInput, type ColumnNode, type ColumnOptions, type ColumnRef, type ColumnToTs, type ColumnType, ConstructorMaterializationStrategy, type CreateTediousClientOptions, type DatabaseCheck, type DatabaseColumn, type DatabaseIndex, type DatabaseSchema, type DatabaseTable, type DbExecutor, type DbExecutorFactory, DefaultBelongsToReference, DefaultEntityMaterializer, DefaultHasManyCollection, DefaultManyToManyCollection, type DefaultValue, DeleteQueryBuilder, type DialectName, type DomainEvent, DomainEventBus, type DomainEventHandler, Entity, type EntityContext, type EntityInstance, type EntityMaterializationStrategy, type EntityMaterializer, type EntityOptions, EntityStatus, type ExecutionContext, type ExistsExpressionNode, type ExpressionNode, type ExpressionVisitor, type ForeignKeyReference, type FunctionNode, type GroupConcatOptions, type HasDomainEvents, HasMany, type HasManyCollection, type HasManyOptions, type HasManyRelation, HasOne, type HasOneOptions, type HasOneReference, type HasOneReferenceApi, type HasOneRelation, type HydrationContext, type HydrationMetadata, type HydrationPivotPlan, type HydrationPlan, type HydrationRelationPlan, type InExpressionNode, type InExpressionRight, type IndexColumn, type IndexDef, type InferRow, type InitialHandlers, InsertQueryBuilder, type IntrospectOptions, type JsonPathNode, type Jsonify, type JsonifyScalar, type LiteralNode, type LiteralValue, type LogicalExpressionNode, type ManyToManyCollection, type MssqlClientLike, MySqlDialect, type MysqlClientLike, type NullExpressionNode, type OperandNode, type OperandVisitor, Orm, type OrmDomainEvent, type OrmInterceptor, type OrmOptions, OrmSession, type OrmSessionOptions, Pool, type PoolAdapter, type PoolLease, type PoolOptions, type PooledConnectionAdapter, type PostgresClientLike, PostgresDialect, PrimaryKey, type Primitive, PrototypeMaterializationStrategy, type QueryLogEntry, type QueryLogger, type QueryResult, type RawDefaultValue, type ReferentialAction, type RelationChange, type RelationChangeEntry, type RelationDef, type RelationKey$1 as RelationKey, RelationKinds, type RelationMap, type RelationTargetTable, type RelationType, type RenderColumnOptions, STANDARD_COLUMN_TYPES, type SaveGraphInputPayload, type SaveGraphInputScalar, type SaveGraphJsonScalar, type ScalarSubqueryNode, type SchemaChange, type SchemaChangeKind, type SchemaDiffOptions, type SchemaGenerateResult, type SchemaIntrospector, type SchemaPlan, SelectQueryBuilder, type SelectQueryInput, type SelectableKeys, type SimpleQueryRunner, SqlServerDialect, type SqliteClientLike, SqliteDialect, type StandardColumnType, type SynchronizeOptions, type TableDef, type TableHooks, type TableOptions, type TableRef$1 as TableRef, type TediousColumn, type TediousConnectionLike, type TediousModule, type TediousRequest, type TediousRequestCtor, type TediousTypes, type TrackedEntity, TypeScriptGenerator, UpdateQueryBuilder, type ValueOperandInput, type WindowFunctionNode, abs, acos, add, addDomainEvent, age, aliasRef, and, arrayAppend, ascii, asin, atan, atan2, avg, belongsTo, belongsToMany, between, bitAnd, bitLength, bitOr, bitXor, bootstrapEntities, caseWhen, cast, cbrt, ceil, ceiling, char, charLength, chr, clearExpressionDispatchers, clearOperandDispatchers, coalesce, col, collate, columnOperand, concat, concatWs, correlateBy, cos, cot, count, countAll, createEntityFromRow, createEntityProxy, createExecutorFromQueryRunner, createMssqlExecutor, createMysqlExecutor, createPooledExecutorFactory, createPostgresExecutor, createQueryLoggingExecutor, createSqliteExecutor, createTediousExecutor, createTediousMssqlClient, currentDate, currentTime, dateAdd, dateDiff, dateFormat, dateSub, dateTrunc, day, dayOfWeek, defineTable, degrees, deleteFrom, denseRank, diffSchema, div, endOfMonth, entityRef, eq, esel, executeHydrated, executeHydratedWithContexts, executeSchemaSql, executeSchemaSqlFor, exists, exp, extract, firstValue, floor, fromUnixTime, generateCreateTableSql, generateSchemaSql, generateSchemaSqlFor, getColumn, getDecoratorMetadata, getSchemaIntrospector, getTableDefFromEntity, greatest, groupConcat, gt, gte, hasMany, hasOne, hour, hydrateRows, ifNull, inList, inSubquery, initcap, insertInto, instr, introspectSchema, isCaseExpressionNode, isCastExpressionNode, isCollateExpressionNode, isExpressionSelectionNode, isFunctionNode, isNotNull, isNull, isOperandNode, isValueOperandInput, isWindowFunctionNode, jsonArrayAgg, jsonContains, jsonLength, jsonPath, jsonSet, jsonify, lag, lastValue, lead, least, left, length, like, ln, loadBelongsToManyRelation, loadBelongsToRelation, loadHasManyRelation, loadHasOneRelation, localTime, localTimestamp, locate, log, log10, log2, logBase, lower, lpad, lt, lte, ltrim, materializeAs, max, md5, min, minute, mod, month, mul, neq, normalizeColumnType, notBetween, notExists, notInList, notInSubquery, notLike, now, ntile, nullif, octetLength, or, outerRef, pi, position, pow, power, quarter, radians, rand, random, rank, registerExpressionDispatcher, registerOperandDispatcher, registerSchemaIntrospector, relationLoaderCache, renderColumnDefinition, renderTypeWithArgs, repeat, replace, reverse, right, round, rowNumber, rowsToQueryResult, rpad, rtrim, second, sel, selectFrom, selectFromEntity, setRelations, sha1, sha2, shiftLeft, shiftRight, sign, sin, space, sqrt, stddev, sub, substr, sum, synchronizeSchema, tableRef, tan, toColumnRef, toTableRef, trim, trunc, truncate, unixTimestamp, update, upper, utcNow, valueToOperand, variance, visitExpression, visitOperand, weekOfYear, windowFunction, year };
6560
+ export { type AliasRefNode, type AnyDomainEvent, type ArithmeticExpressionNode, type TableRef as AstTableRef, AsyncLocalStorage, BelongsTo, BelongsToMany, type BelongsToManyOptions, type BelongsToManyRelation, type BelongsToOptions, type BelongsToReference, type BelongsToReferenceApi, type BelongsToRelation, type BetweenExpressionNode, type BinaryExpressionNode, type BitwiseExpressionNode, type CascadeMode, type CaseExpressionNode, type CastExpressionNode, type CheckConstraint, type CollateExpressionNode, Column, type ColumnDef, type ColumnDiff, type ColumnInput, type ColumnNode, type ColumnOptions, type ColumnRef, type ColumnToTs, type ColumnType, ConstructorMaterializationStrategy, type CreateTediousClientOptions, type DatabaseCheck, type DatabaseColumn, type DatabaseIndex, type DatabaseSchema, type DatabaseTable, type DbExecutor, type DbExecutorFactory, type DecoratedEntityInstance, DefaultBelongsToReference, DefaultEntityMaterializer, DefaultHasManyCollection, DefaultManyToManyCollection, type DefaultValue, DeleteQueryBuilder, type DialectName, type DomainEvent, DomainEventBus, type DomainEventHandler, Entity, type EntityContext, type EntityInstance, type EntityMaterializationStrategy, type EntityMaterializer, type EntityOptions, EntityStatus, type ExecutionContext, type ExistsExpressionNode, type ExpressionNode, type ExpressionVisitor, type ForeignKeyReference, type FunctionNode, type GroupConcatOptions, type HasDomainEvents, HasMany, type HasManyCollection, type HasManyOptions, type HasManyRelation, HasOne, type HasOneOptions, type HasOneReference, type HasOneReferenceApi, type HasOneRelation, type HydrationContext, type HydrationMetadata, type HydrationPivotPlan, type HydrationPlan, type HydrationRelationPlan, type InExpressionNode, type InExpressionRight, type IndexColumn, type IndexDef, type InferRow, type InitialHandlers, InsertQueryBuilder, type IntrospectOptions, type JsonPathNode, type Jsonify, type JsonifyScalar, type LiteralNode, type LiteralValue, type LogicalExpressionNode, type ManyToManyCollection, type MssqlClientLike, MySqlDialect, type MysqlClientLike, type NullExpressionNode, type OperandNode, type OperandVisitor, Orm, type OrmDomainEvent, type OrmInterceptor, type OrmOptions, OrmSession, type OrmSessionOptions, Pool, type PoolAdapter, type PoolLease, type PoolOptions, type PooledConnectionAdapter, type PostgresClientLike, PostgresDialect, PrimaryKey, type Primitive, PrototypeMaterializationStrategy, type QueryLogEntry, type QueryLogger, type QueryResult, type RawDefaultValue, type ReferentialAction, type RelationChange, type RelationChangeEntry, type RelationDef, type RelationKey$1 as RelationKey, RelationKinds, type RelationMap, type RelationTargetTable, type RelationType, type RenderColumnOptions, STANDARD_COLUMN_TYPES, type SaveGraphInputPayload, type SaveGraphInputScalar, type SaveGraphJsonScalar, type ScalarSubqueryNode, type SchemaChange, type SchemaChangeKind, type SchemaDiffOptions, type SchemaGenerateResult, type SchemaIntrospector, type SchemaPlan, SelectQueryBuilder, type SelectQueryInput, type SelectableKeys, type SimpleQueryRunner, SqlServerDialect, type SqliteClientLike, SqliteDialect, type StandardColumnType, type SynchronizeOptions, type TableDef, type TableHooks, type TableOptions, type TableRef$1 as TableRef, type TediousColumn, type TediousConnectionLike, type TediousModule, type TediousRequest, type TediousRequestCtor, type TediousTypes, type TrackedEntity, TypeScriptGenerator, type TypedExpression, UpdateQueryBuilder, type ValueOperandInput, type WindowFunctionNode, abs, acos, add, addDomainEvent, age, aliasRef, and, arrayAppend, asType, ascii, asin, atan, atan2, avg, belongsTo, belongsToMany, between, bitAnd, bitLength, bitOr, bitXor, bootstrapEntities, caseWhen, cast, cbrt, ceil, ceiling, char, charLength, chr, clearExpressionDispatchers, clearOperandDispatchers, coalesce, col, collate, columnOperand, concat, concatWs, correlateBy, cos, cot, count, countAll, createEntityFromRow, createEntityProxy, createExecutorFromQueryRunner, createMssqlExecutor, createMysqlExecutor, createPooledExecutorFactory, createPostgresExecutor, createQueryLoggingExecutor, createSqliteExecutor, createTediousExecutor, createTediousMssqlClient, currentDate, currentTime, dateAdd, dateDiff, dateFormat, dateSub, dateTrunc, day, dayOfWeek, defineTable, degrees, deleteFrom, denseRank, diffSchema, div, endOfMonth, entityRef, eq, esel, executeHydrated, executeHydratedPlain, executeHydratedPlainWithContexts, executeHydratedWithContexts, executeSchemaSql, executeSchemaSqlFor, exists, exp, extract, firstValue, floor, fromUnixTime, generateCreateTableSql, generateSchemaSql, generateSchemaSqlFor, getColumn, getDecoratorMetadata, getSchemaIntrospector, getTableDefFromEntity, greatest, groupConcat, gt, gte, hasMany, hasOne, hour, hydrateRows, ifNull, inList, inSubquery, initcap, insertInto, instr, introspectSchema, isCaseExpressionNode, isCastExpressionNode, isCollateExpressionNode, isExpressionSelectionNode, isFunctionNode, isNotNull, isNull, isOperandNode, isValueOperandInput, isWindowFunctionNode, jsonArrayAgg, jsonContains, jsonLength, jsonPath, jsonSet, jsonify, lag, lastValue, lead, least, left, length, like, ln, loadBelongsToManyRelation, loadBelongsToRelation, loadHasManyRelation, loadHasOneRelation, localTime, localTimestamp, locate, log, log10, log2, logBase, lower, lpad, lt, lte, ltrim, materializeAs, max, md5, min, minute, mod, month, mul, neq, normalizeColumnType, notBetween, notExists, notInList, notInSubquery, notLike, now, ntile, nullif, octetLength, or, outerRef, pi, position, pow, power, quarter, radians, rand, random, rank, registerExpressionDispatcher, registerOperandDispatcher, registerSchemaIntrospector, relationLoaderCache, renderColumnDefinition, renderTypeWithArgs, repeat, replace, reverse, right, round, rowNumber, rowsToQueryResult, rpad, rtrim, second, sel, selectFrom, selectFromEntity, setRelations, sha1, sha2, shiftLeft, shiftRight, sign, sin, space, sqrt, stddev, sub, substr, sum, synchronizeSchema, tableRef, tan, toColumnRef, toTableRef, trim, trunc, truncate, unixTimestamp, update, upper, utcNow, valueToOperand, variance, visitExpression, visitOperand, weekOfYear, windowFunction, year };
package/dist/index.d.ts CHANGED
@@ -1274,6 +1274,16 @@ declare const toColumnRef: (col: ColumnRef | ColumnDef) => ColumnRef;
1274
1274
  */
1275
1275
  declare const toTableRef: (table: TableRef | TableDef) => TableRef;
1276
1276
 
1277
+ /**
1278
+ * Expression AST nodes and builders.
1279
+ * Re-exports components for building and visiting SQL expression trees.
1280
+ */
1281
+
1282
+ type TypedExpression<T> = (FunctionNode | CaseExpressionNode | WindowFunctionNode) & {
1283
+ __tsType: T;
1284
+ };
1285
+ declare const asType: <T>(expr: FunctionNode | CaseExpressionNode | WindowFunctionNode) => TypedExpression<T>;
1286
+
1277
1287
  /**
1278
1288
  * AST node representing a JOIN clause
1279
1289
  */
@@ -3494,7 +3504,12 @@ type RelationCallback = <TChildTable extends TableDef>(qb: SelectQueryBuilder<un
3494
3504
 
3495
3505
  type SelectDialectInput = Dialect | DialectKey;
3496
3506
 
3497
- type ColumnSelectionValue = ColumnDef | FunctionNode | CaseExpressionNode | WindowFunctionNode;
3507
+ type ColumnSelectionValue = ColumnDef | FunctionNode | CaseExpressionNode | WindowFunctionNode | TypedExpression<unknown>;
3508
+ type SelectionValueType<TValue> = TValue extends TypedExpression<infer TRuntime> ? TRuntime : TValue extends ColumnDef ? ColumnToTs<TValue> : unknown;
3509
+ type SelectionResult<TSelection extends Record<string, ColumnSelectionValue>> = {
3510
+ [K in keyof TSelection]: SelectionValueType<TSelection[K]>;
3511
+ };
3512
+ type SelectionFromKeys<TTable extends TableDef, K extends keyof TTable['columns'] & string> = Pick<InferRow<TTable>, K>;
3498
3513
  type DeepSelectEntry<TTable extends TableDef> = {
3499
3514
  type: 'root';
3500
3515
  columns: (keyof TTable['columns'] & string)[];
@@ -3509,7 +3524,7 @@ type DeepSelectConfig<TTable extends TableDef> = DeepSelectEntry<TTable>[];
3509
3524
  * @typeParam T - Result type for projections (unused)
3510
3525
  * @typeParam TTable - Table definition being queried
3511
3526
  */
3512
- declare class SelectQueryBuilder<T = EntityInstance<any>, TTable extends TableDef = TableDef> {
3527
+ declare class SelectQueryBuilder<T = EntityInstance<TableDef>, TTable extends TableDef = TableDef> {
3513
3528
  private readonly env;
3514
3529
  private readonly context;
3515
3530
  private readonly columnSelector;
@@ -3530,7 +3545,7 @@ declare class SelectQueryBuilder<T = EntityInstance<any>, TTable extends TableDe
3530
3545
  * @param hydration - Optional hydration manager
3531
3546
  * @param dependencies - Optional query builder dependencies
3532
3547
  */
3533
- constructor(table: TTable, state?: SelectQueryState, hydration?: HydrationManager, dependencies?: Partial<SelectQueryBuilderDependencies>, lazyRelations?: Set<string>, lazyRelationOptions?: Map<string, RelationIncludeOptions>, entityConstructor?: EntityConstructor<any>);
3548
+ constructor(table: TTable, state?: SelectQueryState, hydration?: HydrationManager, dependencies?: Partial<SelectQueryBuilderDependencies>, lazyRelations?: Set<string>, lazyRelationOptions?: Map<string, RelationIncludeOptions>, entityConstructor?: EntityConstructor);
3534
3549
  /**
3535
3550
  * Creates a new SelectQueryBuilder instance with updated context and lazy relations
3536
3551
  * @param context - Updated query context
@@ -3580,8 +3595,8 @@ declare class SelectQueryBuilder<T = EntityInstance<any>, TTable extends TableDe
3580
3595
  * fullName: concat(userTable.columns.firstName, ' ', userTable.columns.lastName)
3581
3596
  * });
3582
3597
  */
3583
- select<K extends keyof TTable['columns'] & string>(...args: K[]): SelectQueryBuilder<T, TTable>;
3584
- select(columns: Record<string, ColumnSelectionValue>): SelectQueryBuilder<T, TTable>;
3598
+ select<K extends keyof TTable['columns'] & string>(...args: K[]): SelectQueryBuilder<T & SelectionFromKeys<TTable, K>, TTable>;
3599
+ select<TSelection extends Record<string, ColumnSelectionValue>>(columns: TSelection): SelectQueryBuilder<T & SelectionResult<TSelection>, TTable>;
3585
3600
  /**
3586
3601
  * Selects raw column expressions
3587
3602
  * @param cols - Column expressions as strings
@@ -3670,7 +3685,7 @@ declare class SelectQueryBuilder<T = EntityInstance<any>, TTable extends TableDe
3670
3685
  * qb.select('id', 'name')
3671
3686
  * .selectSubquery('postCount', postCount);
3672
3687
  */
3673
- selectSubquery<TSub extends TableDef>(alias: string, sub: SelectQueryBuilder<unknown, TSub> | SelectQueryNode): SelectQueryBuilder<T, TTable>;
3688
+ selectSubquery<TValue = unknown, K extends string = string, TSub extends TableDef = TableDef>(alias: K, sub: SelectQueryBuilder<unknown, TSub> | SelectQueryNode): SelectQueryBuilder<T & Record<K, TValue>, TTable>;
3674
3689
  /**
3675
3690
  * Adds a JOIN against a derived table (subquery with alias)
3676
3691
  * @param subquery - Subquery to join
@@ -6095,6 +6110,14 @@ declare class DefaultManyToManyCollection<TTarget, TPivot extends object | undef
6095
6110
  * @returns Promise resolving to array of entity instances
6096
6111
  */
6097
6112
  declare function executeHydrated<TTable extends TableDef>(session: OrmSession, qb: SelectQueryBuilder<unknown, TTable>): Promise<EntityInstance<TTable>[]>;
6113
+ /**
6114
+ * Executes a hydrated query and returns plain row objects (no entity proxies).
6115
+ * @template TTable - The table type
6116
+ * @param session - The ORM session
6117
+ * @param qb - The select query builder
6118
+ * @returns Promise resolving to array of plain row objects
6119
+ */
6120
+ declare function executeHydratedPlain<TTable extends TableDef>(session: OrmSession, qb: SelectQueryBuilder<unknown, TTable>): Promise<Record<string, unknown>[]>;
6098
6121
  /**
6099
6122
  * Executes a hydrated query using execution and hydration contexts.
6100
6123
  * @template TTable - The table type
@@ -6104,6 +6127,14 @@ declare function executeHydrated<TTable extends TableDef>(session: OrmSession, q
6104
6127
  * @returns Promise resolving to array of entity instances
6105
6128
  */
6106
6129
  declare function executeHydratedWithContexts<TTable extends TableDef>(execCtx: ExecutionContext, hydCtx: HydrationContext, qb: SelectQueryBuilder<unknown, TTable>): Promise<EntityInstance<TTable>[]>;
6130
+ /**
6131
+ * Executes a hydrated query using execution context and returns plain row objects.
6132
+ * @template TTable - The table type
6133
+ * @param execCtx - The execution context
6134
+ * @param qb - The select query builder
6135
+ * @returns Promise resolving to array of plain row objects
6136
+ */
6137
+ declare function executeHydratedPlainWithContexts<TTable extends TableDef>(execCtx: ExecutionContext, qb: SelectQueryBuilder<unknown, TTable>): Promise<Record<string, unknown>[]>;
6107
6138
 
6108
6139
  type JsonifyScalar<T> = T extends Date ? string : T;
6109
6140
  /**
@@ -6253,7 +6284,8 @@ type EntityTable<TEntity extends object> = Omit<TableDef<{
6253
6284
  [K in RelationKeys<TEntity>]: NonNullable<TEntity[K]> extends HasManyCollection<infer TChild> ? HasManyRelation<EntityTable<NonNullable<TChild> & object>> : NonNullable<TEntity[K]> extends ManyToManyCollection<infer TTarget, infer TPivot> ? BelongsToManyRelation<EntityTable<NonNullable<TTarget> & object>, TPivot extends object ? EntityTable<NonNullable<TPivot> & object> : TableDef> : NonNullable<TEntity[K]> extends HasOneReference<infer TChild> ? HasOneRelation<EntityTable<NonNullable<TChild> & object>> : NonNullable<TEntity[K]> extends BelongsToReference<infer TParent> ? BelongsToRelation<EntityTable<NonNullable<TParent> & object>> : NonNullable<TEntity[K]> extends object ? BelongsToRelation<EntityTable<NonNullable<TEntity[K]> & object>> : never;
6254
6285
  };
6255
6286
  };
6256
- declare const selectFromEntity: <TEntity extends object>(ctor: EntityConstructor<TEntity>) => SelectQueryBuilder<TEntity, EntityTable<TEntity>>;
6287
+ type DecoratedEntityInstance<TEntity extends object> = TEntity & EntityInstance<EntityTable<TEntity>>;
6288
+ declare const selectFromEntity: <TEntity extends object>(ctor: EntityConstructor<TEntity>) => SelectQueryBuilder<DecoratedEntityInstance<TEntity>, EntityTable<TEntity>>;
6257
6289
  /**
6258
6290
  * Public API: opt-in ergonomic entity reference (decorator-level).
6259
6291
  *
@@ -6350,6 +6382,7 @@ declare class DefaultEntityMaterializer implements EntityMaterializer {
6350
6382
  * Simple heuristic to check if an object looks like an entity.
6351
6383
  */
6352
6384
  private isEntityLike;
6385
+ private materializeEntityProxy;
6353
6386
  }
6354
6387
  /**
6355
6388
  * Convenience function to materialize query results as real class instances.
@@ -6524,4 +6557,4 @@ type PooledExecutorFactoryOptions<TConn> = {
6524
6557
  */
6525
6558
  declare function createPooledExecutorFactory<TConn>(opts: PooledExecutorFactoryOptions<TConn>): DbExecutorFactory;
6526
6559
 
6527
- export { type AliasRefNode, type AnyDomainEvent, type ArithmeticExpressionNode, type TableRef as AstTableRef, AsyncLocalStorage, BelongsTo, BelongsToMany, type BelongsToManyOptions, type BelongsToManyRelation, type BelongsToOptions, type BelongsToReference, type BelongsToReferenceApi, type BelongsToRelation, type BetweenExpressionNode, type BinaryExpressionNode, type BitwiseExpressionNode, type CascadeMode, type CaseExpressionNode, type CastExpressionNode, type CheckConstraint, type CollateExpressionNode, Column, type ColumnDef, type ColumnDiff, type ColumnInput, type ColumnNode, type ColumnOptions, type ColumnRef, type ColumnToTs, type ColumnType, ConstructorMaterializationStrategy, type CreateTediousClientOptions, type DatabaseCheck, type DatabaseColumn, type DatabaseIndex, type DatabaseSchema, type DatabaseTable, type DbExecutor, type DbExecutorFactory, DefaultBelongsToReference, DefaultEntityMaterializer, DefaultHasManyCollection, DefaultManyToManyCollection, type DefaultValue, DeleteQueryBuilder, type DialectName, type DomainEvent, DomainEventBus, type DomainEventHandler, Entity, type EntityContext, type EntityInstance, type EntityMaterializationStrategy, type EntityMaterializer, type EntityOptions, EntityStatus, type ExecutionContext, type ExistsExpressionNode, type ExpressionNode, type ExpressionVisitor, type ForeignKeyReference, type FunctionNode, type GroupConcatOptions, type HasDomainEvents, HasMany, type HasManyCollection, type HasManyOptions, type HasManyRelation, HasOne, type HasOneOptions, type HasOneReference, type HasOneReferenceApi, type HasOneRelation, type HydrationContext, type HydrationMetadata, type HydrationPivotPlan, type HydrationPlan, type HydrationRelationPlan, type InExpressionNode, type InExpressionRight, type IndexColumn, type IndexDef, type InferRow, type InitialHandlers, InsertQueryBuilder, type IntrospectOptions, type JsonPathNode, type Jsonify, type JsonifyScalar, type LiteralNode, type LiteralValue, type LogicalExpressionNode, type ManyToManyCollection, type MssqlClientLike, MySqlDialect, type MysqlClientLike, type NullExpressionNode, type OperandNode, type OperandVisitor, Orm, type OrmDomainEvent, type OrmInterceptor, type OrmOptions, OrmSession, type OrmSessionOptions, Pool, type PoolAdapter, type PoolLease, type PoolOptions, type PooledConnectionAdapter, type PostgresClientLike, PostgresDialect, PrimaryKey, type Primitive, PrototypeMaterializationStrategy, type QueryLogEntry, type QueryLogger, type QueryResult, type RawDefaultValue, type ReferentialAction, type RelationChange, type RelationChangeEntry, type RelationDef, type RelationKey$1 as RelationKey, RelationKinds, type RelationMap, type RelationTargetTable, type RelationType, type RenderColumnOptions, STANDARD_COLUMN_TYPES, type SaveGraphInputPayload, type SaveGraphInputScalar, type SaveGraphJsonScalar, type ScalarSubqueryNode, type SchemaChange, type SchemaChangeKind, type SchemaDiffOptions, type SchemaGenerateResult, type SchemaIntrospector, type SchemaPlan, SelectQueryBuilder, type SelectQueryInput, type SelectableKeys, type SimpleQueryRunner, SqlServerDialect, type SqliteClientLike, SqliteDialect, type StandardColumnType, type SynchronizeOptions, type TableDef, type TableHooks, type TableOptions, type TableRef$1 as TableRef, type TediousColumn, type TediousConnectionLike, type TediousModule, type TediousRequest, type TediousRequestCtor, type TediousTypes, type TrackedEntity, TypeScriptGenerator, UpdateQueryBuilder, type ValueOperandInput, type WindowFunctionNode, abs, acos, add, addDomainEvent, age, aliasRef, and, arrayAppend, ascii, asin, atan, atan2, avg, belongsTo, belongsToMany, between, bitAnd, bitLength, bitOr, bitXor, bootstrapEntities, caseWhen, cast, cbrt, ceil, ceiling, char, charLength, chr, clearExpressionDispatchers, clearOperandDispatchers, coalesce, col, collate, columnOperand, concat, concatWs, correlateBy, cos, cot, count, countAll, createEntityFromRow, createEntityProxy, createExecutorFromQueryRunner, createMssqlExecutor, createMysqlExecutor, createPooledExecutorFactory, createPostgresExecutor, createQueryLoggingExecutor, createSqliteExecutor, createTediousExecutor, createTediousMssqlClient, currentDate, currentTime, dateAdd, dateDiff, dateFormat, dateSub, dateTrunc, day, dayOfWeek, defineTable, degrees, deleteFrom, denseRank, diffSchema, div, endOfMonth, entityRef, eq, esel, executeHydrated, executeHydratedWithContexts, executeSchemaSql, executeSchemaSqlFor, exists, exp, extract, firstValue, floor, fromUnixTime, generateCreateTableSql, generateSchemaSql, generateSchemaSqlFor, getColumn, getDecoratorMetadata, getSchemaIntrospector, getTableDefFromEntity, greatest, groupConcat, gt, gte, hasMany, hasOne, hour, hydrateRows, ifNull, inList, inSubquery, initcap, insertInto, instr, introspectSchema, isCaseExpressionNode, isCastExpressionNode, isCollateExpressionNode, isExpressionSelectionNode, isFunctionNode, isNotNull, isNull, isOperandNode, isValueOperandInput, isWindowFunctionNode, jsonArrayAgg, jsonContains, jsonLength, jsonPath, jsonSet, jsonify, lag, lastValue, lead, least, left, length, like, ln, loadBelongsToManyRelation, loadBelongsToRelation, loadHasManyRelation, loadHasOneRelation, localTime, localTimestamp, locate, log, log10, log2, logBase, lower, lpad, lt, lte, ltrim, materializeAs, max, md5, min, minute, mod, month, mul, neq, normalizeColumnType, notBetween, notExists, notInList, notInSubquery, notLike, now, ntile, nullif, octetLength, or, outerRef, pi, position, pow, power, quarter, radians, rand, random, rank, registerExpressionDispatcher, registerOperandDispatcher, registerSchemaIntrospector, relationLoaderCache, renderColumnDefinition, renderTypeWithArgs, repeat, replace, reverse, right, round, rowNumber, rowsToQueryResult, rpad, rtrim, second, sel, selectFrom, selectFromEntity, setRelations, sha1, sha2, shiftLeft, shiftRight, sign, sin, space, sqrt, stddev, sub, substr, sum, synchronizeSchema, tableRef, tan, toColumnRef, toTableRef, trim, trunc, truncate, unixTimestamp, update, upper, utcNow, valueToOperand, variance, visitExpression, visitOperand, weekOfYear, windowFunction, year };
6560
+ export { type AliasRefNode, type AnyDomainEvent, type ArithmeticExpressionNode, type TableRef as AstTableRef, AsyncLocalStorage, BelongsTo, BelongsToMany, type BelongsToManyOptions, type BelongsToManyRelation, type BelongsToOptions, type BelongsToReference, type BelongsToReferenceApi, type BelongsToRelation, type BetweenExpressionNode, type BinaryExpressionNode, type BitwiseExpressionNode, type CascadeMode, type CaseExpressionNode, type CastExpressionNode, type CheckConstraint, type CollateExpressionNode, Column, type ColumnDef, type ColumnDiff, type ColumnInput, type ColumnNode, type ColumnOptions, type ColumnRef, type ColumnToTs, type ColumnType, ConstructorMaterializationStrategy, type CreateTediousClientOptions, type DatabaseCheck, type DatabaseColumn, type DatabaseIndex, type DatabaseSchema, type DatabaseTable, type DbExecutor, type DbExecutorFactory, type DecoratedEntityInstance, DefaultBelongsToReference, DefaultEntityMaterializer, DefaultHasManyCollection, DefaultManyToManyCollection, type DefaultValue, DeleteQueryBuilder, type DialectName, type DomainEvent, DomainEventBus, type DomainEventHandler, Entity, type EntityContext, type EntityInstance, type EntityMaterializationStrategy, type EntityMaterializer, type EntityOptions, EntityStatus, type ExecutionContext, type ExistsExpressionNode, type ExpressionNode, type ExpressionVisitor, type ForeignKeyReference, type FunctionNode, type GroupConcatOptions, type HasDomainEvents, HasMany, type HasManyCollection, type HasManyOptions, type HasManyRelation, HasOne, type HasOneOptions, type HasOneReference, type HasOneReferenceApi, type HasOneRelation, type HydrationContext, type HydrationMetadata, type HydrationPivotPlan, type HydrationPlan, type HydrationRelationPlan, type InExpressionNode, type InExpressionRight, type IndexColumn, type IndexDef, type InferRow, type InitialHandlers, InsertQueryBuilder, type IntrospectOptions, type JsonPathNode, type Jsonify, type JsonifyScalar, type LiteralNode, type LiteralValue, type LogicalExpressionNode, type ManyToManyCollection, type MssqlClientLike, MySqlDialect, type MysqlClientLike, type NullExpressionNode, type OperandNode, type OperandVisitor, Orm, type OrmDomainEvent, type OrmInterceptor, type OrmOptions, OrmSession, type OrmSessionOptions, Pool, type PoolAdapter, type PoolLease, type PoolOptions, type PooledConnectionAdapter, type PostgresClientLike, PostgresDialect, PrimaryKey, type Primitive, PrototypeMaterializationStrategy, type QueryLogEntry, type QueryLogger, type QueryResult, type RawDefaultValue, type ReferentialAction, type RelationChange, type RelationChangeEntry, type RelationDef, type RelationKey$1 as RelationKey, RelationKinds, type RelationMap, type RelationTargetTable, type RelationType, type RenderColumnOptions, STANDARD_COLUMN_TYPES, type SaveGraphInputPayload, type SaveGraphInputScalar, type SaveGraphJsonScalar, type ScalarSubqueryNode, type SchemaChange, type SchemaChangeKind, type SchemaDiffOptions, type SchemaGenerateResult, type SchemaIntrospector, type SchemaPlan, SelectQueryBuilder, type SelectQueryInput, type SelectableKeys, type SimpleQueryRunner, SqlServerDialect, type SqliteClientLike, SqliteDialect, type StandardColumnType, type SynchronizeOptions, type TableDef, type TableHooks, type TableOptions, type TableRef$1 as TableRef, type TediousColumn, type TediousConnectionLike, type TediousModule, type TediousRequest, type TediousRequestCtor, type TediousTypes, type TrackedEntity, TypeScriptGenerator, type TypedExpression, UpdateQueryBuilder, type ValueOperandInput, type WindowFunctionNode, abs, acos, add, addDomainEvent, age, aliasRef, and, arrayAppend, asType, ascii, asin, atan, atan2, avg, belongsTo, belongsToMany, between, bitAnd, bitLength, bitOr, bitXor, bootstrapEntities, caseWhen, cast, cbrt, ceil, ceiling, char, charLength, chr, clearExpressionDispatchers, clearOperandDispatchers, coalesce, col, collate, columnOperand, concat, concatWs, correlateBy, cos, cot, count, countAll, createEntityFromRow, createEntityProxy, createExecutorFromQueryRunner, createMssqlExecutor, createMysqlExecutor, createPooledExecutorFactory, createPostgresExecutor, createQueryLoggingExecutor, createSqliteExecutor, createTediousExecutor, createTediousMssqlClient, currentDate, currentTime, dateAdd, dateDiff, dateFormat, dateSub, dateTrunc, day, dayOfWeek, defineTable, degrees, deleteFrom, denseRank, diffSchema, div, endOfMonth, entityRef, eq, esel, executeHydrated, executeHydratedPlain, executeHydratedPlainWithContexts, executeHydratedWithContexts, executeSchemaSql, executeSchemaSqlFor, exists, exp, extract, firstValue, floor, fromUnixTime, generateCreateTableSql, generateSchemaSql, generateSchemaSqlFor, getColumn, getDecoratorMetadata, getSchemaIntrospector, getTableDefFromEntity, greatest, groupConcat, gt, gte, hasMany, hasOne, hour, hydrateRows, ifNull, inList, inSubquery, initcap, insertInto, instr, introspectSchema, isCaseExpressionNode, isCastExpressionNode, isCollateExpressionNode, isExpressionSelectionNode, isFunctionNode, isNotNull, isNull, isOperandNode, isValueOperandInput, isWindowFunctionNode, jsonArrayAgg, jsonContains, jsonLength, jsonPath, jsonSet, jsonify, lag, lastValue, lead, least, left, length, like, ln, loadBelongsToManyRelation, loadBelongsToRelation, loadHasManyRelation, loadHasOneRelation, localTime, localTimestamp, locate, log, log10, log2, logBase, lower, lpad, lt, lte, ltrim, materializeAs, max, md5, min, minute, mod, month, mul, neq, normalizeColumnType, notBetween, notExists, notInList, notInSubquery, notLike, now, ntile, nullif, octetLength, or, outerRef, pi, position, pow, power, quarter, radians, rand, random, rank, registerExpressionDispatcher, registerOperandDispatcher, registerSchemaIntrospector, relationLoaderCache, renderColumnDefinition, renderTypeWithArgs, repeat, replace, reverse, right, round, rowNumber, rowsToQueryResult, rpad, rtrim, second, sel, selectFrom, selectFromEntity, setRelations, sha1, sha2, shiftLeft, shiftRight, sign, sin, space, sqrt, stddev, sub, substr, sum, synchronizeSchema, tableRef, tan, toColumnRef, toTableRef, trim, trunc, truncate, unixTimestamp, update, upper, utcNow, valueToOperand, variance, visitExpression, visitOperand, weekOfYear, windowFunction, year };
package/dist/index.js CHANGED
@@ -831,6 +831,9 @@ var toTableRef = (table) => ({
831
831
  alias: hasAlias(table) ? table.alias : void 0
832
832
  });
833
833
 
834
+ // src/core/ast/expression.ts
835
+ var asType = (expr) => expr;
836
+
834
837
  // src/core/functions/function-registry.ts
835
838
  var FunctionRegistry = class {
836
839
  renderers = /* @__PURE__ */ new Map();
@@ -3444,10 +3447,9 @@ var HydrationPlanner = class _HydrationPlanner {
3444
3447
  const rootCols = new Set(currentPlan.rootColumns);
3445
3448
  let changed = false;
3446
3449
  columns.forEach((node) => {
3447
- if (node.type !== "Column") return;
3448
- if (node.table !== this.table.name) return;
3449
- const alias = node.alias || node.name;
3450
- if (isRelationAlias(alias)) return;
3450
+ const alias = node.type === "Column" ? node.alias || node.name : node.alias;
3451
+ if (!alias || isRelationAlias(alias)) return;
3452
+ if (node.type === "Column" && node.table !== this.table.name) return;
3451
3453
  if (!rootCols.has(alias)) {
3452
3454
  rootCols.add(alias);
3453
3455
  changed = true;
@@ -5913,9 +5915,22 @@ var executeWithContexts = async (execCtx, entityCtx, qb) => {
5913
5915
  await loadLazyRelationsForTable(entityCtx, qb.getTable(), lazyRelations, lazyRelationOptions);
5914
5916
  return entities;
5915
5917
  };
5918
+ var executePlainWithContexts = async (execCtx, qb) => {
5919
+ const ast = qb.getAST();
5920
+ const compiled = execCtx.dialect.compileSelect(ast);
5921
+ const executed = await execCtx.interceptors.run({ sql: compiled.sql, params: compiled.params }, execCtx.executor);
5922
+ const rows = flattenResults(executed);
5923
+ if (ast.setOps && ast.setOps.length > 0) {
5924
+ return rows;
5925
+ }
5926
+ return hydrateRows(rows, qb.getHydrationPlan());
5927
+ };
5916
5928
  async function executeHydrated(session, qb) {
5917
5929
  return executeWithContexts(session.getExecutionContext(), session, qb);
5918
5930
  }
5931
+ async function executeHydratedPlain(session, qb) {
5932
+ return executePlainWithContexts(session.getExecutionContext(), qb);
5933
+ }
5919
5934
  async function executeHydratedWithContexts(execCtx, hydCtx, qb) {
5920
5935
  const entityCtx = hydCtx.entityContext;
5921
5936
  if (!entityCtx) {
@@ -5923,6 +5938,9 @@ async function executeHydratedWithContexts(execCtx, hydCtx, qb) {
5923
5938
  }
5924
5939
  return executeWithContexts(execCtx, entityCtx, qb);
5925
5940
  }
5941
+ async function executeHydratedPlainWithContexts(execCtx, qb) {
5942
+ return executePlainWithContexts(execCtx, qb);
5943
+ }
5926
5944
  var loadLazyRelationsForTable = async (ctx, table, lazyRelations, lazyRelationOptions) => {
5927
5945
  if (!lazyRelations.length) return;
5928
5946
  const tracked = ctx.getEntitiesForTable(table);
@@ -6056,8 +6074,11 @@ var DefaultEntityMaterializer = class {
6056
6074
  this.strategy = strategy;
6057
6075
  }
6058
6076
  materialize(ctor, row) {
6077
+ if (hasEntityMeta(row)) {
6078
+ return this.materializeEntityProxy(ctor, row);
6079
+ }
6059
6080
  const instance = this.strategy.materialize(ctor, row);
6060
- this.materializeRelations(instance, ctor);
6081
+ this.materializeRelations(instance);
6061
6082
  return instance;
6062
6083
  }
6063
6084
  materializeMany(ctor, rows) {
@@ -6066,9 +6087,9 @@ var DefaultEntityMaterializer = class {
6066
6087
  /**
6067
6088
  * Recursively materializes nested relation data.
6068
6089
  */
6069
- materializeRelations(instance, _ctor) {
6090
+ materializeRelations(instance) {
6070
6091
  rebuildRegistry();
6071
- for (const [key, value] of Object.entries(instance)) {
6092
+ for (const value of Object.values(instance)) {
6072
6093
  if (value === null || value === void 0) continue;
6073
6094
  if (typeof value === "object" && !Array.isArray(value)) {
6074
6095
  const nested = value;
@@ -6090,6 +6111,17 @@ var DefaultEntityMaterializer = class {
6090
6111
  (k) => k.endsWith("Id") || k === "createdAt" || k === "updatedAt"
6091
6112
  );
6092
6113
  }
6114
+ materializeEntityProxy(ctor, row) {
6115
+ const proxy = row;
6116
+ const baseline = this.strategy.materialize(ctor, {});
6117
+ for (const key of Object.keys(baseline)) {
6118
+ if (!Object.prototype.hasOwnProperty.call(proxy, key)) {
6119
+ proxy[key] = baseline[key];
6120
+ }
6121
+ }
6122
+ Object.setPrototypeOf(proxy, ctor.prototype);
6123
+ return proxy;
6124
+ }
6093
6125
  };
6094
6126
  var materializeAs = (ctor, results) => {
6095
6127
  const materializer = new DefaultEntityMaterializer();
@@ -6599,7 +6631,9 @@ var SelectQueryBuilder = class _SelectQueryBuilder {
6599
6631
  select(...args) {
6600
6632
  if (args.length === 1 && typeof args[0] === "object" && args[0] !== null && typeof args[0] !== "string") {
6601
6633
  const columns = args[0];
6602
- return this.clone(this.projectionFacet.select(this.context, columns));
6634
+ return this.clone(
6635
+ this.projectionFacet.select(this.context, columns)
6636
+ );
6603
6637
  }
6604
6638
  const cols = args;
6605
6639
  const selection = {};
@@ -6610,7 +6644,9 @@ var SelectQueryBuilder = class _SelectQueryBuilder {
6610
6644
  }
6611
6645
  selection[key] = col2;
6612
6646
  }
6613
- return this.clone(this.projectionFacet.select(this.context, selection));
6647
+ return this.clone(
6648
+ this.projectionFacet.select(this.context, selection)
6649
+ );
6614
6650
  }
6615
6651
  /**
6616
6652
  * Selects raw column expressions
@@ -6714,7 +6750,9 @@ var SelectQueryBuilder = class _SelectQueryBuilder {
6714
6750
  */
6715
6751
  selectSubquery(alias, sub2) {
6716
6752
  const query = resolveSelectQuery(sub2);
6717
- return this.clone(this.projectionFacet.selectSubquery(this.context, alias, query));
6753
+ return this.clone(
6754
+ this.projectionFacet.selectSubquery(this.context, alias, query)
6755
+ );
6718
6756
  }
6719
6757
  /**
6720
6758
  * Adds a JOIN against a derived table (subquery with alias)
@@ -6947,7 +6985,8 @@ var SelectQueryBuilder = class _SelectQueryBuilder {
6947
6985
  ensureDefaultSelection() {
6948
6986
  const columns = this.context.state.ast.columns;
6949
6987
  if (!columns || columns.length === 0) {
6950
- return this.select(...Object.keys(this.env.table.columns));
6988
+ const columnKeys = Object.keys(this.env.table.columns);
6989
+ return this.select(...columnKeys);
6951
6990
  }
6952
6991
  return this;
6953
6992
  }
@@ -6983,7 +7022,8 @@ var SelectQueryBuilder = class _SelectQueryBuilder {
6983
7022
  */
6984
7023
  async executePlain(ctx) {
6985
7024
  const builder = this.ensureDefaultSelection();
6986
- return executeHydrated(ctx, builder);
7025
+ const rows = await executeHydratedPlain(ctx, builder);
7026
+ return rows;
6987
7027
  }
6988
7028
  /**
6989
7029
  * Executes the query and returns results as real class instances.
@@ -12738,6 +12778,7 @@ export {
12738
12778
  aliasRef,
12739
12779
  and,
12740
12780
  arrayAppend,
12781
+ asType,
12741
12782
  ascii,
12742
12783
  asin,
12743
12784
  atan,
@@ -12803,6 +12844,8 @@ export {
12803
12844
  eq,
12804
12845
  esel,
12805
12846
  executeHydrated,
12847
+ executeHydratedPlain,
12848
+ executeHydratedPlainWithContexts,
12806
12849
  executeHydratedWithContexts,
12807
12850
  executeSchemaSql,
12808
12851
  executeSchemaSqlFor,