metal-orm 1.0.66 → 1.0.68

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
@@ -653,8 +653,8 @@ interface TableRef {
653
653
  */
654
654
  interface LiteralNode {
655
655
  type: 'Literal';
656
- /** The literal value (string, number, boolean, or null) */
657
- value: string | number | boolean | null;
656
+ /** The literal value (string, number, boolean, Date, or null) */
657
+ value: string | number | boolean | Date | null;
658
658
  }
659
659
  /**
660
660
  * AST node representing a reference to a SELECT alias (for ORDER BY / GROUP BY).
@@ -3466,9 +3466,10 @@ interface SaveGraphOptions {
3466
3466
  /**
3467
3467
  * Coerce JSON-friendly input values into DB-friendly primitives.
3468
3468
  * Currently:
3469
- * - Date -> ISO string (for DATE/DATETIME/TIMESTAMP/TIMESTAMPTZ columns)
3469
+ * - `json`: Date -> ISO string (for DATE/DATETIME/TIMESTAMP/TIMESTAMPTZ columns)
3470
+ * - `json-in`: string/number -> Date (for DATE/DATETIME/TIMESTAMP/TIMESTAMPTZ columns)
3470
3471
  */
3471
- coerce?: 'json';
3472
+ coerce?: 'json' | 'json-in';
3472
3473
  }
3473
3474
 
3474
3475
  type AnyId = number | string;
@@ -3486,8 +3487,9 @@ type SaveGraphJsonScalar<T> = T extends Date ? string : T;
3486
3487
  * Input scalar type for `OrmSession.saveGraph` payloads.
3487
3488
  *
3488
3489
  * Note: runtime coercion is opt-in via `SaveGraphOptions.coerce`.
3490
+ * For Date columns, string input is only safe when using `coerce: 'json-in'`.
3489
3491
  */
3490
- type SaveGraphInputScalar<T> = T;
3492
+ type SaveGraphInputScalar<T> = T extends Date ? T | string | number : T;
3491
3493
  type ColumnInput$1<TEntity> = {
3492
3494
  [K in ColumnKeys<TEntity>]?: SaveGraphInputScalar<TEntity[K]>;
3493
3495
  };
@@ -3532,6 +3534,12 @@ interface OrmSessionOptions<E extends DomainEvent = OrmDomainEvent> {
3532
3534
  /** Optional domain event handlers */
3533
3535
  domainEventHandlers?: InitialHandlers<E, OrmSession<E>>;
3534
3536
  }
3537
+ interface SaveGraphSessionOptions extends SaveGraphOptions {
3538
+ /** Wrap the save operation in a transaction (default: true). */
3539
+ transactional?: boolean;
3540
+ /** Flush after saveGraph when not transactional (default: false). */
3541
+ flush?: boolean;
3542
+ }
3535
3543
  /**
3536
3544
  * ORM Session that manages entity lifecycle, identity mapping, and database operations.
3537
3545
  * @template E - The domain event type
@@ -3550,6 +3558,7 @@ declare class OrmSession<E extends DomainEvent = OrmDomainEvent> implements Enti
3550
3558
  /** The relation change processor */
3551
3559
  readonly relationChanges: RelationChangeProcessor;
3552
3560
  private readonly interceptors;
3561
+ private saveGraphDefaults?;
3553
3562
  /**
3554
3563
  * Creates a new OrmSession instance.
3555
3564
  * @param opts - Session options
@@ -3639,6 +3648,12 @@ declare class OrmSession<E extends DomainEvent = OrmDomainEvent> implements Enti
3639
3648
  registerDomainEventHandler<TType extends E['type']>(type: TType, handler: DomainEventHandler<Extract<E, {
3640
3649
  type: TType;
3641
3650
  }>, OrmSession<E>>): void;
3651
+ /**
3652
+ * Sets default options applied to all saveGraph calls for this session.
3653
+ * Per-call options override these defaults.
3654
+ * @param defaults - Default saveGraph options for the session
3655
+ */
3656
+ withSaveGraphDefaults(defaults: SaveGraphSessionOptions): this;
3642
3657
  /**
3643
3658
  * Finds an entity by its primary key.
3644
3659
  * @template TCtor - The entity constructor type
@@ -3669,9 +3684,23 @@ declare class OrmSession<E extends DomainEvent = OrmDomainEvent> implements Enti
3669
3684
  * @param options - Graph save options
3670
3685
  * @returns The root entity instance
3671
3686
  */
3672
- saveGraph<TCtor extends EntityConstructor<object>>(entityClass: TCtor, payload: SaveGraphInputPayload<InstanceType<TCtor>>, options?: SaveGraphOptions & {
3673
- transactional?: boolean;
3674
- }): Promise<InstanceType<TCtor>>;
3687
+ saveGraph<TCtor extends EntityConstructor<object>>(entityClass: TCtor, payload: SaveGraphInputPayload<InstanceType<TCtor>>, options?: SaveGraphSessionOptions): Promise<InstanceType<TCtor>>;
3688
+ /**
3689
+ * Saves an entity graph and flushes immediately (defaults to transactional: false).
3690
+ * @param entityClass - Root entity constructor
3691
+ * @param payload - DTO payload containing column values and nested relations
3692
+ * @param options - Graph save options
3693
+ * @returns The root entity instance
3694
+ */
3695
+ saveGraphAndFlush<TCtor extends EntityConstructor<object>>(entityClass: TCtor, payload: SaveGraphInputPayload<InstanceType<TCtor>>, options?: SaveGraphSessionOptions): Promise<InstanceType<TCtor>>;
3696
+ /**
3697
+ * Updates an existing entity graph (requires a primary key in the payload).
3698
+ * @param entityClass - Root entity constructor
3699
+ * @param payload - DTO payload containing column values and nested relations
3700
+ * @param options - Graph save options
3701
+ * @returns The root entity instance or null if not found
3702
+ */
3703
+ updateGraph<TCtor extends EntityConstructor<object>>(entityClass: TCtor, payload: SaveGraphInputPayload<InstanceType<TCtor>>, options?: SaveGraphSessionOptions): Promise<InstanceType<TCtor> | null>;
3675
3704
  /**
3676
3705
  * Persists an entity (either inserts or updates).
3677
3706
  * @param entity - The entity to persist
@@ -3717,6 +3746,12 @@ declare class OrmSession<E extends DomainEvent = OrmDomainEvent> implements Enti
3717
3746
  * @returns The hydration context
3718
3747
  */
3719
3748
  getHydrationContext(): HydrationContext<E>;
3749
+ /**
3750
+ * Merges session defaults with per-call saveGraph options.
3751
+ * @param options - Per-call saveGraph options
3752
+ * @returns Combined options with per-call values taking precedence
3753
+ */
3754
+ private resolveSaveGraphOptions;
3720
3755
  }
3721
3756
 
3722
3757
  type WhereHasOptions = {
@@ -6948,4 +6983,4 @@ type PooledExecutorFactoryOptions<TConn> = {
6948
6983
  */
6949
6984
  declare function createPooledExecutorFactory<TConn>(opts: PooledExecutorFactoryOptions<TConn>): DbExecutorFactory;
6950
6985
 
6951
- 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, type PrimaryKey$1 as EntityPrimaryKey, 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, type TypedLike, 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 };
6986
+ 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, type PrimaryKey$1 as EntityPrimaryKey, 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 SaveGraphSessionOptions, 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, type TypedLike, 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
@@ -653,8 +653,8 @@ interface TableRef {
653
653
  */
654
654
  interface LiteralNode {
655
655
  type: 'Literal';
656
- /** The literal value (string, number, boolean, or null) */
657
- value: string | number | boolean | null;
656
+ /** The literal value (string, number, boolean, Date, or null) */
657
+ value: string | number | boolean | Date | null;
658
658
  }
659
659
  /**
660
660
  * AST node representing a reference to a SELECT alias (for ORDER BY / GROUP BY).
@@ -3466,9 +3466,10 @@ interface SaveGraphOptions {
3466
3466
  /**
3467
3467
  * Coerce JSON-friendly input values into DB-friendly primitives.
3468
3468
  * Currently:
3469
- * - Date -> ISO string (for DATE/DATETIME/TIMESTAMP/TIMESTAMPTZ columns)
3469
+ * - `json`: Date -> ISO string (for DATE/DATETIME/TIMESTAMP/TIMESTAMPTZ columns)
3470
+ * - `json-in`: string/number -> Date (for DATE/DATETIME/TIMESTAMP/TIMESTAMPTZ columns)
3470
3471
  */
3471
- coerce?: 'json';
3472
+ coerce?: 'json' | 'json-in';
3472
3473
  }
3473
3474
 
3474
3475
  type AnyId = number | string;
@@ -3486,8 +3487,9 @@ type SaveGraphJsonScalar<T> = T extends Date ? string : T;
3486
3487
  * Input scalar type for `OrmSession.saveGraph` payloads.
3487
3488
  *
3488
3489
  * Note: runtime coercion is opt-in via `SaveGraphOptions.coerce`.
3490
+ * For Date columns, string input is only safe when using `coerce: 'json-in'`.
3489
3491
  */
3490
- type SaveGraphInputScalar<T> = T;
3492
+ type SaveGraphInputScalar<T> = T extends Date ? T | string | number : T;
3491
3493
  type ColumnInput$1<TEntity> = {
3492
3494
  [K in ColumnKeys<TEntity>]?: SaveGraphInputScalar<TEntity[K]>;
3493
3495
  };
@@ -3532,6 +3534,12 @@ interface OrmSessionOptions<E extends DomainEvent = OrmDomainEvent> {
3532
3534
  /** Optional domain event handlers */
3533
3535
  domainEventHandlers?: InitialHandlers<E, OrmSession<E>>;
3534
3536
  }
3537
+ interface SaveGraphSessionOptions extends SaveGraphOptions {
3538
+ /** Wrap the save operation in a transaction (default: true). */
3539
+ transactional?: boolean;
3540
+ /** Flush after saveGraph when not transactional (default: false). */
3541
+ flush?: boolean;
3542
+ }
3535
3543
  /**
3536
3544
  * ORM Session that manages entity lifecycle, identity mapping, and database operations.
3537
3545
  * @template E - The domain event type
@@ -3550,6 +3558,7 @@ declare class OrmSession<E extends DomainEvent = OrmDomainEvent> implements Enti
3550
3558
  /** The relation change processor */
3551
3559
  readonly relationChanges: RelationChangeProcessor;
3552
3560
  private readonly interceptors;
3561
+ private saveGraphDefaults?;
3553
3562
  /**
3554
3563
  * Creates a new OrmSession instance.
3555
3564
  * @param opts - Session options
@@ -3639,6 +3648,12 @@ declare class OrmSession<E extends DomainEvent = OrmDomainEvent> implements Enti
3639
3648
  registerDomainEventHandler<TType extends E['type']>(type: TType, handler: DomainEventHandler<Extract<E, {
3640
3649
  type: TType;
3641
3650
  }>, OrmSession<E>>): void;
3651
+ /**
3652
+ * Sets default options applied to all saveGraph calls for this session.
3653
+ * Per-call options override these defaults.
3654
+ * @param defaults - Default saveGraph options for the session
3655
+ */
3656
+ withSaveGraphDefaults(defaults: SaveGraphSessionOptions): this;
3642
3657
  /**
3643
3658
  * Finds an entity by its primary key.
3644
3659
  * @template TCtor - The entity constructor type
@@ -3669,9 +3684,23 @@ declare class OrmSession<E extends DomainEvent = OrmDomainEvent> implements Enti
3669
3684
  * @param options - Graph save options
3670
3685
  * @returns The root entity instance
3671
3686
  */
3672
- saveGraph<TCtor extends EntityConstructor<object>>(entityClass: TCtor, payload: SaveGraphInputPayload<InstanceType<TCtor>>, options?: SaveGraphOptions & {
3673
- transactional?: boolean;
3674
- }): Promise<InstanceType<TCtor>>;
3687
+ saveGraph<TCtor extends EntityConstructor<object>>(entityClass: TCtor, payload: SaveGraphInputPayload<InstanceType<TCtor>>, options?: SaveGraphSessionOptions): Promise<InstanceType<TCtor>>;
3688
+ /**
3689
+ * Saves an entity graph and flushes immediately (defaults to transactional: false).
3690
+ * @param entityClass - Root entity constructor
3691
+ * @param payload - DTO payload containing column values and nested relations
3692
+ * @param options - Graph save options
3693
+ * @returns The root entity instance
3694
+ */
3695
+ saveGraphAndFlush<TCtor extends EntityConstructor<object>>(entityClass: TCtor, payload: SaveGraphInputPayload<InstanceType<TCtor>>, options?: SaveGraphSessionOptions): Promise<InstanceType<TCtor>>;
3696
+ /**
3697
+ * Updates an existing entity graph (requires a primary key in the payload).
3698
+ * @param entityClass - Root entity constructor
3699
+ * @param payload - DTO payload containing column values and nested relations
3700
+ * @param options - Graph save options
3701
+ * @returns The root entity instance or null if not found
3702
+ */
3703
+ updateGraph<TCtor extends EntityConstructor<object>>(entityClass: TCtor, payload: SaveGraphInputPayload<InstanceType<TCtor>>, options?: SaveGraphSessionOptions): Promise<InstanceType<TCtor> | null>;
3675
3704
  /**
3676
3705
  * Persists an entity (either inserts or updates).
3677
3706
  * @param entity - The entity to persist
@@ -3717,6 +3746,12 @@ declare class OrmSession<E extends DomainEvent = OrmDomainEvent> implements Enti
3717
3746
  * @returns The hydration context
3718
3747
  */
3719
3748
  getHydrationContext(): HydrationContext<E>;
3749
+ /**
3750
+ * Merges session defaults with per-call saveGraph options.
3751
+ * @param options - Per-call saveGraph options
3752
+ * @returns Combined options with per-call values taking precedence
3753
+ */
3754
+ private resolveSaveGraphOptions;
3720
3755
  }
3721
3756
 
3722
3757
  type WhereHasOptions = {
@@ -6948,4 +6983,4 @@ type PooledExecutorFactoryOptions<TConn> = {
6948
6983
  */
6949
6984
  declare function createPooledExecutorFactory<TConn>(opts: PooledExecutorFactoryOptions<TConn>): DbExecutorFactory;
6950
6985
 
6951
- 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, type PrimaryKey$1 as EntityPrimaryKey, 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, type TypedLike, 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 };
6986
+ 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, type PrimaryKey$1 as EntityPrimaryKey, 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 SaveGraphSessionOptions, 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, type TypedLike, 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
@@ -383,10 +383,10 @@ var isWindowFunctionNode = (node) => isOperandNode(node) && node.type === "Windo
383
383
  var isExpressionSelectionNode = (node) => isFunctionNode(node) || isCaseExpressionNode(node) || isCastExpressionNode(node) || isWindowFunctionNode(node);
384
384
 
385
385
  // src/core/ast/expression-builders.ts
386
- var isLiteralValue = (value) => value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
386
+ var isLiteralValue = (value) => value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value instanceof Date;
387
387
  var toLiteralNode = (value) => ({
388
388
  type: "Literal",
389
- value
389
+ value: value instanceof Date ? value.toISOString() : value
390
390
  });
391
391
  var columnRefToNode = (col2) => {
392
392
  if (!col2.table) {
@@ -11449,14 +11449,28 @@ var runInTransaction = async (executor, action) => {
11449
11449
  // src/orm/save-graph.ts
11450
11450
  var toKey8 = (value) => value === null || value === void 0 ? "" : String(value);
11451
11451
  var coerceColumnValue = (table, columnName, value, options) => {
11452
- if (options.coerce !== "json") return value;
11453
11452
  if (value === null || value === void 0) return value;
11454
11453
  const column = table.columns[columnName];
11455
11454
  if (!column) return value;
11456
11455
  const normalized = normalizeColumnType(column.type);
11457
11456
  const isDateLikeColumn = normalized === "date" || normalized === "datetime" || normalized === "timestamp" || normalized === "timestamptz";
11458
- if (isDateLikeColumn && value instanceof Date) {
11459
- return value.toISOString();
11457
+ if (!isDateLikeColumn) return value;
11458
+ if (options.coerce === "json") {
11459
+ if (value instanceof Date) {
11460
+ return value.toISOString();
11461
+ }
11462
+ return value;
11463
+ }
11464
+ if (options.coerce === "json-in") {
11465
+ if (value instanceof Date) return value;
11466
+ if (typeof value === "string" || typeof value === "number") {
11467
+ const date = new Date(value);
11468
+ if (Number.isNaN(date.getTime())) {
11469
+ throw new Error(`Invalid date value for column "${columnName}"`);
11470
+ }
11471
+ return date;
11472
+ }
11473
+ return value;
11460
11474
  }
11461
11475
  return value;
11462
11476
  };
@@ -11653,6 +11667,7 @@ var OrmSession = class {
11653
11667
  /** The relation change processor */
11654
11668
  relationChanges;
11655
11669
  interceptors;
11670
+ saveGraphDefaults;
11656
11671
  /**
11657
11672
  * Creates a new OrmSession instance.
11658
11673
  * @param opts - Session options
@@ -11783,6 +11798,15 @@ var OrmSession = class {
11783
11798
  registerDomainEventHandler(type, handler) {
11784
11799
  this.domainEvents.on(type, handler);
11785
11800
  }
11801
+ /**
11802
+ * Sets default options applied to all saveGraph calls for this session.
11803
+ * Per-call options override these defaults.
11804
+ * @param defaults - Default saveGraph options for the session
11805
+ */
11806
+ withSaveGraphDefaults(defaults) {
11807
+ this.saveGraphDefaults = { ...defaults };
11808
+ return this;
11809
+ }
11786
11810
  /**
11787
11811
  * Finds an entity by its primary key.
11788
11812
  * @template TCtor - The entity constructor type
@@ -11830,10 +11854,60 @@ var OrmSession = class {
11830
11854
  return executeHydrated(this, qb);
11831
11855
  }
11832
11856
  async saveGraph(entityClass, payload, options) {
11833
- const { transactional = true, ...graphOptions } = options ?? {};
11857
+ const resolved = this.resolveSaveGraphOptions(options);
11858
+ const { transactional = true, flush = false, ...graphOptions } = resolved;
11834
11859
  const execute = () => saveGraphInternal(this, entityClass, payload, graphOptions);
11835
11860
  if (!transactional) {
11836
- return execute();
11861
+ const result = await execute();
11862
+ if (flush) {
11863
+ await this.flush();
11864
+ }
11865
+ return result;
11866
+ }
11867
+ return this.transaction(() => execute());
11868
+ }
11869
+ /**
11870
+ * Saves an entity graph and flushes immediately (defaults to transactional: false).
11871
+ * @param entityClass - Root entity constructor
11872
+ * @param payload - DTO payload containing column values and nested relations
11873
+ * @param options - Graph save options
11874
+ * @returns The root entity instance
11875
+ */
11876
+ async saveGraphAndFlush(entityClass, payload, options) {
11877
+ const merged = { ...options ?? {}, flush: true, transactional: options?.transactional ?? false };
11878
+ return this.saveGraph(entityClass, payload, merged);
11879
+ }
11880
+ /**
11881
+ * Updates an existing entity graph (requires a primary key in the payload).
11882
+ * @param entityClass - Root entity constructor
11883
+ * @param payload - DTO payload containing column values and nested relations
11884
+ * @param options - Graph save options
11885
+ * @returns The root entity instance or null if not found
11886
+ */
11887
+ async updateGraph(entityClass, payload, options) {
11888
+ const table = getTableDefFromEntity(entityClass);
11889
+ if (!table) {
11890
+ throw new Error("Entity metadata has not been bootstrapped");
11891
+ }
11892
+ const primaryKey = findPrimaryKey(table);
11893
+ const pkValue = payload[primaryKey];
11894
+ if (pkValue === void 0 || pkValue === null) {
11895
+ throw new Error(`updateGraph requires a primary key value for "${primaryKey}"`);
11896
+ }
11897
+ const resolved = this.resolveSaveGraphOptions(options);
11898
+ const { transactional = true, flush = false, ...graphOptions } = resolved;
11899
+ const execute = async () => {
11900
+ const tracked = this.getEntity(table, pkValue);
11901
+ const existing = tracked ?? await this.find(entityClass, pkValue);
11902
+ if (!existing) return null;
11903
+ return saveGraphInternal(this, entityClass, payload, graphOptions);
11904
+ };
11905
+ if (!transactional) {
11906
+ const result = await execute();
11907
+ if (result && flush) {
11908
+ await this.flush();
11909
+ }
11910
+ return result;
11837
11911
  }
11838
11912
  return this.transaction(() => execute());
11839
11913
  }
@@ -11953,6 +12027,14 @@ var OrmSession = class {
11953
12027
  entityContext: this
11954
12028
  };
11955
12029
  }
12030
+ /**
12031
+ * Merges session defaults with per-call saveGraph options.
12032
+ * @param options - Per-call saveGraph options
12033
+ * @returns Combined options with per-call values taking precedence
12034
+ */
12035
+ resolveSaveGraphOptions(options) {
12036
+ return { ...this.saveGraphDefaults ?? {}, ...options ?? {} };
12037
+ }
11956
12038
  };
11957
12039
  var buildRelationChangeEntry = (root, relationKey, rootTable, relationName, relation, change) => ({
11958
12040
  root,