metal-orm 1.0.40 → 1.0.42

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.
Files changed (45) hide show
  1. package/README.md +53 -14
  2. package/dist/index.cjs +1298 -126
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +676 -30
  5. package/dist/index.d.ts +676 -30
  6. package/dist/index.js +1293 -126
  7. package/dist/index.js.map +1 -1
  8. package/package.json +1 -1
  9. package/src/codegen/typescript.ts +6 -2
  10. package/src/core/ast/expression-builders.ts +25 -4
  11. package/src/core/ast/expression-nodes.ts +3 -1
  12. package/src/core/ast/expression.ts +2 -2
  13. package/src/core/ast/query.ts +24 -2
  14. package/src/core/dialect/abstract.ts +6 -2
  15. package/src/core/dialect/base/join-compiler.ts +9 -12
  16. package/src/core/dialect/base/sql-dialect.ts +98 -17
  17. package/src/core/dialect/mssql/index.ts +30 -62
  18. package/src/core/dialect/sqlite/index.ts +39 -34
  19. package/src/core/execution/db-executor.ts +46 -6
  20. package/src/core/execution/executors/mssql-executor.ts +39 -22
  21. package/src/core/execution/executors/mysql-executor.ts +23 -6
  22. package/src/core/execution/executors/sqlite-executor.ts +29 -3
  23. package/src/core/execution/pooling/pool-types.ts +30 -0
  24. package/src/core/execution/pooling/pool.ts +268 -0
  25. package/src/decorators/bootstrap.ts +7 -7
  26. package/src/index.ts +6 -0
  27. package/src/orm/domain-event-bus.ts +49 -0
  28. package/src/orm/entity-metadata.ts +9 -9
  29. package/src/orm/entity.ts +58 -0
  30. package/src/orm/orm-session.ts +465 -270
  31. package/src/orm/orm.ts +61 -11
  32. package/src/orm/pooled-executor-factory.ts +131 -0
  33. package/src/orm/query-logger.ts +6 -12
  34. package/src/orm/relation-change-processor.ts +75 -0
  35. package/src/orm/relations/many-to-many.ts +4 -2
  36. package/src/orm/save-graph.ts +303 -0
  37. package/src/orm/transaction-runner.ts +3 -3
  38. package/src/orm/unit-of-work.ts +128 -0
  39. package/src/query-builder/delete-query-state.ts +67 -38
  40. package/src/query-builder/delete.ts +37 -1
  41. package/src/query-builder/insert-query-state.ts +131 -61
  42. package/src/query-builder/insert.ts +27 -1
  43. package/src/query-builder/update-query-state.ts +114 -77
  44. package/src/query-builder/update.ts +38 -1
  45. package/src/schema/table.ts +210 -115
package/dist/index.d.cts CHANGED
@@ -365,6 +365,27 @@ interface TableDef<T extends Record<string, ColumnDef> = Record<string, ColumnDe
365
365
  * ```
366
366
  */
367
367
  declare const defineTable: <T extends Record<string, ColumnDef>>(name: string, columns: T, relations?: Record<string, RelationDef>, hooks?: TableHooks, options?: TableOptions) => TableDef<T>;
368
+ type DirectColumnKeys<T extends TableDef> = Exclude<keyof T["columns"] & string, keyof T | "$">;
369
+ type TableRef$1<T extends TableDef> = T & {
370
+ [K in DirectColumnKeys<T>]: T["columns"][K];
371
+ } & {
372
+ /**
373
+ * Escape hatch for collisions:
374
+ * - tref.name => table name (string)
375
+ * - tref.$.name => column def for "name"
376
+ */
377
+ $: T["columns"];
378
+ };
379
+ /**
380
+ * Public API: opt-in ergonomic table reference.
381
+ * Usage:
382
+ * const t = tableRef(todos);
383
+ * qb.where(eq(t.done, false)).orderBy(t.id, "ASC");
384
+ * Collisions:
385
+ * t.name is the table name (real field)
386
+ * t.$.name is the "name" column (escape hatch)
387
+ */
388
+ declare const tableRef: <T extends TableDef>(table: T) => TableRef$1<T>;
368
389
 
369
390
  /**
370
391
  * Resolves a relation definition to its target table type.
@@ -607,6 +628,7 @@ interface ScalarSubqueryNode {
607
628
  /** Optional alias for the subquery result */
608
629
  alias?: string;
609
630
  }
631
+ type InExpressionRight = OperandNode[] | ScalarSubqueryNode;
610
632
  /**
611
633
  * AST node representing a CASE expression
612
634
  */
@@ -700,7 +722,7 @@ interface InExpressionNode {
700
722
  /** IN/NOT IN operator */
701
723
  operator: 'IN' | 'NOT IN';
702
724
  /** Values to check against */
703
- right: OperandNode[];
725
+ right: InExpressionRight;
704
726
  }
705
727
  /**
706
728
  * AST node representing an EXISTS/NOT EXISTS expression
@@ -740,6 +762,9 @@ type ValueOperandInput = OperandNode | LiteralValue;
740
762
  */
741
763
  declare const valueToOperand: (value: ValueOperandInput) => OperandNode;
742
764
  declare const isValueOperandInput: (value: unknown) => value is ValueOperandInput;
765
+ type SelectQueryInput = SelectQueryNode | {
766
+ getAST(): SelectQueryNode;
767
+ };
743
768
  declare const columnOperand: (col: ColumnRef | ColumnNode) => ColumnNode;
744
769
  /**
745
770
  * Marks a column reference as an outer-scope reference for correlated subqueries.
@@ -841,6 +866,8 @@ declare const inList: (left: OperandNode | ColumnRef, values: (string | number |
841
866
  * @returns NOT IN expression node
842
867
  */
843
868
  declare const notInList: (left: OperandNode | ColumnRef, values: (string | number | LiteralNode)[]) => InExpressionNode;
869
+ declare const inSubquery: (left: OperandNode | ColumnRef, subquery: SelectQueryInput) => InExpressionNode;
870
+ declare const notInSubquery: (left: OperandNode | ColumnRef, subquery: SelectQueryInput) => InExpressionNode;
844
871
  /**
845
872
  * Creates a BETWEEN expression (value BETWEEN lower AND upper)
846
873
  * @param left - Operand to check
@@ -1200,14 +1227,25 @@ interface SelectQueryNode {
1200
1227
  /** Optional set operations chaining this query with others */
1201
1228
  setOps?: SetOperationNode[];
1202
1229
  }
1230
+ interface InsertValuesSourceNode {
1231
+ type: 'InsertValues';
1232
+ /** Rows of values for INSERT rows */
1233
+ rows: OperandNode[][];
1234
+ }
1235
+ interface InsertSelectSourceNode {
1236
+ type: 'InsertSelect';
1237
+ /** SELECT query providing rows */
1238
+ query: SelectQueryNode;
1239
+ }
1240
+ type InsertSourceNode = InsertValuesSourceNode | InsertSelectSourceNode;
1203
1241
  interface InsertQueryNode {
1204
1242
  type: 'InsertQuery';
1205
1243
  /** Target table */
1206
1244
  into: TableNode;
1207
1245
  /** Column order for inserted values */
1208
1246
  columns: ColumnNode[];
1209
- /** Rows of values to insert */
1210
- values: OperandNode[][];
1247
+ /** Source of inserted rows (either literal values or a SELECT query) */
1248
+ source: InsertSourceNode;
1211
1249
  /** Optional RETURNING clause */
1212
1250
  returning?: ColumnNode[];
1213
1251
  }
@@ -1221,6 +1259,10 @@ interface UpdateQueryNode {
1221
1259
  type: 'UpdateQuery';
1222
1260
  /** Table being updated */
1223
1261
  table: TableNode;
1262
+ /** Optional FROM clause for multi-table updates */
1263
+ from?: TableSourceNode;
1264
+ /** Optional joins applied to the FROM/USING tables */
1265
+ joins?: JoinNode[];
1224
1266
  /** Assignments for SET clause */
1225
1267
  set: UpdateAssignmentNode[];
1226
1268
  /** Optional WHERE clause */
@@ -1232,6 +1274,10 @@ interface DeleteQueryNode {
1232
1274
  type: 'DeleteQuery';
1233
1275
  /** Table to delete from */
1234
1276
  from: TableNode;
1277
+ /** Optional USING clause for multi-table deletes */
1278
+ using?: TableSourceNode;
1279
+ /** Optional joins applied to the USING clause */
1280
+ joins?: JoinNode[];
1235
1281
  /** Optional WHERE clause */
1236
1282
  where?: ExpressionNode;
1237
1283
  /** Optional RETURNING clause */
@@ -1982,10 +2028,17 @@ type QueryResult = {
1982
2028
  values: unknown[][];
1983
2029
  };
1984
2030
  interface DbExecutor {
2031
+ /** Capability flags so the runtime can make correct decisions without relying on optional methods. */
2032
+ readonly capabilities: {
2033
+ /** True if begin/commit/rollback are real and should be used to provide atomicity. */
2034
+ transactions: boolean;
2035
+ };
1985
2036
  executeSql(sql: string, params?: unknown[]): Promise<QueryResult[]>;
1986
- beginTransaction?(): Promise<void>;
1987
- commitTransaction?(): Promise<void>;
1988
- rollbackTransaction?(): Promise<void>;
2037
+ beginTransaction(): Promise<void>;
2038
+ commitTransaction(): Promise<void>;
2039
+ rollbackTransaction(): Promise<void>;
2040
+ /** Release any underlying resources (connections, pool leases, etc). Must be idempotent. */
2041
+ dispose(): Promise<void>;
1989
2042
  }
1990
2043
  /**
1991
2044
  * Convert an array of row objects into a QueryResult.
@@ -1996,17 +2049,20 @@ declare function rowsToQueryResult(rows: Array<Record<string, unknown>>): QueryR
1996
2049
  */
1997
2050
  interface SimpleQueryRunner {
1998
2051
  query(sql: string, params?: unknown[]): Promise<Array<Record<string, unknown>>>;
2052
+ /** Optional: used to support real transactions. */
1999
2053
  beginTransaction?(): Promise<void>;
2000
2054
  commitTransaction?(): Promise<void>;
2001
2055
  rollbackTransaction?(): Promise<void>;
2056
+ /** Optional: release resources (connection close, pool lease release, etc). */
2057
+ dispose?(): Promise<void>;
2002
2058
  }
2003
2059
  /**
2004
2060
  * Generic factory: turn any SimpleQueryRunner into a DbExecutor.
2005
2061
  */
2006
2062
  declare function createExecutorFromQueryRunner(runner: SimpleQueryRunner): DbExecutor;
2007
2063
 
2008
- type EntityConstructor = new (...args: any[]) => any;
2009
- type EntityOrTableTarget = EntityConstructor | TableDef;
2064
+ type EntityConstructor<T = object> = new (...args: any[]) => T;
2065
+ type EntityOrTableTarget = EntityConstructor<any> | TableDef;
2010
2066
  type EntityOrTableTargetResolver = EntityOrTableTarget | (() => EntityOrTableTarget);
2011
2067
 
2012
2068
  /**
@@ -2133,30 +2189,74 @@ declare class InterceptorPipeline {
2133
2189
  run(ctx: QueryContext, executor: DbExecutor): Promise<QueryResult[]>;
2134
2190
  }
2135
2191
 
2192
+ /**
2193
+ * Options for creating an ORM instance.
2194
+ * @template E - The domain event type
2195
+ */
2136
2196
  interface OrmOptions<E extends DomainEvent = OrmDomainEvent> {
2197
+ /** The database dialect */
2137
2198
  dialect: Dialect;
2199
+ /** The database executor factory */
2138
2200
  executorFactory: DbExecutorFactory;
2201
+ /** Optional interceptors pipeline */
2139
2202
  interceptors?: InterceptorPipeline;
2203
+ /** Optional naming strategy */
2140
2204
  namingStrategy?: NamingStrategy;
2141
2205
  }
2206
+ /**
2207
+ * Database executor factory interface.
2208
+ */
2142
2209
  interface DbExecutorFactory {
2143
- createExecutor(options?: {
2144
- tx?: ExternalTransaction;
2145
- }): DbExecutor;
2210
+ /**
2211
+ * Creates a database executor.
2212
+ * @returns The database executor
2213
+ */
2214
+ createExecutor(): DbExecutor;
2215
+ /**
2216
+ * Creates a transactional database executor.
2217
+ * @returns The transactional database executor
2218
+ */
2146
2219
  createTransactionalExecutor(): DbExecutor;
2220
+ /**
2221
+ * Disposes any underlying resources (connection pools, background timers, etc).
2222
+ */
2223
+ dispose(): Promise<void>;
2147
2224
  }
2148
- interface ExternalTransaction {
2149
- }
2225
+ /**
2226
+ * ORM (Object-Relational Mapping) main class.
2227
+ * @template E - The domain event type
2228
+ */
2150
2229
  declare class Orm<E extends DomainEvent = OrmDomainEvent> {
2230
+ /** The database dialect */
2151
2231
  readonly dialect: Dialect;
2232
+ /** The interceptors pipeline */
2152
2233
  readonly interceptors: InterceptorPipeline;
2234
+ /** The naming strategy */
2153
2235
  readonly namingStrategy: NamingStrategy;
2154
2236
  private readonly executorFactory;
2237
+ /**
2238
+ * Creates a new ORM instance.
2239
+ * @param opts - ORM options
2240
+ */
2155
2241
  constructor(opts: OrmOptions<E>);
2156
- createSession(options?: {
2157
- tx?: ExternalTransaction;
2158
- }): OrmSession<E>;
2242
+ /**
2243
+ * Creates a new ORM session.
2244
+ * @param options - Optional session options
2245
+ * @returns The ORM session
2246
+ */
2247
+ createSession(): OrmSession<E>;
2248
+ /**
2249
+ * Executes a function within a transaction.
2250
+ * @template T - The return type
2251
+ * @param fn - The function to execute
2252
+ * @returns The result of the function
2253
+ * @throws If the transaction fails
2254
+ */
2159
2255
  transaction<T>(fn: (session: OrmSession<E>) => Promise<T>): Promise<T>;
2256
+ /**
2257
+ * Shuts down the ORM and releases underlying resources (pools, timers).
2258
+ */
2259
+ dispose(): Promise<void>;
2160
2260
  }
2161
2261
 
2162
2262
  declare class IdentityMap {
@@ -2170,75 +2270,327 @@ declare class IdentityMap {
2170
2270
  private toIdentityKey;
2171
2271
  }
2172
2272
 
2273
+ /**
2274
+ * Unit of Work pattern implementation for tracking entity changes.
2275
+ */
2173
2276
  declare class UnitOfWork {
2174
2277
  private readonly dialect;
2175
2278
  private readonly executor;
2176
2279
  private readonly identityMap;
2177
2280
  private readonly hookContext;
2178
2281
  private readonly trackedEntities;
2282
+ /**
2283
+ * Creates a new UnitOfWork instance.
2284
+ * @param dialect - The database dialect
2285
+ * @param executor - The database executor
2286
+ * @param identityMap - The identity map
2287
+ * @param hookContext - Function to get the hook context
2288
+ */
2179
2289
  constructor(dialect: Dialect, executor: DbExecutor, identityMap: IdentityMap, hookContext: () => unknown);
2290
+ /**
2291
+ * Gets the identity buckets map.
2292
+ */
2180
2293
  get identityBuckets(): Map<string, Map<string, TrackedEntity>>;
2294
+ /**
2295
+ * Gets all tracked entities.
2296
+ * @returns Array of tracked entities
2297
+ */
2181
2298
  getTracked(): TrackedEntity[];
2299
+ /**
2300
+ * Gets an entity by table and primary key.
2301
+ * @param table - The table definition
2302
+ * @param pk - The primary key value
2303
+ * @returns The entity or undefined if not found
2304
+ */
2182
2305
  getEntity(table: TableDef, pk: string | number): any | undefined;
2306
+ /**
2307
+ * Gets all tracked entities for a specific table.
2308
+ * @param table - The table definition
2309
+ * @returns Array of tracked entities
2310
+ */
2183
2311
  getEntitiesForTable(table: TableDef): TrackedEntity[];
2312
+ /**
2313
+ * Finds a tracked entity.
2314
+ * @param entity - The entity to find
2315
+ * @returns The tracked entity or undefined if not found
2316
+ */
2184
2317
  findTracked(entity: any): TrackedEntity | undefined;
2318
+ /**
2319
+ * Sets an entity in the identity map.
2320
+ * @param table - The table definition
2321
+ * @param pk - The primary key value
2322
+ * @param entity - The entity instance
2323
+ */
2185
2324
  setEntity(table: TableDef, pk: string | number, entity: any): void;
2325
+ /**
2326
+ * Tracks a new entity.
2327
+ * @param table - The table definition
2328
+ * @param entity - The entity instance
2329
+ * @param pk - Optional primary key value
2330
+ */
2186
2331
  trackNew(table: TableDef, entity: any, pk?: string | number): void;
2332
+ /**
2333
+ * Tracks a managed entity.
2334
+ * @param table - The table definition
2335
+ * @param pk - The primary key value
2336
+ * @param entity - The entity instance
2337
+ */
2187
2338
  trackManaged(table: TableDef, pk: string | number, entity: any): void;
2339
+ /**
2340
+ * Marks an entity as dirty (modified).
2341
+ * @param entity - The entity to mark as dirty
2342
+ */
2188
2343
  markDirty(entity: any): void;
2344
+ /**
2345
+ * Marks an entity as removed.
2346
+ * @param entity - The entity to mark as removed
2347
+ */
2189
2348
  markRemoved(entity: any): void;
2349
+ /**
2350
+ * Flushes pending changes to the database.
2351
+ */
2190
2352
  flush(): Promise<void>;
2353
+ /**
2354
+ * Resets the unit of work by clearing all tracked entities and identity map.
2355
+ */
2191
2356
  reset(): void;
2357
+ /**
2358
+ * Flushes an insert operation for a new entity.
2359
+ * @param tracked - The tracked entity to insert
2360
+ */
2192
2361
  private flushInsert;
2362
+ /**
2363
+ * Flushes an update operation for a modified entity.
2364
+ * @param tracked - The tracked entity to update
2365
+ */
2193
2366
  private flushUpdate;
2367
+ /**
2368
+ * Flushes a delete operation for a removed entity.
2369
+ * @param tracked - The tracked entity to delete
2370
+ */
2194
2371
  private flushDelete;
2372
+ /**
2373
+ * Runs a table hook if defined.
2374
+ * @param hook - The hook function
2375
+ * @param tracked - The tracked entity
2376
+ */
2195
2377
  private runHook;
2378
+ /**
2379
+ * Computes changes between current entity state and original snapshot.
2380
+ * @param tracked - The tracked entity
2381
+ * @returns Object with changed column values
2382
+ */
2196
2383
  private computeChanges;
2384
+ /**
2385
+ * Extracts column values from an entity.
2386
+ * @param table - The table definition
2387
+ * @param entity - The entity instance
2388
+ * @returns Object with column values
2389
+ */
2197
2390
  private extractColumns;
2391
+ /**
2392
+ * Executes a compiled query.
2393
+ * @param compiled - The compiled query
2394
+ * @returns Query results
2395
+ */
2198
2396
  private executeCompiled;
2397
+ /**
2398
+ * Gets columns for RETURNING clause.
2399
+ * @param table - The table definition
2400
+ * @returns Array of column nodes
2401
+ */
2199
2402
  private getReturningColumns;
2403
+ /**
2404
+ * Applies RETURNING clause results to the tracked entity.
2405
+ * @param tracked - The tracked entity
2406
+ * @param results - Query results
2407
+ */
2200
2408
  private applyReturningResults;
2409
+ /**
2410
+ * Normalizes a column name by removing quotes and table prefixes.
2411
+ * @param column - The column name to normalize
2412
+ * @returns Normalized column name
2413
+ */
2201
2414
  private normalizeColumnName;
2415
+ /**
2416
+ * Registers an entity in the identity map.
2417
+ * @param tracked - The tracked entity to register
2418
+ */
2202
2419
  private registerIdentity;
2420
+ /**
2421
+ * Creates a snapshot of an entity's current state.
2422
+ * @param table - The table definition
2423
+ * @param entity - The entity instance
2424
+ * @returns Object with entity state
2425
+ */
2203
2426
  private createSnapshot;
2427
+ /**
2428
+ * Gets the primary key value from a tracked entity.
2429
+ * @param tracked - The tracked entity
2430
+ * @returns Primary key value or null
2431
+ */
2204
2432
  private getPrimaryKeyValue;
2205
2433
  }
2206
2434
 
2435
+ /**
2436
+ * Extracts domain events of a specific type.
2437
+ * @template E - The domain event type
2438
+ * @template TType - The specific event type
2439
+ */
2207
2440
  type EventOfType<E extends DomainEvent, TType extends E['type']> = Extract<E, {
2208
2441
  type: TType;
2209
2442
  }>;
2443
+ /**
2444
+ * Domain event handler function.
2445
+ * @template E - The domain event type
2446
+ * @template Context - The context type
2447
+ * @param event - The domain event
2448
+ * @param ctx - The context
2449
+ */
2210
2450
  type DomainEventHandler<E extends DomainEvent, Context> = (event: E, ctx: Context) => Promise<void> | void;
2451
+ /**
2452
+ * Initial handlers for domain events.
2453
+ * @template E - The domain event type
2454
+ * @template Context - The context type
2455
+ */
2211
2456
  type InitialHandlers<E extends DomainEvent, Context> = {
2212
2457
  [K in E['type']]?: DomainEventHandler<EventOfType<E, K>, Context>[];
2213
2458
  };
2459
+ /**
2460
+ * Domain event bus for managing and dispatching domain events.
2461
+ * @template E - The domain event type
2462
+ * @template Context - The context type
2463
+ */
2214
2464
  declare class DomainEventBus<E extends DomainEvent, Context> {
2215
2465
  private readonly handlers;
2466
+ /**
2467
+ * Creates a new DomainEventBus instance.
2468
+ * @param initialHandlers - Optional initial event handlers
2469
+ */
2216
2470
  constructor(initialHandlers?: InitialHandlers<E, Context>);
2471
+ /**
2472
+ * Registers an event handler for a specific event type.
2473
+ * @template TType - The event type
2474
+ * @param type - The event type
2475
+ * @param handler - The event handler
2476
+ */
2217
2477
  on<TType extends E['type']>(type: TType, handler: DomainEventHandler<EventOfType<E, TType>, Context>): void;
2478
+ /**
2479
+ * Registers an event handler for a specific event type (alias for on).
2480
+ * @template TType - The event type
2481
+ * @param type - The event type
2482
+ * @param handler - The event handler
2483
+ */
2218
2484
  register<TType extends E['type']>(type: TType, handler: DomainEventHandler<EventOfType<E, TType>, Context>): void;
2485
+ /**
2486
+ * Dispatches domain events for tracked entities.
2487
+ * @param trackedEntities - Iterable of tracked entities
2488
+ * @param ctx - The context to pass to handlers
2489
+ */
2219
2490
  dispatch(trackedEntities: Iterable<TrackedEntity>, ctx: Context): Promise<void>;
2220
2491
  }
2492
+ /**
2493
+ * Adds a domain event to an entity.
2494
+ * @template E - The domain event type
2495
+ * @param entity - The entity to add the event to
2496
+ * @param event - The domain event to add
2497
+ */
2221
2498
  declare const addDomainEvent: <E extends DomainEvent>(entity: HasDomainEvents<E>, event: E) => void;
2222
2499
 
2500
+ /**
2501
+ * Processes relation changes for entity relationships.
2502
+ */
2223
2503
  declare class RelationChangeProcessor {
2224
2504
  private readonly unitOfWork;
2225
2505
  private readonly dialect;
2226
2506
  private readonly executor;
2227
2507
  private readonly relationChanges;
2508
+ /**
2509
+ * Creates a new RelationChangeProcessor instance.
2510
+ * @param unitOfWork - The unit of work instance
2511
+ * @param dialect - The database dialect
2512
+ * @param executor - The database executor
2513
+ */
2228
2514
  constructor(unitOfWork: UnitOfWork, dialect: Dialect, executor: DbExecutor);
2515
+ /**
2516
+ * Registers a relation change for processing.
2517
+ * @param entry - The relation change entry
2518
+ */
2229
2519
  registerChange(entry: RelationChangeEntry): void;
2520
+ /**
2521
+ * Resets the relation change processor by clearing all pending changes.
2522
+ */
2230
2523
  reset(): void;
2524
+ /**
2525
+ * Processes all pending relation changes.
2526
+ */
2231
2527
  process(): Promise<void>;
2528
+ /**
2529
+ * Handles changes for has-many relations.
2530
+ * @param entry - The relation change entry
2531
+ */
2232
2532
  private handleHasManyChange;
2533
+ /**
2534
+ * Handles changes for has-one relations.
2535
+ * @param entry - The relation change entry
2536
+ */
2233
2537
  private handleHasOneChange;
2538
+ /**
2539
+ * Handles changes for belongs-to relations.
2540
+ * @param _entry - The relation change entry (reserved for future use)
2541
+ */
2234
2542
  private handleBelongsToChange;
2543
+ /**
2544
+ * Handles changes for belongs-to-many relations.
2545
+ * @param entry - The relation change entry
2546
+ */
2235
2547
  private handleBelongsToManyChange;
2548
+ /**
2549
+ * Assigns a foreign key for has-many relations.
2550
+ * @param child - The child entity
2551
+ * @param relation - The has-many relation
2552
+ * @param rootValue - The root entity's primary key value
2553
+ */
2236
2554
  private assignHasManyForeignKey;
2555
+ /**
2556
+ * Detaches a child entity from has-many relations.
2557
+ * @param child - The child entity
2558
+ * @param relation - The has-many relation
2559
+ */
2237
2560
  private detachHasManyChild;
2561
+ /**
2562
+ * Assigns a foreign key for has-one relations.
2563
+ * @param child - The child entity
2564
+ * @param relation - The has-one relation
2565
+ * @param rootValue - The root entity's primary key value
2566
+ */
2238
2567
  private assignHasOneForeignKey;
2568
+ /**
2569
+ * Detaches a child entity from has-one relations.
2570
+ * @param child - The child entity
2571
+ * @param relation - The has-one relation
2572
+ */
2239
2573
  private detachHasOneChild;
2574
+ /**
2575
+ * Inserts a pivot row for belongs-to-many relations.
2576
+ * @param relation - The belongs-to-many relation
2577
+ * @param rootId - The root entity's primary key value
2578
+ * @param targetId - The target entity's primary key value
2579
+ */
2240
2580
  private insertPivotRow;
2581
+ /**
2582
+ * Deletes a pivot row for belongs-to-many relations.
2583
+ * @param relation - The belongs-to-many relation
2584
+ * @param rootId - The root entity's primary key value
2585
+ * @param targetId - The target entity's primary key value
2586
+ */
2241
2587
  private deletePivotRow;
2588
+ /**
2589
+ * Resolves the primary key value from an entity.
2590
+ * @param entity - The entity
2591
+ * @param table - The table definition
2592
+ * @returns The primary key value or null
2593
+ */
2242
2594
  private resolvePrimaryKeyValue;
2243
2595
  }
2244
2596
 
@@ -2297,52 +2649,226 @@ interface HydrationContext<E extends DomainEvent = AnyDomainEvent> {
2297
2649
  entityContext: EntityContext;
2298
2650
  }
2299
2651
 
2652
+ interface SaveGraphOptions {
2653
+ /** Remove existing collection members that are not present in the payload */
2654
+ pruneMissing?: boolean;
2655
+ }
2656
+
2657
+ /**
2658
+ * Interface for ORM interceptors that allow hooking into the flush lifecycle.
2659
+ */
2300
2660
  interface OrmInterceptor {
2661
+ /**
2662
+ * Called before the flush operation begins.
2663
+ * @param ctx - The entity context
2664
+ */
2301
2665
  beforeFlush?(ctx: EntityContext): Promise<void> | void;
2666
+ /**
2667
+ * Called after the flush operation completes.
2668
+ * @param ctx - The entity context
2669
+ */
2302
2670
  afterFlush?(ctx: EntityContext): Promise<void> | void;
2303
2671
  }
2672
+ /**
2673
+ * Options for creating an OrmSession instance.
2674
+ * @template E - The domain event type
2675
+ */
2304
2676
  interface OrmSessionOptions<E extends DomainEvent = OrmDomainEvent> {
2677
+ /** The ORM instance */
2305
2678
  orm: Orm<E>;
2679
+ /** The database executor */
2306
2680
  executor: DbExecutor;
2681
+ /** Optional query logger for debugging */
2307
2682
  queryLogger?: QueryLogger;
2683
+ /** Optional interceptors for flush lifecycle hooks */
2308
2684
  interceptors?: OrmInterceptor[];
2685
+ /** Optional domain event handlers */
2309
2686
  domainEventHandlers?: InitialHandlers<E, OrmSession<E>>;
2310
2687
  }
2688
+ /**
2689
+ * ORM Session that manages entity lifecycle, identity mapping, and database operations.
2690
+ * @template E - The domain event type
2691
+ */
2311
2692
  declare class OrmSession<E extends DomainEvent = OrmDomainEvent> implements EntityContext {
2693
+ /** The ORM instance */
2312
2694
  readonly orm: Orm<E>;
2695
+ /** The database executor */
2313
2696
  readonly executor: DbExecutor;
2697
+ /** The identity map for tracking entity instances */
2314
2698
  readonly identityMap: IdentityMap;
2699
+ /** The unit of work for tracking entity changes */
2315
2700
  readonly unitOfWork: UnitOfWork;
2701
+ /** The domain event bus */
2316
2702
  readonly domainEvents: DomainEventBus<E, OrmSession<E>>;
2703
+ /** The relation change processor */
2317
2704
  readonly relationChanges: RelationChangeProcessor;
2318
2705
  private readonly interceptors;
2706
+ /**
2707
+ * Creates a new OrmSession instance.
2708
+ * @param opts - Session options
2709
+ */
2319
2710
  constructor(opts: OrmSessionOptions<E>);
2711
+ /**
2712
+ * Releases resources associated with this session (executor/pool leases) and resets tracking.
2713
+ * Must be safe to call multiple times.
2714
+ */
2715
+ dispose(): Promise<void>;
2716
+ /**
2717
+ * Gets the database dialect.
2718
+ */
2320
2719
  get dialect(): Dialect;
2720
+ /**
2721
+ * Gets the identity buckets map.
2722
+ */
2321
2723
  get identityBuckets(): Map<string, Map<string, TrackedEntity>>;
2724
+ /**
2725
+ * Gets all tracked entities.
2726
+ */
2322
2727
  get tracked(): TrackedEntity[];
2728
+ /**
2729
+ * Gets an entity by table and primary key.
2730
+ * @param table - The table definition
2731
+ * @param pk - The primary key value
2732
+ * @returns The entity or undefined if not found
2733
+ */
2323
2734
  getEntity(table: TableDef, pk: any): any | undefined;
2735
+ /**
2736
+ * Sets an entity in the identity map.
2737
+ * @param table - The table definition
2738
+ * @param pk - The primary key value
2739
+ * @param entity - The entity instance
2740
+ */
2324
2741
  setEntity(table: TableDef, pk: any, entity: any): void;
2742
+ /**
2743
+ * Tracks a new entity.
2744
+ * @param table - The table definition
2745
+ * @param entity - The entity instance
2746
+ * @param pk - Optional primary key value
2747
+ */
2325
2748
  trackNew(table: TableDef, entity: any, pk?: any): void;
2749
+ /**
2750
+ * Tracks a managed entity.
2751
+ * @param table - The table definition
2752
+ * @param pk - The primary key value
2753
+ * @param entity - The entity instance
2754
+ */
2326
2755
  trackManaged(table: TableDef, pk: any, entity: any): void;
2756
+ /**
2757
+ * Marks an entity as dirty (modified).
2758
+ * @param entity - The entity to mark as dirty
2759
+ */
2327
2760
  markDirty(entity: any): void;
2761
+ /**
2762
+ * Marks an entity as removed.
2763
+ * @param entity - The entity to mark as removed
2764
+ */
2328
2765
  markRemoved(entity: any): void;
2766
+ /**
2767
+ * Registers a relation change.
2768
+ * @param root - The root entity
2769
+ * @param relationKey - The relation key
2770
+ * @param rootTable - The root table definition
2771
+ * @param relationName - The relation name
2772
+ * @param relation - The relation definition
2773
+ * @param change - The relation change
2774
+ */
2329
2775
  registerRelationChange: (root: any, relationKey: RelationKey, rootTable: TableDef, relationName: string, relation: RelationDef, change: RelationChange<any>) => void;
2776
+ /**
2777
+ * Gets all tracked entities for a specific table.
2778
+ * @param table - The table definition
2779
+ * @returns Array of tracked entities
2780
+ */
2330
2781
  getEntitiesForTable(table: TableDef): TrackedEntity[];
2782
+ /**
2783
+ * Registers an interceptor for flush lifecycle hooks.
2784
+ * @param interceptor - The interceptor to register
2785
+ */
2331
2786
  registerInterceptor(interceptor: OrmInterceptor): void;
2787
+ /**
2788
+ * Registers a domain event handler.
2789
+ * @param type - The event type
2790
+ * @param handler - The event handler
2791
+ */
2332
2792
  registerDomainEventHandler<TType extends E['type']>(type: TType, handler: DomainEventHandler<Extract<E, {
2333
2793
  type: TType;
2334
2794
  }>, OrmSession<E>>): void;
2335
- find<TTable extends TableDef>(entityClass: EntityConstructor, id: any): Promise<EntityInstance<TTable> | null>;
2795
+ /**
2796
+ * Finds an entity by its primary key.
2797
+ * @template TCtor - The entity constructor type
2798
+ * @param entityClass - The entity constructor
2799
+ * @param id - The primary key value
2800
+ * @returns The entity instance or null if not found
2801
+ * @throws If entity metadata is not bootstrapped or table has no primary key
2802
+ */
2803
+ find<TCtor extends EntityConstructor<any>>(entityClass: TCtor, id: any): Promise<InstanceType<TCtor> | null>;
2804
+ /**
2805
+ * Finds a single entity using a query builder.
2806
+ * @template TTable - The table type
2807
+ * @param qb - The query builder
2808
+ * @returns The first entity instance or null if not found
2809
+ */
2336
2810
  findOne<TTable extends TableDef>(qb: SelectQueryBuilder<any, TTable>): Promise<EntityInstance<TTable> | null>;
2811
+ /**
2812
+ * Finds multiple entities using a query builder.
2813
+ * @template TTable - The table type
2814
+ * @param qb - The query builder
2815
+ * @returns Array of entity instances
2816
+ */
2337
2817
  findMany<TTable extends TableDef>(qb: SelectQueryBuilder<any, TTable>): Promise<EntityInstance<TTable>[]>;
2818
+ /**
2819
+ * Saves an entity graph (root + nested relations) based on a DTO-like payload.
2820
+ * @param entityClass - Root entity constructor
2821
+ * @param payload - DTO payload containing column values and nested relations
2822
+ * @param options - Graph save options
2823
+ * @returns The root entity instance
2824
+ */
2825
+ saveGraph<TCtor extends EntityConstructor<any>>(entityClass: TCtor, payload: Record<string, any>, options?: SaveGraphOptions & {
2826
+ transactional?: boolean;
2827
+ }): Promise<InstanceType<TCtor>>;
2828
+ /**
2829
+ * Persists an entity (either inserts or updates).
2830
+ * @param entity - The entity to persist
2831
+ * @throws If entity metadata is not bootstrapped
2832
+ */
2338
2833
  persist(entity: object): Promise<void>;
2834
+ /**
2835
+ * Marks an entity for removal.
2836
+ * @param entity - The entity to remove
2837
+ */
2339
2838
  remove(entity: object): Promise<void>;
2839
+ /**
2840
+ * Flushes pending changes to the database.
2841
+ */
2340
2842
  flush(): Promise<void>;
2843
+ /**
2844
+ * Flushes pending changes with interceptors and relation processing.
2845
+ */
2341
2846
  private flushWithHooks;
2847
+ /**
2848
+ * Commits the current transaction.
2849
+ */
2342
2850
  commit(): Promise<void>;
2851
+ /**
2852
+ * Executes a function within a transaction.
2853
+ * @template T - The return type
2854
+ * @param fn - The function to execute
2855
+ * @returns The result of the function
2856
+ * @throws If the transaction fails
2857
+ */
2343
2858
  transaction<T>(fn: (session: OrmSession<E>) => Promise<T>): Promise<T>;
2859
+ /**
2860
+ * Rolls back the current transaction.
2861
+ */
2344
2862
  rollback(): Promise<void>;
2863
+ /**
2864
+ * Gets the execution context.
2865
+ * @returns The execution context
2866
+ */
2345
2867
  getExecutionContext(): ExecutionContext;
2868
+ /**
2869
+ * Gets the hydration context.
2870
+ * @returns The hydration context
2871
+ */
2346
2872
  getHydrationContext(): HydrationContext<E>;
2347
2873
  }
2348
2874
 
@@ -2804,7 +3330,12 @@ declare class InsertQueryState {
2804
3330
  readonly ast: InsertQueryNode;
2805
3331
  constructor(table: TableDef, ast?: InsertQueryNode);
2806
3332
  private clone;
3333
+ private ensureColumnsFromRow;
3334
+ private appendValues;
3335
+ private getTableColumns;
2807
3336
  withValues(rows: Record<string, unknown>[]): InsertQueryState;
3337
+ withColumns(columns: ColumnNode[]): InsertQueryState;
3338
+ withSelect(query: SelectQueryNode, columns: ColumnNode[]): InsertQueryState;
2808
3339
  withReturning(columns: ColumnNode[]): InsertQueryState;
2809
3340
  }
2810
3341
 
@@ -2818,7 +3349,11 @@ declare class InsertQueryBuilder<T> {
2818
3349
  constructor(table: TableDef, state?: InsertQueryState);
2819
3350
  private clone;
2820
3351
  values(rowOrRows: Record<string, unknown> | Record<string, unknown>[]): InsertQueryBuilder<T>;
3352
+ columns(...columns: (ColumnDef | ColumnNode)[]): InsertQueryBuilder<T>;
3353
+ fromSelect(query: SelectQueryNode | SelectQueryBuilder<any, TableDef<any>>, columns?: (ColumnDef | ColumnNode)[]): InsertQueryBuilder<T>;
2821
3354
  returning(...columns: (ColumnDef | ColumnNode)[]): InsertQueryBuilder<T>;
3355
+ private resolveColumnNodes;
3356
+ private resolveSelectQuery;
2822
3357
  compile(compiler: InsertCompiler): CompiledQuery;
2823
3358
  compile(dialect: InsertDialectInput): CompiledQuery;
2824
3359
  toSql(arg: InsertCompiler | InsertDialectInput): string;
@@ -2836,6 +3371,9 @@ declare class UpdateQueryState {
2836
3371
  withSet(values: Record<string, unknown>): UpdateQueryState;
2837
3372
  withWhere(expr: ExpressionNode): UpdateQueryState;
2838
3373
  withReturning(columns: ColumnNode[]): UpdateQueryState;
3374
+ withFrom(from: TableSourceNode): UpdateQueryState;
3375
+ withJoin(join: JoinNode): UpdateQueryState;
3376
+ withTableAlias(alias: string): UpdateQueryState;
2839
3377
  }
2840
3378
 
2841
3379
  type UpdateDialectInput = Dialect | DialectKey;
@@ -2847,9 +3385,14 @@ declare class UpdateQueryBuilder<T> {
2847
3385
  private readonly state;
2848
3386
  constructor(table: TableDef, state?: UpdateQueryState);
2849
3387
  private clone;
3388
+ as(alias: string): UpdateQueryBuilder<T>;
3389
+ from(source: TableDef | TableSourceNode): UpdateQueryBuilder<T>;
3390
+ join(table: TableDef | TableSourceNode | string, condition: ExpressionNode, kind?: JoinKind, relationName?: string): UpdateQueryBuilder<T>;
2850
3391
  set(values: Record<string, unknown>): UpdateQueryBuilder<T>;
2851
3392
  where(expr: ExpressionNode): UpdateQueryBuilder<T>;
2852
3393
  returning(...columns: (ColumnDef | ColumnNode)[]): UpdateQueryBuilder<T>;
3394
+ private resolveTableSource;
3395
+ private resolveJoinTarget;
2853
3396
  compile(compiler: UpdateCompiler): CompiledQuery;
2854
3397
  compile(dialect: UpdateDialectInput): CompiledQuery;
2855
3398
  toSql(arg: UpdateCompiler | UpdateDialectInput): string;
@@ -2866,6 +3409,9 @@ declare class DeleteQueryState {
2866
3409
  private clone;
2867
3410
  withWhere(expr: ExpressionNode): DeleteQueryState;
2868
3411
  withReturning(columns: ColumnNode[]): DeleteQueryState;
3412
+ withUsing(source: TableSourceNode): DeleteQueryState;
3413
+ withJoin(join: JoinNode): DeleteQueryState;
3414
+ withTableAlias(alias: string): DeleteQueryState;
2869
3415
  }
2870
3416
 
2871
3417
  type DeleteDialectInput = Dialect | DialectKey;
@@ -2878,7 +3424,12 @@ declare class DeleteQueryBuilder<T> {
2878
3424
  constructor(table: TableDef, state?: DeleteQueryState);
2879
3425
  private clone;
2880
3426
  where(expr: ExpressionNode): DeleteQueryBuilder<T>;
3427
+ as(alias: string): DeleteQueryBuilder<T>;
3428
+ using(source: TableDef | TableSourceNode): DeleteQueryBuilder<T>;
3429
+ join(table: TableDef | TableSourceNode | string, condition: ExpressionNode, kind?: JoinKind, relationName?: string): DeleteQueryBuilder<T>;
2881
3430
  returning(...columns: (ColumnDef | ColumnNode)[]): DeleteQueryBuilder<T>;
3431
+ private resolveTableSource;
3432
+ private resolveJoinTarget;
2882
3433
  compile(compiler: DeleteCompiler): CompiledQuery;
2883
3434
  compile(dialect: DeleteDialectInput): CompiledQuery;
2884
3435
  toSql(arg: DeleteCompiler | DeleteDialectInput): string;
@@ -2929,11 +3480,12 @@ declare abstract class SqlDialectBase extends Dialect {
2929
3480
  private compileSelectWithSetOps;
2930
3481
  protected compileInsertAst(ast: InsertQueryNode, ctx: CompilerContext): string;
2931
3482
  protected compileReturning(returning: ColumnNode[] | undefined, ctx: CompilerContext): string;
3483
+ private compileInsertSource;
2932
3484
  private compileInsertColumnList;
2933
- private compileInsertValues;
2934
3485
  private compileSelectCore;
2935
3486
  protected compileUpdateAst(ast: UpdateQueryNode, ctx: CompilerContext): string;
2936
3487
  private compileUpdateAssignments;
3488
+ protected compileQualifiedColumn(column: ColumnNode, table: TableNode): string;
2937
3489
  protected compileDeleteAst(ast: DeleteQueryNode, ctx: CompilerContext): string;
2938
3490
  protected formatReturningColumns(returning: ColumnNode[]): string;
2939
3491
  protected compileDistinct(ast: SelectQueryNode): string;
@@ -2945,7 +3497,15 @@ declare abstract class SqlDialectBase extends Dialect {
2945
3497
  protected compileTableName(table: {
2946
3498
  name: string;
2947
3499
  schema?: string;
3500
+ alias?: string;
3501
+ }): string;
3502
+ protected compileTableReference(table: {
3503
+ name: string;
3504
+ schema?: string;
3505
+ alias?: string;
2948
3506
  }): string;
3507
+ private compileUpdateFromClause;
3508
+ private compileDeleteUsingClause;
2949
3509
  protected compileHaving(ast: SelectQueryNode, ctx: CompilerContext): string;
2950
3510
  protected stripTrailingSemicolon(sql: string): string;
2951
3511
  protected wrapSetOperand(sql: string): string;
@@ -2979,7 +3539,7 @@ declare class MySqlDialect extends SqlDialectBase {
2979
3539
  /**
2980
3540
  * Microsoft SQL Server dialect implementation
2981
3541
  */
2982
- declare class SqlServerDialect extends Dialect {
3542
+ declare class SqlServerDialect extends SqlDialectBase {
2983
3543
  protected readonly dialect = "mssql";
2984
3544
  /**
2985
3545
  * Creates a new SqlServerDialect instance
@@ -3010,18 +3570,11 @@ declare class SqlServerDialect extends Dialect {
3010
3570
  * @returns SQL Server SQL string
3011
3571
  */
3012
3572
  protected compileSelectAst(ast: SelectQueryNode, ctx: CompilerContext): string;
3013
- protected compileInsertAst(ast: InsertQueryNode, ctx: CompilerContext): string;
3014
- protected compileUpdateAst(ast: UpdateQueryNode, ctx: CompilerContext): string;
3015
3573
  protected compileDeleteAst(ast: DeleteQueryNode, ctx: CompilerContext): string;
3016
- private compileSelectCore;
3574
+ private compileSelectCoreForMssql;
3017
3575
  private compileOrderBy;
3018
3576
  private compilePagination;
3019
- private renderOrderByNulls;
3020
- private renderOrderByCollation;
3021
- private compileTableSource;
3022
- private compileDerivedTable;
3023
3577
  private compileCtes;
3024
- private wrapSetOperand;
3025
3578
  }
3026
3579
 
3027
3580
  /**
@@ -3045,6 +3598,7 @@ declare class SqliteDialect extends SqlDialectBase {
3045
3598
  * @returns SQLite JSON path expression
3046
3599
  */
3047
3600
  protected compileJsonPath(node: JsonPathNode): string;
3601
+ protected compileQualifiedColumn(column: ColumnNode, _table: TableNode): string;
3048
3602
  protected compileReturning(returning: ColumnNode[] | undefined, ctx: CompilerContext): string;
3049
3603
  protected formatReturningColumns(returning: ColumnNode[]): string;
3050
3604
  supportsReturning(): boolean;
@@ -3671,7 +4225,27 @@ declare class TypeScriptGenerator implements ExpressionVisitor<string>, OperandV
3671
4225
  private mapOp;
3672
4226
  }
3673
4227
 
4228
+ /**
4229
+ * Creates an entity proxy with lazy loading capabilities.
4230
+ * @template TTable - The table type
4231
+ * @template TLazy - The lazy relation keys
4232
+ * @param ctx - The entity context
4233
+ * @param table - The table definition
4234
+ * @param row - The database row
4235
+ * @param lazyRelations - Optional lazy relations
4236
+ * @returns The entity instance
4237
+ */
3674
4238
  declare const createEntityProxy: <TTable extends TableDef, TLazy extends keyof RelationMap<TTable> = keyof RelationMap<TTable>>(ctx: EntityContext, table: TTable, row: Record<string, any>, lazyRelations?: TLazy[]) => EntityInstance<TTable>;
4239
+ /**
4240
+ * Creates an entity instance from a database row.
4241
+ * @template TTable - The table type
4242
+ * @template TResult - The result type
4243
+ * @param ctx - The entity context
4244
+ * @param table - The table definition
4245
+ * @param row - The database row
4246
+ * @param lazyRelations - Optional lazy relations
4247
+ * @returns The entity instance
4248
+ */
3675
4249
  declare const createEntityFromRow: <TTable extends TableDef, TResult extends EntityInstance<TTable> = EntityInstance<TTable>>(ctx: EntityContext, table: TTable, row: Record<string, any>, lazyRelations?: (keyof RelationMap<TTable>)[]) => TResult;
3676
4250
 
3677
4251
  type Rows$3 = Record<string, any>[];
@@ -3843,8 +4417,60 @@ declare function BelongsTo(options: BelongsToOptions): DualModePropertyDecorator
3843
4417
  declare function BelongsToMany(options: BelongsToManyOptions): DualModePropertyDecorator;
3844
4418
 
3845
4419
  declare const bootstrapEntities: () => TableDef[];
3846
- declare const getTableDefFromEntity: <TTable extends TableDef = TableDef>(ctor: EntityConstructor) => TTable | undefined;
3847
- declare const selectFromEntity: <TTable extends TableDef = TableDef>(ctor: EntityConstructor) => SelectQueryBuilder<any, TTable>;
4420
+ declare const getTableDefFromEntity: <TTable extends TableDef = TableDef>(ctor: EntityConstructor<any>) => TTable | undefined;
4421
+ declare const selectFromEntity: <TTable extends TableDef = TableDef>(ctor: EntityConstructor<any>) => SelectQueryBuilder<any, TTable>;
4422
+
4423
+ type PoolOptions = {
4424
+ /** Maximum number of live resources (idle + leased). */
4425
+ max: number;
4426
+ /** Minimum number of idle resources to keep warm (best-effort). */
4427
+ min?: number;
4428
+ /** How long an idle resource can sit before being destroyed. */
4429
+ idleTimeoutMillis?: number;
4430
+ /** How often to reap idle resources. Defaults to idleTimeoutMillis / 2 (min 1s). */
4431
+ reapIntervalMillis?: number;
4432
+ /** How long callers wait for a resource before acquire() rejects. */
4433
+ acquireTimeoutMillis?: number;
4434
+ };
4435
+ interface PoolAdapter<TResource> {
4436
+ create(): Promise<TResource>;
4437
+ destroy(resource: TResource): Promise<void>;
4438
+ validate?(resource: TResource): Promise<boolean>;
4439
+ }
4440
+ interface PoolLease<TResource> {
4441
+ readonly resource: TResource;
4442
+ /** Returns the resource to the pool. Idempotent. */
4443
+ release(): Promise<void>;
4444
+ /** Permanently removes the resource from the pool. Idempotent. */
4445
+ destroy(): Promise<void>;
4446
+ }
4447
+
4448
+ declare class Pool<TResource> {
4449
+ private readonly adapter;
4450
+ private readonly options;
4451
+ private destroyed;
4452
+ private creating;
4453
+ private leased;
4454
+ private readonly idle;
4455
+ private readonly waiters;
4456
+ private reapTimer;
4457
+ constructor(adapter: PoolAdapter<TResource>, options: PoolOptions);
4458
+ /**
4459
+ * Acquire a resource lease.
4460
+ * The returned lease MUST be released or destroyed.
4461
+ */
4462
+ acquire(): Promise<PoolLease<TResource>>;
4463
+ /** Destroy pool and all idle resources; waits for in-flight creations to settle. */
4464
+ destroy(): Promise<void>;
4465
+ private totalLive;
4466
+ private makeLease;
4467
+ private releaseResource;
4468
+ private destroyResource;
4469
+ private takeIdleValidated;
4470
+ private reapIdle;
4471
+ private warm;
4472
+ private trimToMinMax;
4473
+ }
3848
4474
 
3849
4475
  interface PostgresClientLike {
3850
4476
  query(text: string, params?: unknown[]): Promise<{
@@ -3917,4 +4543,24 @@ interface CreateTediousClientOptions {
3917
4543
  declare function createTediousMssqlClient(connection: TediousConnectionLike, { Request, TYPES }: TediousModule, options?: CreateTediousClientOptions): MssqlClientLike;
3918
4544
  declare function createTediousExecutor(connection: TediousConnectionLike, module: TediousModule, options?: CreateTediousClientOptions): DbExecutor;
3919
4545
 
3920
- export { type AliasRefNode, type AnyDomainEvent, type ArithmeticExpressionNode, AsyncLocalStorage, BelongsTo, BelongsToMany, type BelongsToManyOptions, type BelongsToManyRelation, type BelongsToOptions, type BelongsToReference, type BelongsToRelation, type BetweenExpressionNode, type BinaryExpressionNode, type CascadeMode, type CaseExpressionNode, 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 ExternalTransaction, 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 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, 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, type ScalarSubqueryNode, type SchemaChange, type SchemaChangeKind, type SchemaDiffOptions, type SchemaGenerateResult, type SchemaIntrospector, type SchemaPlan, SelectQueryBuilder, type SimpleQueryRunner, SqlServerDialect, type SqliteClientLike, SqliteDialect, type SynchronizeOptions, type TableDef, type TableHooks, type TableOptions, type 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, ceil, ceiling, char, charLength, clearExpressionDispatchers, clearOperandDispatchers, col, columnOperand, concat, concatWs, correlateBy, cos, cot, count, createColumn, createEntityFromRow, createEntityProxy, createExecutorFromQueryRunner, createLiteral, createMssqlExecutor, createMysqlExecutor, createPostgresExecutor, createQueryLoggingExecutor, createSqliteExecutor, createTediousExecutor, createTediousMssqlClient, currentDate, currentTime, dateAdd, dateDiff, dateFormat, dateSub, dateTrunc, day, dayOfWeek, defineTable, degrees, denseRank, diffSchema, div, endOfMonth, eq, esel, executeHydrated, executeHydratedWithContexts, exists, exp, extract, firstValue, floor, fromUnixTime, generateCreateTableSql, generateSchemaSql, getSchemaIntrospector, getTableDefFromEntity, groupConcat, gt, gte, hasMany, hasOne, hydrateRows, inList, instr, introspectSchema, isCaseExpressionNode, 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, notBetween, notExists, notInList, notLike, now, ntile, or, outerRef, pi, position, pow, power, radians, rand, random, rank, registerExpressionDispatcher, registerOperandDispatcher, registerSchemaIntrospector, renderColumnDefinition, repeat, replace, right, round, rowNumber, rowsToQueryResult, rpad, rtrim, sel, selectFromEntity, sign, sin, space, sqrt, sub, substr, sum, synchronizeSchema, tan, toColumnRef, toTableRef, trim, trunc, truncate, unixTimestamp, upper, utcNow, valueToOperand, visitExpression, visitOperand, weekOfYear, windowFunction, year };
4546
+ interface PooledConnectionAdapter<TConn> {
4547
+ query(conn: TConn, sql: string, params?: unknown[]): Promise<Array<Record<string, unknown>>>;
4548
+ beginTransaction(conn: TConn): Promise<void>;
4549
+ commitTransaction(conn: TConn): Promise<void>;
4550
+ rollbackTransaction(conn: TConn): Promise<void>;
4551
+ }
4552
+ type PooledExecutorFactoryOptions<TConn> = {
4553
+ pool: Pool<TConn>;
4554
+ adapter: PooledConnectionAdapter<TConn>;
4555
+ };
4556
+ /**
4557
+ * Creates a first-class DbExecutorFactory backed by MetalORM's Pool.
4558
+ *
4559
+ * Design goals:
4560
+ * - No leaks by default: pool leases are always released in `finally`.
4561
+ * - Correct transactions: one leased connection per transaction.
4562
+ * - Session-friendly: createExecutor() supports transactions without permanently leasing a connection.
4563
+ */
4564
+ declare function createPooledExecutorFactory<TConn>(opts: PooledExecutorFactoryOptions<TConn>): DbExecutorFactory;
4565
+
4566
+ 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 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, type ScalarSubqueryNode, type SchemaChange, type SchemaChangeKind, type SchemaDiffOptions, type SchemaGenerateResult, type SchemaIntrospector, type SchemaPlan, SelectQueryBuilder, type SelectQueryInput, type SimpleQueryRunner, SqlServerDialect, type SqliteClientLike, SqliteDialect, 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, ceil, ceiling, char, charLength, clearExpressionDispatchers, clearOperandDispatchers, col, columnOperand, concat, concatWs, correlateBy, cos, cot, count, createColumn, createEntityFromRow, createEntityProxy, createExecutorFromQueryRunner, createLiteral, createMssqlExecutor, createMysqlExecutor, createPooledExecutorFactory, createPostgresExecutor, createQueryLoggingExecutor, createSqliteExecutor, createTediousExecutor, createTediousMssqlClient, currentDate, currentTime, dateAdd, dateDiff, dateFormat, dateSub, dateTrunc, day, dayOfWeek, defineTable, degrees, denseRank, diffSchema, div, endOfMonth, eq, esel, executeHydrated, executeHydratedWithContexts, exists, exp, extract, firstValue, floor, fromUnixTime, generateCreateTableSql, generateSchemaSql, getSchemaIntrospector, getTableDefFromEntity, groupConcat, gt, gte, hasMany, hasOne, hydrateRows, inList, inSubquery, instr, introspectSchema, isCaseExpressionNode, 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, notBetween, notExists, notInList, notInSubquery, notLike, now, ntile, or, outerRef, pi, position, pow, power, radians, rand, random, rank, registerExpressionDispatcher, registerOperandDispatcher, registerSchemaIntrospector, renderColumnDefinition, 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 };