metal-orm 1.0.51 → 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/README.md +18 -15
- package/dist/index.cjs +103 -30
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +68 -3
- package/dist/index.d.ts +68 -3
- package/dist/index.js +101 -30
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/core/ast/aggregate-functions.ts +10 -0
- package/src/core/functions/standard-strategy.ts +1 -1
- package/src/index.ts +4 -2
- package/src/orm/execute.ts +37 -36
- package/src/orm/jsonify.ts +27 -0
- package/src/orm/orm-session.ts +28 -22
- package/src/orm/save-graph-types.ts +55 -0
- package/src/orm/save-graph.ts +141 -105
- package/src/query-builder/delete.ts +5 -4
- package/src/query-builder/select.ts +68 -10
- package/src/query-builder/update.ts +5 -4
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;
|
|
@@ -2989,8 +2994,44 @@ interface HydrationContext<E extends DomainEvent = AnyDomainEvent> {
|
|
|
2989
2994
|
interface SaveGraphOptions {
|
|
2990
2995
|
/** Remove existing collection members that are not present in the payload */
|
|
2991
2996
|
pruneMissing?: boolean;
|
|
2997
|
+
/**
|
|
2998
|
+
* Coerce JSON-friendly input values into DB-friendly primitives.
|
|
2999
|
+
* Currently:
|
|
3000
|
+
* - Date -> ISO string (for DATE/DATETIME/TIMESTAMP/TIMESTAMPTZ columns)
|
|
3001
|
+
*/
|
|
3002
|
+
coerce?: 'json';
|
|
2992
3003
|
}
|
|
2993
3004
|
|
|
3005
|
+
type AnyId = number | string;
|
|
3006
|
+
type AnyFn = (...args: unknown[]) => unknown;
|
|
3007
|
+
type RelationWrapper = HasManyCollection<unknown> | HasOneReference<unknown> | BelongsToReference<unknown> | ManyToManyCollection<unknown>;
|
|
3008
|
+
type FunctionKeys<T> = {
|
|
3009
|
+
[K in keyof T & string]-?: T[K] extends AnyFn ? K : never;
|
|
3010
|
+
}[keyof T & string];
|
|
3011
|
+
type RelationKeys<T> = {
|
|
3012
|
+
[K in keyof T & string]-?: NonNullable<T[K]> extends RelationWrapper ? K : never;
|
|
3013
|
+
}[keyof T & string];
|
|
3014
|
+
type ColumnKeys<T> = Exclude<keyof T & string, FunctionKeys<T> | RelationKeys<T>>;
|
|
3015
|
+
type SaveGraphJsonScalar<T> = T extends Date ? string : T;
|
|
3016
|
+
/**
|
|
3017
|
+
* Input scalar type for `OrmSession.saveGraph` payloads.
|
|
3018
|
+
*
|
|
3019
|
+
* Note: runtime coercion is opt-in via `SaveGraphOptions.coerce`.
|
|
3020
|
+
*/
|
|
3021
|
+
type SaveGraphInputScalar<T> = T;
|
|
3022
|
+
type ColumnInput$1<TEntity> = {
|
|
3023
|
+
[K in ColumnKeys<TEntity>]?: SaveGraphInputScalar<TEntity[K]>;
|
|
3024
|
+
};
|
|
3025
|
+
type RelationInputValue<T> = T extends HasManyCollection<infer C> ? Array<SaveGraphInputPayload<C> | AnyId> : T extends HasOneReference<infer C> ? SaveGraphInputPayload<C> | AnyId | null : T extends BelongsToReference<infer P> ? SaveGraphInputPayload<P> | AnyId | null : T extends ManyToManyCollection<infer Tgt> ? Array<SaveGraphInputPayload<Tgt> | AnyId> : never;
|
|
3026
|
+
type RelationInput<TEntity> = {
|
|
3027
|
+
[K in RelationKeys<TEntity>]?: RelationInputValue<NonNullable<TEntity[K]>>;
|
|
3028
|
+
};
|
|
3029
|
+
/**
|
|
3030
|
+
* Typed payload accepted by `OrmSession.saveGraph`:
|
|
3031
|
+
* - Only entity scalar keys + relation keys are accepted.
|
|
3032
|
+
*/
|
|
3033
|
+
type SaveGraphInputPayload<TEntity> = ColumnInput$1<TEntity> & RelationInput<TEntity>;
|
|
3034
|
+
|
|
2994
3035
|
/**
|
|
2995
3036
|
* Interface for ORM interceptors that allow hooking into the flush lifecycle.
|
|
2996
3037
|
*/
|
|
@@ -3159,7 +3200,7 @@ declare class OrmSession<E extends DomainEvent = OrmDomainEvent> implements Enti
|
|
|
3159
3200
|
* @param options - Graph save options
|
|
3160
3201
|
* @returns The root entity instance
|
|
3161
3202
|
*/
|
|
3162
|
-
saveGraph<TCtor extends EntityConstructor<object>>(entityClass: TCtor, payload:
|
|
3203
|
+
saveGraph<TCtor extends EntityConstructor<object>>(entityClass: TCtor, payload: SaveGraphInputPayload<InstanceType<TCtor>>, options?: SaveGraphOptions & {
|
|
3163
3204
|
transactional?: boolean;
|
|
3164
3205
|
}): Promise<InstanceType<TCtor>>;
|
|
3165
3206
|
/**
|
|
@@ -3454,6 +3495,15 @@ declare class SelectQueryBuilder<T = unknown, TTable extends TableDef = TableDef
|
|
|
3454
3495
|
* @returns Promise of entity instances
|
|
3455
3496
|
*/
|
|
3456
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
|
+
}>;
|
|
3457
3507
|
/**
|
|
3458
3508
|
* Executes the query with provided execution and hydration contexts
|
|
3459
3509
|
* @param execCtx - Execution context
|
|
@@ -5252,7 +5302,22 @@ declare function executeHydrated<TTable extends TableDef>(session: OrmSession, q
|
|
|
5252
5302
|
* @param qb - The select query builder
|
|
5253
5303
|
* @returns Promise resolving to array of entity instances
|
|
5254
5304
|
*/
|
|
5255
|
-
declare function executeHydratedWithContexts<TTable extends TableDef>(
|
|
5305
|
+
declare function executeHydratedWithContexts<TTable extends TableDef>(execCtx: ExecutionContext, hydCtx: HydrationContext, qb: SelectQueryBuilder<unknown, TTable>): Promise<EntityInstance<TTable>[]>;
|
|
5306
|
+
|
|
5307
|
+
type JsonifyScalar<T> = T extends Date ? string : T;
|
|
5308
|
+
/**
|
|
5309
|
+
* Shallow JSON-friendly mapping:
|
|
5310
|
+
* - Date -> ISO string
|
|
5311
|
+
* - Everything else unchanged
|
|
5312
|
+
*/
|
|
5313
|
+
type Jsonify<T> = {
|
|
5314
|
+
[K in keyof T]: JsonifyScalar<T[K]>;
|
|
5315
|
+
};
|
|
5316
|
+
/**
|
|
5317
|
+
* Creates a shallow, JSON-friendly copy of an object by converting `Date` values to ISO strings.
|
|
5318
|
+
* This intentionally does not deep-walk nested objects/relations.
|
|
5319
|
+
*/
|
|
5320
|
+
declare const jsonify: <T extends object>(value: T) => Jsonify<T>;
|
|
5256
5321
|
|
|
5257
5322
|
/**
|
|
5258
5323
|
* Context object provided by standard decorators in newer TypeScript versions.
|
|
@@ -5553,4 +5618,4 @@ type PooledExecutorFactoryOptions<TConn> = {
|
|
|
5553
5618
|
*/
|
|
5554
5619
|
declare function createPooledExecutorFactory<TConn>(opts: PooledExecutorFactoryOptions<TConn>): DbExecutorFactory;
|
|
5555
5620
|
|
|
5556
|
-
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 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 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, 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;
|
|
@@ -2989,8 +2994,44 @@ interface HydrationContext<E extends DomainEvent = AnyDomainEvent> {
|
|
|
2989
2994
|
interface SaveGraphOptions {
|
|
2990
2995
|
/** Remove existing collection members that are not present in the payload */
|
|
2991
2996
|
pruneMissing?: boolean;
|
|
2997
|
+
/**
|
|
2998
|
+
* Coerce JSON-friendly input values into DB-friendly primitives.
|
|
2999
|
+
* Currently:
|
|
3000
|
+
* - Date -> ISO string (for DATE/DATETIME/TIMESTAMP/TIMESTAMPTZ columns)
|
|
3001
|
+
*/
|
|
3002
|
+
coerce?: 'json';
|
|
2992
3003
|
}
|
|
2993
3004
|
|
|
3005
|
+
type AnyId = number | string;
|
|
3006
|
+
type AnyFn = (...args: unknown[]) => unknown;
|
|
3007
|
+
type RelationWrapper = HasManyCollection<unknown> | HasOneReference<unknown> | BelongsToReference<unknown> | ManyToManyCollection<unknown>;
|
|
3008
|
+
type FunctionKeys<T> = {
|
|
3009
|
+
[K in keyof T & string]-?: T[K] extends AnyFn ? K : never;
|
|
3010
|
+
}[keyof T & string];
|
|
3011
|
+
type RelationKeys<T> = {
|
|
3012
|
+
[K in keyof T & string]-?: NonNullable<T[K]> extends RelationWrapper ? K : never;
|
|
3013
|
+
}[keyof T & string];
|
|
3014
|
+
type ColumnKeys<T> = Exclude<keyof T & string, FunctionKeys<T> | RelationKeys<T>>;
|
|
3015
|
+
type SaveGraphJsonScalar<T> = T extends Date ? string : T;
|
|
3016
|
+
/**
|
|
3017
|
+
* Input scalar type for `OrmSession.saveGraph` payloads.
|
|
3018
|
+
*
|
|
3019
|
+
* Note: runtime coercion is opt-in via `SaveGraphOptions.coerce`.
|
|
3020
|
+
*/
|
|
3021
|
+
type SaveGraphInputScalar<T> = T;
|
|
3022
|
+
type ColumnInput$1<TEntity> = {
|
|
3023
|
+
[K in ColumnKeys<TEntity>]?: SaveGraphInputScalar<TEntity[K]>;
|
|
3024
|
+
};
|
|
3025
|
+
type RelationInputValue<T> = T extends HasManyCollection<infer C> ? Array<SaveGraphInputPayload<C> | AnyId> : T extends HasOneReference<infer C> ? SaveGraphInputPayload<C> | AnyId | null : T extends BelongsToReference<infer P> ? SaveGraphInputPayload<P> | AnyId | null : T extends ManyToManyCollection<infer Tgt> ? Array<SaveGraphInputPayload<Tgt> | AnyId> : never;
|
|
3026
|
+
type RelationInput<TEntity> = {
|
|
3027
|
+
[K in RelationKeys<TEntity>]?: RelationInputValue<NonNullable<TEntity[K]>>;
|
|
3028
|
+
};
|
|
3029
|
+
/**
|
|
3030
|
+
* Typed payload accepted by `OrmSession.saveGraph`:
|
|
3031
|
+
* - Only entity scalar keys + relation keys are accepted.
|
|
3032
|
+
*/
|
|
3033
|
+
type SaveGraphInputPayload<TEntity> = ColumnInput$1<TEntity> & RelationInput<TEntity>;
|
|
3034
|
+
|
|
2994
3035
|
/**
|
|
2995
3036
|
* Interface for ORM interceptors that allow hooking into the flush lifecycle.
|
|
2996
3037
|
*/
|
|
@@ -3159,7 +3200,7 @@ declare class OrmSession<E extends DomainEvent = OrmDomainEvent> implements Enti
|
|
|
3159
3200
|
* @param options - Graph save options
|
|
3160
3201
|
* @returns The root entity instance
|
|
3161
3202
|
*/
|
|
3162
|
-
saveGraph<TCtor extends EntityConstructor<object>>(entityClass: TCtor, payload:
|
|
3203
|
+
saveGraph<TCtor extends EntityConstructor<object>>(entityClass: TCtor, payload: SaveGraphInputPayload<InstanceType<TCtor>>, options?: SaveGraphOptions & {
|
|
3163
3204
|
transactional?: boolean;
|
|
3164
3205
|
}): Promise<InstanceType<TCtor>>;
|
|
3165
3206
|
/**
|
|
@@ -3454,6 +3495,15 @@ declare class SelectQueryBuilder<T = unknown, TTable extends TableDef = TableDef
|
|
|
3454
3495
|
* @returns Promise of entity instances
|
|
3455
3496
|
*/
|
|
3456
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
|
+
}>;
|
|
3457
3507
|
/**
|
|
3458
3508
|
* Executes the query with provided execution and hydration contexts
|
|
3459
3509
|
* @param execCtx - Execution context
|
|
@@ -5252,7 +5302,22 @@ declare function executeHydrated<TTable extends TableDef>(session: OrmSession, q
|
|
|
5252
5302
|
* @param qb - The select query builder
|
|
5253
5303
|
* @returns Promise resolving to array of entity instances
|
|
5254
5304
|
*/
|
|
5255
|
-
declare function executeHydratedWithContexts<TTable extends TableDef>(
|
|
5305
|
+
declare function executeHydratedWithContexts<TTable extends TableDef>(execCtx: ExecutionContext, hydCtx: HydrationContext, qb: SelectQueryBuilder<unknown, TTable>): Promise<EntityInstance<TTable>[]>;
|
|
5306
|
+
|
|
5307
|
+
type JsonifyScalar<T> = T extends Date ? string : T;
|
|
5308
|
+
/**
|
|
5309
|
+
* Shallow JSON-friendly mapping:
|
|
5310
|
+
* - Date -> ISO string
|
|
5311
|
+
* - Everything else unchanged
|
|
5312
|
+
*/
|
|
5313
|
+
type Jsonify<T> = {
|
|
5314
|
+
[K in keyof T]: JsonifyScalar<T[K]>;
|
|
5315
|
+
};
|
|
5316
|
+
/**
|
|
5317
|
+
* Creates a shallow, JSON-friendly copy of an object by converting `Date` values to ISO strings.
|
|
5318
|
+
* This intentionally does not deep-walk nested objects/relations.
|
|
5319
|
+
*/
|
|
5320
|
+
declare const jsonify: <T extends object>(value: T) => Jsonify<T>;
|
|
5256
5321
|
|
|
5257
5322
|
/**
|
|
5258
5323
|
* Context object provided by standard decorators in newer TypeScript versions.
|
|
@@ -5553,4 +5618,4 @@ type PooledExecutorFactoryOptions<TConn> = {
|
|
|
5553
5618
|
*/
|
|
5554
5619
|
declare function createPooledExecutorFactory<TConn>(opts: PooledExecutorFactoryOptions<TConn>): DbExecutorFactory;
|
|
5555
5620
|
|
|
5556
|
-
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 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 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, 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
|
|
4789
|
+
var executeWithContexts = async (execCtx, entityCtx, qb) => {
|
|
4785
4790
|
const ast = qb.getAST();
|
|
4786
|
-
const compiled =
|
|
4787
|
-
const executed = await
|
|
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
|
|
4801
|
+
return executeWithContexts(session.getExecutionContext(), session, qb);
|
|
4797
4802
|
}
|
|
4798
|
-
async function executeHydratedWithContexts(
|
|
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
|
|
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
|
|
6007
|
-
|
|
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
|
|
6192
|
-
|
|
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
|
|
@@ -9301,18 +9354,30 @@ var runInTransaction = async (executor, action) => {
|
|
|
9301
9354
|
|
|
9302
9355
|
// src/orm/save-graph.ts
|
|
9303
9356
|
var toKey8 = (value) => value === null || value === void 0 ? "" : String(value);
|
|
9304
|
-
var
|
|
9357
|
+
var coerceColumnValue = (table, columnName, value, options) => {
|
|
9358
|
+
if (options.coerce !== "json") return value;
|
|
9359
|
+
if (value === null || value === void 0) return value;
|
|
9360
|
+
const column = table.columns[columnName];
|
|
9361
|
+
if (!column) return value;
|
|
9362
|
+
const normalized = normalizeColumnType(column.type);
|
|
9363
|
+
const isDateLikeColumn = normalized === "date" || normalized === "datetime" || normalized === "timestamp" || normalized === "timestamptz";
|
|
9364
|
+
if (isDateLikeColumn && value instanceof Date) {
|
|
9365
|
+
return value.toISOString();
|
|
9366
|
+
}
|
|
9367
|
+
return value;
|
|
9368
|
+
};
|
|
9369
|
+
var pickColumns = (table, payload, options) => {
|
|
9305
9370
|
const columns = {};
|
|
9306
9371
|
for (const key of Object.keys(table.columns)) {
|
|
9307
9372
|
if (payload[key] !== void 0) {
|
|
9308
|
-
columns[key] = payload[key];
|
|
9373
|
+
columns[key] = coerceColumnValue(table, key, payload[key], options);
|
|
9309
9374
|
}
|
|
9310
9375
|
}
|
|
9311
9376
|
return columns;
|
|
9312
9377
|
};
|
|
9313
|
-
var ensureEntity = (session, table, payload) => {
|
|
9378
|
+
var ensureEntity = (session, table, payload, options) => {
|
|
9314
9379
|
const pk = findPrimaryKey(table);
|
|
9315
|
-
const row = pickColumns(table, payload);
|
|
9380
|
+
const row = pickColumns(table, payload, options);
|
|
9316
9381
|
const pkValue = payload[pk];
|
|
9317
9382
|
if (pkValue !== void 0 && pkValue !== null) {
|
|
9318
9383
|
const tracked = session.getEntity(table, pkValue);
|
|
@@ -9325,10 +9390,10 @@ var ensureEntity = (session, table, payload) => {
|
|
|
9325
9390
|
}
|
|
9326
9391
|
return createEntityFromRow(session, table, row);
|
|
9327
9392
|
};
|
|
9328
|
-
var assignColumns = (table, entity, payload) => {
|
|
9393
|
+
var assignColumns = (table, entity, payload, options) => {
|
|
9329
9394
|
for (const key of Object.keys(table.columns)) {
|
|
9330
9395
|
if (payload[key] !== void 0) {
|
|
9331
|
-
entity[key] = payload[key];
|
|
9396
|
+
entity[key] = coerceColumnValue(table, key, payload[key], options);
|
|
9332
9397
|
}
|
|
9333
9398
|
}
|
|
9334
9399
|
};
|
|
@@ -9355,8 +9420,8 @@ var handleHasMany = async (session, root, relationName, relation, payload, optio
|
|
|
9355
9420
|
const asObj = typeof item === "object" ? item : { [targetPk]: item };
|
|
9356
9421
|
const pkValue = asObj[targetPk];
|
|
9357
9422
|
const current = findInCollectionByPk(existing, targetPk, pkValue) ?? (pkValue !== void 0 && pkValue !== null ? session.getEntity(targetTable, pkValue) : void 0);
|
|
9358
|
-
const entity = current ?? ensureEntity(session, targetTable, asObj);
|
|
9359
|
-
assignColumns(targetTable, entity, asObj);
|
|
9423
|
+
const entity = current ?? ensureEntity(session, targetTable, asObj, options);
|
|
9424
|
+
assignColumns(targetTable, entity, asObj, options);
|
|
9360
9425
|
await applyGraphToEntity(session, targetTable, entity, asObj, options);
|
|
9361
9426
|
if (!isEntityInCollection(collection.getItems(), targetPk, entity)) {
|
|
9362
9427
|
collection.attach(entity);
|
|
@@ -9431,8 +9496,8 @@ var handleBelongsToMany = async (session, root, relationName, relation, payload,
|
|
|
9431
9496
|
}
|
|
9432
9497
|
const asObj = item;
|
|
9433
9498
|
const pkValue = asObj[targetPk];
|
|
9434
|
-
const entity = pkValue !== void 0 && pkValue !== null ? session.getEntity(targetTable, pkValue) ?? ensureEntity(session, targetTable, asObj) : ensureEntity(session, targetTable, asObj);
|
|
9435
|
-
assignColumns(targetTable, entity, asObj);
|
|
9499
|
+
const entity = pkValue !== void 0 && pkValue !== null ? session.getEntity(targetTable, pkValue) ?? ensureEntity(session, targetTable, asObj, options) : ensureEntity(session, targetTable, asObj, options);
|
|
9500
|
+
assignColumns(targetTable, entity, asObj, options);
|
|
9436
9501
|
await applyGraphToEntity(session, targetTable, entity, asObj, options);
|
|
9437
9502
|
if (!isEntityInCollection(collection.getItems(), targetPk, entity)) {
|
|
9438
9503
|
collection.attach(entity);
|
|
@@ -9463,7 +9528,7 @@ var applyRelation = async (session, table, entity, relationName, relation, paylo
|
|
|
9463
9528
|
}
|
|
9464
9529
|
};
|
|
9465
9530
|
var applyGraphToEntity = async (session, table, entity, payload, options) => {
|
|
9466
|
-
assignColumns(table, entity, payload);
|
|
9531
|
+
assignColumns(table, entity, payload, options);
|
|
9467
9532
|
for (const [relationName, relation] of Object.entries(table.relations)) {
|
|
9468
9533
|
if (!(relationName in payload)) continue;
|
|
9469
9534
|
await applyRelation(session, table, entity, relationName, relation, payload[relationName], options);
|
|
@@ -9474,7 +9539,7 @@ var saveGraphInternal = async (session, entityClass, payload, options = {}) => {
|
|
|
9474
9539
|
if (!table) {
|
|
9475
9540
|
throw new Error("Entity metadata has not been bootstrapped");
|
|
9476
9541
|
}
|
|
9477
|
-
const root = ensureEntity(session, table, payload);
|
|
9542
|
+
const root = ensureEntity(session, table, payload, options);
|
|
9478
9543
|
await applyGraphToEntity(session, table, root, payload, options);
|
|
9479
9544
|
return root;
|
|
9480
9545
|
};
|
|
@@ -9657,13 +9722,6 @@ var OrmSession = class {
|
|
|
9657
9722
|
async findMany(qb) {
|
|
9658
9723
|
return executeHydrated(this, qb);
|
|
9659
9724
|
}
|
|
9660
|
-
/**
|
|
9661
|
-
* Saves an entity graph (root + nested relations) based on a DTO-like payload.
|
|
9662
|
-
* @param entityClass - Root entity constructor
|
|
9663
|
-
* @param payload - DTO payload containing column values and nested relations
|
|
9664
|
-
* @param options - Graph save options
|
|
9665
|
-
* @returns The root entity instance
|
|
9666
|
-
*/
|
|
9667
9725
|
async saveGraph(entityClass, payload, options) {
|
|
9668
9726
|
const { transactional = true, ...graphOptions } = options ?? {};
|
|
9669
9727
|
const execute = () => saveGraphInternal(this, entityClass, payload, graphOptions);
|
|
@@ -9864,6 +9922,17 @@ var Orm = class {
|
|
|
9864
9922
|
}
|
|
9865
9923
|
};
|
|
9866
9924
|
|
|
9925
|
+
// src/orm/jsonify.ts
|
|
9926
|
+
var jsonify = (value) => {
|
|
9927
|
+
const record = value;
|
|
9928
|
+
const result = {};
|
|
9929
|
+
for (const key of Object.keys(record)) {
|
|
9930
|
+
const entry = record[key];
|
|
9931
|
+
result[key] = entry instanceof Date ? entry.toISOString() : entry;
|
|
9932
|
+
}
|
|
9933
|
+
return result;
|
|
9934
|
+
};
|
|
9935
|
+
|
|
9867
9936
|
// src/decorators/decorator-metadata.ts
|
|
9868
9937
|
var METADATA_KEY = "metal-orm:decorators";
|
|
9869
9938
|
var isStandardDecoratorContext = (value) => {
|
|
@@ -10685,6 +10754,7 @@ export {
|
|
|
10685
10754
|
cos,
|
|
10686
10755
|
cot,
|
|
10687
10756
|
count,
|
|
10757
|
+
countAll,
|
|
10688
10758
|
createEntityFromRow,
|
|
10689
10759
|
createEntityProxy,
|
|
10690
10760
|
createExecutorFromQueryRunner,
|
|
@@ -10747,6 +10817,7 @@ export {
|
|
|
10747
10817
|
isValueOperandInput,
|
|
10748
10818
|
isWindowFunctionNode,
|
|
10749
10819
|
jsonPath,
|
|
10820
|
+
jsonify,
|
|
10750
10821
|
lag,
|
|
10751
10822
|
lastValue,
|
|
10752
10823
|
lead,
|