metal-orm 1.0.52 → 1.0.53

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
@@ -1082,6 +1082,11 @@ declare const min: (col: ColumnRef | ColumnNode) => FunctionNode;
1082
1082
  * @returns Function node with MAX
1083
1083
  */
1084
1084
  declare const max: (col: ColumnRef | ColumnNode) => FunctionNode;
1085
+ /**
1086
+ * Creates a COUNT(*) function expression.
1087
+ * @returns Function node with COUNT(*)
1088
+ */
1089
+ declare const countAll: () => FunctionNode;
1085
1090
  type GroupConcatOrderByInput = {
1086
1091
  column: ColumnRef | ColumnNode;
1087
1092
  direction?: OrderDirection;
@@ -3009,11 +3014,11 @@ type RelationKeys<T> = {
3009
3014
  type ColumnKeys<T> = Exclude<keyof T & string, FunctionKeys<T> | RelationKeys<T>>;
3010
3015
  type SaveGraphJsonScalar<T> = T extends Date ? string : T;
3011
3016
  /**
3012
- * Input scalar type that accepts JSON-friendly values for common runtime types.
3013
- * Currently:
3014
- * - Date fields accept `Date | string` (ISO string recommended)
3017
+ * Input scalar type for `OrmSession.saveGraph` payloads.
3018
+ *
3019
+ * Note: runtime coercion is opt-in via `SaveGraphOptions.coerce`.
3015
3020
  */
3016
- type SaveGraphInputScalar<T> = T extends Date ? Date | string : T;
3021
+ type SaveGraphInputScalar<T> = T;
3017
3022
  type ColumnInput$1<TEntity> = {
3018
3023
  [K in ColumnKeys<TEntity>]?: SaveGraphInputScalar<TEntity[K]>;
3019
3024
  };
@@ -3024,7 +3029,6 @@ type RelationInput<TEntity> = {
3024
3029
  /**
3025
3030
  * Typed payload accepted by `OrmSession.saveGraph`:
3026
3031
  * - Only entity scalar keys + relation keys are accepted.
3027
- * - Scalars can use JSON-friendly values (e.g., Date fields accept ISO strings).
3028
3032
  */
3029
3033
  type SaveGraphInputPayload<TEntity> = ColumnInput$1<TEntity> & RelationInput<TEntity>;
3030
3034
 
@@ -3491,6 +3495,15 @@ declare class SelectQueryBuilder<T = unknown, TTable extends TableDef = TableDef
3491
3495
  * @returns Promise of entity instances
3492
3496
  */
3493
3497
  execute(ctx: OrmSession): Promise<EntityInstance<TTable>[]>;
3498
+ private withAst;
3499
+ count(session: OrmSession): Promise<number>;
3500
+ executePaged(session: OrmSession, options: {
3501
+ page: number;
3502
+ pageSize: number;
3503
+ }): Promise<{
3504
+ items: EntityInstance<TTable>[];
3505
+ totalItems: number;
3506
+ }>;
3494
3507
  /**
3495
3508
  * Executes the query with provided execution and hydration contexts
3496
3509
  * @param execCtx - Execution context
@@ -5289,7 +5302,7 @@ declare function executeHydrated<TTable extends TableDef>(session: OrmSession, q
5289
5302
  * @param qb - The select query builder
5290
5303
  * @returns Promise resolving to array of entity instances
5291
5304
  */
5292
- declare function executeHydratedWithContexts<TTable extends TableDef>(_execCtx: ExecutionContext, hydCtx: HydrationContext, qb: SelectQueryBuilder<unknown, TTable>): Promise<EntityInstance<TTable>[]>;
5305
+ declare function executeHydratedWithContexts<TTable extends TableDef>(execCtx: ExecutionContext, hydCtx: HydrationContext, qb: SelectQueryBuilder<unknown, TTable>): Promise<EntityInstance<TTable>[]>;
5293
5306
 
5294
5307
  type JsonifyScalar<T> = T extends Date ? string : T;
5295
5308
  /**
@@ -5605,4 +5618,4 @@ type PooledExecutorFactoryOptions<TConn> = {
5605
5618
  */
5606
5619
  declare function createPooledExecutorFactory<TConn>(opts: PooledExecutorFactoryOptions<TConn>): DbExecutorFactory;
5607
5620
 
5608
- export { type AliasRefNode, type AnyDomainEvent, type ArithmeticExpressionNode, type TableRef as AstTableRef, AsyncLocalStorage, BelongsTo, BelongsToMany, type BelongsToManyOptions, type BelongsToManyRelation, type BelongsToOptions, type BelongsToReference, type BelongsToRelation, type BetweenExpressionNode, type BinaryExpressionNode, type CascadeMode, type CaseExpressionNode, type CastExpressionNode, type CheckConstraint, Column, type ColumnDef, type ColumnDiff, type ColumnInput, type ColumnNode, type ColumnOptions, type ColumnRef, type ColumnToTs, type ColumnType, type CreateTediousClientOptions, type DatabaseCheck, type DatabaseColumn, type DatabaseIndex, type DatabaseSchema, type DatabaseTable, type DbExecutor, type DbExecutorFactory, DefaultBelongsToReference, DefaultHasManyCollection, DefaultManyToManyCollection, type DefaultValue, DeleteQueryBuilder, type DialectName, type DomainEvent, DomainEventBus, type DomainEventHandler, Entity, type EntityContext, type EntityInstance, 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 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 QueryLogEntry, type QueryLogger, type QueryResult, type RawDefaultValue, type ReferentialAction, type RelationChange, type RelationChangeEntry, type RelationDef, type 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 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, aliasRef, and, ascii, asin, atan, atan2, avg, belongsTo, belongsToMany, between, bootstrapEntities, caseWhen, cast, ceil, ceiling, char, charLength, clearExpressionDispatchers, clearOperandDispatchers, col, columnOperand, concat, concatWs, correlateBy, cos, cot, count, createEntityFromRow, createEntityProxy, createExecutorFromQueryRunner, createMssqlExecutor, createMysqlExecutor, createPooledExecutorFactory, createPostgresExecutor, createQueryLoggingExecutor, createSqliteExecutor, createTediousExecutor, createTediousMssqlClient, currentDate, currentTime, dateAdd, dateDiff, dateFormat, dateSub, dateTrunc, day, dayOfWeek, defineTable, degrees, denseRank, diffSchema, div, endOfMonth, entityRef, eq, esel, executeHydrated, executeHydratedWithContexts, exists, exp, extract, firstValue, floor, fromUnixTime, generateCreateTableSql, generateSchemaSql, getColumn, getSchemaIntrospector, getTableDefFromEntity, groupConcat, gt, gte, hasMany, hasOne, hydrateRows, inList, inSubquery, instr, introspectSchema, isCaseExpressionNode, isCastExpressionNode, isExpressionSelectionNode, isFunctionNode, isNotNull, isNull, isOperandNode, isValueOperandInput, isWindowFunctionNode, jsonPath, jsonify, lag, lastValue, lead, left, length, like, ln, loadBelongsToManyRelation, loadBelongsToRelation, loadHasManyRelation, loadHasOneRelation, locate, log, log10, logBase, lower, lpad, lt, lte, ltrim, max, min, mod, month, mul, neq, normalizeColumnType, notBetween, notExists, notInList, notInSubquery, notLike, now, ntile, or, outerRef, pi, position, pow, power, radians, rand, random, rank, registerExpressionDispatcher, registerOperandDispatcher, registerSchemaIntrospector, renderColumnDefinition, renderTypeWithArgs, repeat, replace, right, round, rowNumber, rowsToQueryResult, rpad, rtrim, sel, selectFromEntity, sign, sin, space, sqrt, sub, substr, sum, synchronizeSchema, tableRef, tan, toColumnRef, toTableRef, trim, trunc, truncate, unixTimestamp, upper, utcNow, valueToOperand, visitExpression, visitOperand, weekOfYear, windowFunction, year };
5621
+ export { type AliasRefNode, type AnyDomainEvent, type ArithmeticExpressionNode, type TableRef as AstTableRef, AsyncLocalStorage, BelongsTo, BelongsToMany, type BelongsToManyOptions, type BelongsToManyRelation, type BelongsToOptions, type BelongsToReference, type BelongsToRelation, type BetweenExpressionNode, type BinaryExpressionNode, type CascadeMode, type CaseExpressionNode, type CastExpressionNode, type CheckConstraint, Column, type ColumnDef, type ColumnDiff, type ColumnInput, type ColumnNode, type ColumnOptions, type ColumnRef, type ColumnToTs, type ColumnType, type CreateTediousClientOptions, type DatabaseCheck, type DatabaseColumn, type DatabaseIndex, type DatabaseSchema, type DatabaseTable, type DbExecutor, type DbExecutorFactory, DefaultBelongsToReference, DefaultHasManyCollection, DefaultManyToManyCollection, type DefaultValue, DeleteQueryBuilder, type DialectName, type DomainEvent, DomainEventBus, type DomainEventHandler, Entity, type EntityContext, type EntityInstance, 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 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 QueryLogEntry, type QueryLogger, type QueryResult, type RawDefaultValue, type ReferentialAction, type RelationChange, type RelationChangeEntry, type RelationDef, type 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 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, aliasRef, and, ascii, asin, atan, atan2, avg, belongsTo, belongsToMany, between, bootstrapEntities, caseWhen, cast, ceil, ceiling, char, charLength, clearExpressionDispatchers, clearOperandDispatchers, col, 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, denseRank, diffSchema, div, endOfMonth, entityRef, eq, esel, executeHydrated, executeHydratedWithContexts, exists, exp, extract, firstValue, floor, fromUnixTime, generateCreateTableSql, generateSchemaSql, getColumn, getSchemaIntrospector, getTableDefFromEntity, groupConcat, gt, gte, hasMany, hasOne, hydrateRows, inList, inSubquery, instr, introspectSchema, isCaseExpressionNode, isCastExpressionNode, isExpressionSelectionNode, isFunctionNode, isNotNull, isNull, isOperandNode, isValueOperandInput, isWindowFunctionNode, jsonPath, jsonify, lag, lastValue, lead, left, length, like, ln, loadBelongsToManyRelation, loadBelongsToRelation, loadHasManyRelation, loadHasOneRelation, locate, log, log10, logBase, lower, lpad, lt, lte, ltrim, max, min, mod, month, mul, neq, normalizeColumnType, notBetween, notExists, notInList, notInSubquery, notLike, now, ntile, or, outerRef, pi, position, pow, power, radians, rand, random, rank, registerExpressionDispatcher, registerOperandDispatcher, registerSchemaIntrospector, renderColumnDefinition, renderTypeWithArgs, repeat, replace, right, round, rowNumber, rowsToQueryResult, rpad, rtrim, sel, selectFromEntity, sign, sin, space, sqrt, sub, substr, sum, synchronizeSchema, tableRef, tan, toColumnRef, toTableRef, trim, trunc, truncate, unixTimestamp, upper, utcNow, valueToOperand, visitExpression, visitOperand, weekOfYear, windowFunction, year };
package/dist/index.d.ts CHANGED
@@ -1082,6 +1082,11 @@ declare const min: (col: ColumnRef | ColumnNode) => FunctionNode;
1082
1082
  * @returns Function node with MAX
1083
1083
  */
1084
1084
  declare const max: (col: ColumnRef | ColumnNode) => FunctionNode;
1085
+ /**
1086
+ * Creates a COUNT(*) function expression.
1087
+ * @returns Function node with COUNT(*)
1088
+ */
1089
+ declare const countAll: () => FunctionNode;
1085
1090
  type GroupConcatOrderByInput = {
1086
1091
  column: ColumnRef | ColumnNode;
1087
1092
  direction?: OrderDirection;
@@ -3009,11 +3014,11 @@ type RelationKeys<T> = {
3009
3014
  type ColumnKeys<T> = Exclude<keyof T & string, FunctionKeys<T> | RelationKeys<T>>;
3010
3015
  type SaveGraphJsonScalar<T> = T extends Date ? string : T;
3011
3016
  /**
3012
- * Input scalar type that accepts JSON-friendly values for common runtime types.
3013
- * Currently:
3014
- * - Date fields accept `Date | string` (ISO string recommended)
3017
+ * Input scalar type for `OrmSession.saveGraph` payloads.
3018
+ *
3019
+ * Note: runtime coercion is opt-in via `SaveGraphOptions.coerce`.
3015
3020
  */
3016
- type SaveGraphInputScalar<T> = T extends Date ? Date | string : T;
3021
+ type SaveGraphInputScalar<T> = T;
3017
3022
  type ColumnInput$1<TEntity> = {
3018
3023
  [K in ColumnKeys<TEntity>]?: SaveGraphInputScalar<TEntity[K]>;
3019
3024
  };
@@ -3024,7 +3029,6 @@ type RelationInput<TEntity> = {
3024
3029
  /**
3025
3030
  * Typed payload accepted by `OrmSession.saveGraph`:
3026
3031
  * - Only entity scalar keys + relation keys are accepted.
3027
- * - Scalars can use JSON-friendly values (e.g., Date fields accept ISO strings).
3028
3032
  */
3029
3033
  type SaveGraphInputPayload<TEntity> = ColumnInput$1<TEntity> & RelationInput<TEntity>;
3030
3034
 
@@ -3491,6 +3495,15 @@ declare class SelectQueryBuilder<T = unknown, TTable extends TableDef = TableDef
3491
3495
  * @returns Promise of entity instances
3492
3496
  */
3493
3497
  execute(ctx: OrmSession): Promise<EntityInstance<TTable>[]>;
3498
+ private withAst;
3499
+ count(session: OrmSession): Promise<number>;
3500
+ executePaged(session: OrmSession, options: {
3501
+ page: number;
3502
+ pageSize: number;
3503
+ }): Promise<{
3504
+ items: EntityInstance<TTable>[];
3505
+ totalItems: number;
3506
+ }>;
3494
3507
  /**
3495
3508
  * Executes the query with provided execution and hydration contexts
3496
3509
  * @param execCtx - Execution context
@@ -5289,7 +5302,7 @@ declare function executeHydrated<TTable extends TableDef>(session: OrmSession, q
5289
5302
  * @param qb - The select query builder
5290
5303
  * @returns Promise resolving to array of entity instances
5291
5304
  */
5292
- declare function executeHydratedWithContexts<TTable extends TableDef>(_execCtx: ExecutionContext, hydCtx: HydrationContext, qb: SelectQueryBuilder<unknown, TTable>): Promise<EntityInstance<TTable>[]>;
5305
+ declare function executeHydratedWithContexts<TTable extends TableDef>(execCtx: ExecutionContext, hydCtx: HydrationContext, qb: SelectQueryBuilder<unknown, TTable>): Promise<EntityInstance<TTable>[]>;
5293
5306
 
5294
5307
  type JsonifyScalar<T> = T extends Date ? string : T;
5295
5308
  /**
@@ -5605,4 +5618,4 @@ type PooledExecutorFactoryOptions<TConn> = {
5605
5618
  */
5606
5619
  declare function createPooledExecutorFactory<TConn>(opts: PooledExecutorFactoryOptions<TConn>): DbExecutorFactory;
5607
5620
 
5608
- export { type AliasRefNode, type AnyDomainEvent, type ArithmeticExpressionNode, type TableRef as AstTableRef, AsyncLocalStorage, BelongsTo, BelongsToMany, type BelongsToManyOptions, type BelongsToManyRelation, type BelongsToOptions, type BelongsToReference, type BelongsToRelation, type BetweenExpressionNode, type BinaryExpressionNode, type CascadeMode, type CaseExpressionNode, type CastExpressionNode, type CheckConstraint, Column, type ColumnDef, type ColumnDiff, type ColumnInput, type ColumnNode, type ColumnOptions, type ColumnRef, type ColumnToTs, type ColumnType, type CreateTediousClientOptions, type DatabaseCheck, type DatabaseColumn, type DatabaseIndex, type DatabaseSchema, type DatabaseTable, type DbExecutor, type DbExecutorFactory, DefaultBelongsToReference, DefaultHasManyCollection, DefaultManyToManyCollection, type DefaultValue, DeleteQueryBuilder, type DialectName, type DomainEvent, DomainEventBus, type DomainEventHandler, Entity, type EntityContext, type EntityInstance, 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 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 QueryLogEntry, type QueryLogger, type QueryResult, type RawDefaultValue, type ReferentialAction, type RelationChange, type RelationChangeEntry, type RelationDef, type 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 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, aliasRef, and, ascii, asin, atan, atan2, avg, belongsTo, belongsToMany, between, bootstrapEntities, caseWhen, cast, ceil, ceiling, char, charLength, clearExpressionDispatchers, clearOperandDispatchers, col, columnOperand, concat, concatWs, correlateBy, cos, cot, count, createEntityFromRow, createEntityProxy, createExecutorFromQueryRunner, createMssqlExecutor, createMysqlExecutor, createPooledExecutorFactory, createPostgresExecutor, createQueryLoggingExecutor, createSqliteExecutor, createTediousExecutor, createTediousMssqlClient, currentDate, currentTime, dateAdd, dateDiff, dateFormat, dateSub, dateTrunc, day, dayOfWeek, defineTable, degrees, denseRank, diffSchema, div, endOfMonth, entityRef, eq, esel, executeHydrated, executeHydratedWithContexts, exists, exp, extract, firstValue, floor, fromUnixTime, generateCreateTableSql, generateSchemaSql, getColumn, getSchemaIntrospector, getTableDefFromEntity, groupConcat, gt, gte, hasMany, hasOne, hydrateRows, inList, inSubquery, instr, introspectSchema, isCaseExpressionNode, isCastExpressionNode, isExpressionSelectionNode, isFunctionNode, isNotNull, isNull, isOperandNode, isValueOperandInput, isWindowFunctionNode, jsonPath, jsonify, lag, lastValue, lead, left, length, like, ln, loadBelongsToManyRelation, loadBelongsToRelation, loadHasManyRelation, loadHasOneRelation, locate, log, log10, logBase, lower, lpad, lt, lte, ltrim, max, min, mod, month, mul, neq, normalizeColumnType, notBetween, notExists, notInList, notInSubquery, notLike, now, ntile, or, outerRef, pi, position, pow, power, radians, rand, random, rank, registerExpressionDispatcher, registerOperandDispatcher, registerSchemaIntrospector, renderColumnDefinition, renderTypeWithArgs, repeat, replace, right, round, rowNumber, rowsToQueryResult, rpad, rtrim, sel, selectFromEntity, sign, sin, space, sqrt, sub, substr, sum, synchronizeSchema, tableRef, tan, toColumnRef, toTableRef, trim, trunc, truncate, unixTimestamp, upper, utcNow, valueToOperand, visitExpression, visitOperand, weekOfYear, windowFunction, year };
5621
+ export { type AliasRefNode, type AnyDomainEvent, type ArithmeticExpressionNode, type TableRef as AstTableRef, AsyncLocalStorage, BelongsTo, BelongsToMany, type BelongsToManyOptions, type BelongsToManyRelation, type BelongsToOptions, type BelongsToReference, type BelongsToRelation, type BetweenExpressionNode, type BinaryExpressionNode, type CascadeMode, type CaseExpressionNode, type CastExpressionNode, type CheckConstraint, Column, type ColumnDef, type ColumnDiff, type ColumnInput, type ColumnNode, type ColumnOptions, type ColumnRef, type ColumnToTs, type ColumnType, type CreateTediousClientOptions, type DatabaseCheck, type DatabaseColumn, type DatabaseIndex, type DatabaseSchema, type DatabaseTable, type DbExecutor, type DbExecutorFactory, DefaultBelongsToReference, DefaultHasManyCollection, DefaultManyToManyCollection, type DefaultValue, DeleteQueryBuilder, type DialectName, type DomainEvent, DomainEventBus, type DomainEventHandler, Entity, type EntityContext, type EntityInstance, 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 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 QueryLogEntry, type QueryLogger, type QueryResult, type RawDefaultValue, type ReferentialAction, type RelationChange, type RelationChangeEntry, type RelationDef, type 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 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, aliasRef, and, ascii, asin, atan, atan2, avg, belongsTo, belongsToMany, between, bootstrapEntities, caseWhen, cast, ceil, ceiling, char, charLength, clearExpressionDispatchers, clearOperandDispatchers, col, 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, denseRank, diffSchema, div, endOfMonth, entityRef, eq, esel, executeHydrated, executeHydratedWithContexts, exists, exp, extract, firstValue, floor, fromUnixTime, generateCreateTableSql, generateSchemaSql, getColumn, getSchemaIntrospector, getTableDefFromEntity, groupConcat, gt, gte, hasMany, hasOne, hydrateRows, inList, inSubquery, instr, introspectSchema, isCaseExpressionNode, isCastExpressionNode, isExpressionSelectionNode, isFunctionNode, isNotNull, isNull, isOperandNode, isValueOperandInput, isWindowFunctionNode, jsonPath, jsonify, lag, lastValue, lead, left, length, like, ln, loadBelongsToManyRelation, loadBelongsToRelation, loadHasManyRelation, loadHasOneRelation, locate, log, log10, logBase, lower, lpad, lt, lte, ltrim, max, min, mod, month, mul, neq, normalizeColumnType, notBetween, notExists, notInList, notInSubquery, notLike, now, ntile, or, outerRef, pi, position, pow, power, radians, rand, random, rank, registerExpressionDispatcher, registerOperandDispatcher, registerSchemaIntrospector, renderColumnDefinition, renderTypeWithArgs, repeat, replace, right, round, rowNumber, rowsToQueryResult, rpad, rtrim, sel, selectFromEntity, sign, sin, space, sqrt, sub, substr, sum, synchronizeSchema, tableRef, tan, toColumnRef, toTableRef, trim, trunc, truncate, unixTimestamp, upper, utcNow, valueToOperand, visitExpression, visitOperand, weekOfYear, windowFunction, year };
package/dist/index.js CHANGED
@@ -653,6 +653,11 @@ var sum = buildAggregate("SUM");
653
653
  var avg = buildAggregate("AVG");
654
654
  var min = buildAggregate("MIN");
655
655
  var max = buildAggregate("MAX");
656
+ var countAll = () => ({
657
+ type: "Function",
658
+ name: "COUNT",
659
+ args: []
660
+ });
656
661
  var toOrderByNode = (order) => ({
657
662
  type: "OrderBy",
658
663
  term: columnOperand(order.column),
@@ -855,7 +860,7 @@ var StandardFunctionStrategy = class _StandardFunctionStrategy {
855
860
  this.registerStandard();
856
861
  }
857
862
  registerStandard() {
858
- this.add("COUNT", ({ compiledArgs }) => `COUNT(${compiledArgs.join(", ")})`);
863
+ this.add("COUNT", ({ compiledArgs }) => compiledArgs.length ? `COUNT(${compiledArgs.join(", ")})` : "COUNT(*)");
859
864
  this.add("SUM", ({ compiledArgs }) => `SUM(${compiledArgs[0]})`);
860
865
  this.add("AVG", ({ compiledArgs }) => `AVG(${compiledArgs[0]})`);
861
866
  this.add("MIN", ({ compiledArgs }) => `MIN(${compiledArgs[0]})`);
@@ -4781,10 +4786,10 @@ var flattenResults = (results) => {
4781
4786
  }
4782
4787
  return rows;
4783
4788
  };
4784
- var executeWithEntityContext = async (entityCtx, qb) => {
4789
+ var executeWithContexts = async (execCtx, entityCtx, qb) => {
4785
4790
  const ast = qb.getAST();
4786
- const compiled = entityCtx.dialect.compileSelect(ast);
4787
- const executed = await entityCtx.executor.executeSql(compiled.sql, compiled.params);
4791
+ const compiled = execCtx.dialect.compileSelect(ast);
4792
+ const executed = await execCtx.interceptors.run({ sql: compiled.sql, params: compiled.params }, execCtx.executor);
4788
4793
  const rows = flattenResults(executed);
4789
4794
  if (ast.setOps && ast.setOps.length > 0) {
4790
4795
  return rows.map((row) => createEntityProxy(entityCtx, qb.getTable(), row, qb.getLazyRelations()));
@@ -4793,14 +4798,14 @@ var executeWithEntityContext = async (entityCtx, qb) => {
4793
4798
  return hydrated.map((row) => createEntityFromRow(entityCtx, qb.getTable(), row, qb.getLazyRelations()));
4794
4799
  };
4795
4800
  async function executeHydrated(session, qb) {
4796
- return executeWithEntityContext(session, qb);
4801
+ return executeWithContexts(session.getExecutionContext(), session, qb);
4797
4802
  }
4798
- async function executeHydratedWithContexts(_execCtx, hydCtx, qb) {
4803
+ async function executeHydratedWithContexts(execCtx, hydCtx, qb) {
4799
4804
  const entityCtx = hydCtx.entityContext;
4800
4805
  if (!entityCtx) {
4801
4806
  throw new Error("Hydration context is missing an EntityContext");
4802
4807
  }
4803
- return executeWithEntityContext(entityCtx, qb);
4808
+ return executeWithContexts(execCtx, entityCtx, qb);
4804
4809
  }
4805
4810
 
4806
4811
  // src/query-builder/query-resolution.ts
@@ -5154,6 +5159,52 @@ var SelectQueryBuilder = class _SelectQueryBuilder {
5154
5159
  async execute(ctx) {
5155
5160
  return executeHydrated(ctx, this);
5156
5161
  }
5162
+ withAst(ast) {
5163
+ const nextState = new SelectQueryState(this.env.table, ast);
5164
+ const nextContext = {
5165
+ ...this.context,
5166
+ state: nextState
5167
+ };
5168
+ return this.clone(nextContext);
5169
+ }
5170
+ async count(session) {
5171
+ const unpagedAst = {
5172
+ ...this.context.state.ast,
5173
+ orderBy: void 0,
5174
+ limit: void 0,
5175
+ offset: void 0
5176
+ };
5177
+ const subAst = this.withAst(unpagedAst).getAST();
5178
+ const countQuery = {
5179
+ type: "SelectQuery",
5180
+ from: derivedTable(subAst, "__metal_count"),
5181
+ columns: [{ type: "Function", name: "COUNT", args: [], alias: "total" }],
5182
+ joins: []
5183
+ };
5184
+ const execCtx = session.getExecutionContext();
5185
+ const compiled = execCtx.dialect.compileSelect(countQuery);
5186
+ const results = await execCtx.interceptors.run({ sql: compiled.sql, params: compiled.params }, execCtx.executor);
5187
+ const value = results[0]?.values?.[0]?.[0];
5188
+ if (typeof value === "number") return value;
5189
+ if (typeof value === "bigint") return Number(value);
5190
+ if (typeof value === "string") return Number(value);
5191
+ return value === null || value === void 0 ? 0 : Number(value);
5192
+ }
5193
+ async executePaged(session, options) {
5194
+ const { page, pageSize } = options;
5195
+ if (!Number.isInteger(page) || page < 1) {
5196
+ throw new Error("executePaged: page must be an integer >= 1");
5197
+ }
5198
+ if (!Number.isInteger(pageSize) || pageSize < 1) {
5199
+ throw new Error("executePaged: pageSize must be an integer >= 1");
5200
+ }
5201
+ const offset = (page - 1) * pageSize;
5202
+ const [items, totalItems] = await Promise.all([
5203
+ this.limit(pageSize).offset(offset).execute(session),
5204
+ this.count(session)
5205
+ ]);
5206
+ return { items, totalItems };
5207
+ }
5157
5208
  /**
5158
5209
  * Executes the query with provided execution and hydration contexts
5159
5210
  * @param execCtx - Execution context
@@ -6003,8 +6054,9 @@ var UpdateQueryBuilder = class _UpdateQueryBuilder {
6003
6054
  * @returns A promise that resolves to the query results
6004
6055
  */
6005
6056
  async execute(session) {
6006
- const compiled = this.compile(session.dialect);
6007
- return session.executor.executeSql(compiled.sql, compiled.params);
6057
+ const execCtx = session.getExecutionContext();
6058
+ const compiled = this.compile(execCtx.dialect);
6059
+ return execCtx.interceptors.run({ sql: compiled.sql, params: compiled.params }, execCtx.executor);
6008
6060
  }
6009
6061
  /**
6010
6062
  * Returns the Abstract Syntax Tree (AST) representation of the query
@@ -6188,8 +6240,9 @@ var DeleteQueryBuilder = class _DeleteQueryBuilder {
6188
6240
  * @returns A promise that resolves to the query results
6189
6241
  */
6190
6242
  async execute(session) {
6191
- const compiled = this.compile(session.dialect);
6192
- return session.executor.executeSql(compiled.sql, compiled.params);
6243
+ const execCtx = session.getExecutionContext();
6244
+ const compiled = this.compile(execCtx.dialect);
6245
+ return execCtx.interceptors.run({ sql: compiled.sql, params: compiled.params }, execCtx.executor);
6193
6246
  }
6194
6247
  /**
6195
6248
  * Returns the Abstract Syntax Tree (AST) representation of the query
@@ -10701,6 +10754,7 @@ export {
10701
10754
  cos,
10702
10755
  cot,
10703
10756
  count,
10757
+ countAll,
10704
10758
  createEntityFromRow,
10705
10759
  createEntityProxy,
10706
10760
  createExecutorFromQueryRunner,