metal-orm 1.0.40 → 1.0.41

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 (42) hide show
  1. package/dist/index.cjs +1244 -122
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +655 -30
  4. package/dist/index.d.ts +655 -30
  5. package/dist/index.js +1240 -122
  6. package/dist/index.js.map +1 -1
  7. package/package.json +1 -1
  8. package/src/codegen/typescript.ts +6 -2
  9. package/src/core/ast/expression-builders.ts +25 -4
  10. package/src/core/ast/expression-nodes.ts +3 -1
  11. package/src/core/ast/query.ts +24 -2
  12. package/src/core/dialect/abstract.ts +6 -2
  13. package/src/core/dialect/base/join-compiler.ts +9 -12
  14. package/src/core/dialect/base/sql-dialect.ts +98 -17
  15. package/src/core/dialect/mssql/index.ts +30 -62
  16. package/src/core/dialect/sqlite/index.ts +39 -34
  17. package/src/core/execution/db-executor.ts +46 -6
  18. package/src/core/execution/executors/mssql-executor.ts +39 -22
  19. package/src/core/execution/executors/mysql-executor.ts +23 -6
  20. package/src/core/execution/executors/sqlite-executor.ts +29 -3
  21. package/src/core/execution/pooling/pool-types.ts +30 -0
  22. package/src/core/execution/pooling/pool.ts +268 -0
  23. package/src/decorators/bootstrap.ts +7 -7
  24. package/src/index.ts +6 -0
  25. package/src/orm/domain-event-bus.ts +49 -0
  26. package/src/orm/entity-metadata.ts +9 -9
  27. package/src/orm/entity.ts +58 -0
  28. package/src/orm/orm-session.ts +465 -270
  29. package/src/orm/orm.ts +61 -11
  30. package/src/orm/pooled-executor-factory.ts +131 -0
  31. package/src/orm/query-logger.ts +6 -12
  32. package/src/orm/relation-change-processor.ts +75 -0
  33. package/src/orm/relations/many-to-many.ts +4 -2
  34. package/src/orm/save-graph.ts +303 -0
  35. package/src/orm/transaction-runner.ts +3 -3
  36. package/src/orm/unit-of-work.ts +128 -0
  37. package/src/query-builder/delete-query-state.ts +67 -38
  38. package/src/query-builder/delete.ts +37 -1
  39. package/src/query-builder/insert-query-state.ts +131 -61
  40. package/src/query-builder/insert.ts +27 -1
  41. package/src/query-builder/update-query-state.ts +114 -77
  42. package/src/query-builder/update.ts +38 -1
package/dist/index.d.ts CHANGED
@@ -607,6 +607,7 @@ interface ScalarSubqueryNode {
607
607
  /** Optional alias for the subquery result */
608
608
  alias?: string;
609
609
  }
610
+ type InExpressionRight = OperandNode[] | ScalarSubqueryNode;
610
611
  /**
611
612
  * AST node representing a CASE expression
612
613
  */
@@ -700,7 +701,7 @@ interface InExpressionNode {
700
701
  /** IN/NOT IN operator */
701
702
  operator: 'IN' | 'NOT IN';
702
703
  /** Values to check against */
703
- right: OperandNode[];
704
+ right: InExpressionRight;
704
705
  }
705
706
  /**
706
707
  * AST node representing an EXISTS/NOT EXISTS expression
@@ -740,6 +741,9 @@ type ValueOperandInput = OperandNode | LiteralValue;
740
741
  */
741
742
  declare const valueToOperand: (value: ValueOperandInput) => OperandNode;
742
743
  declare const isValueOperandInput: (value: unknown) => value is ValueOperandInput;
744
+ type SelectQueryInput = SelectQueryNode | {
745
+ getAST(): SelectQueryNode;
746
+ };
743
747
  declare const columnOperand: (col: ColumnRef | ColumnNode) => ColumnNode;
744
748
  /**
745
749
  * Marks a column reference as an outer-scope reference for correlated subqueries.
@@ -841,6 +845,8 @@ declare const inList: (left: OperandNode | ColumnRef, values: (string | number |
841
845
  * @returns NOT IN expression node
842
846
  */
843
847
  declare const notInList: (left: OperandNode | ColumnRef, values: (string | number | LiteralNode)[]) => InExpressionNode;
848
+ declare const inSubquery: (left: OperandNode | ColumnRef, subquery: SelectQueryInput) => InExpressionNode;
849
+ declare const notInSubquery: (left: OperandNode | ColumnRef, subquery: SelectQueryInput) => InExpressionNode;
844
850
  /**
845
851
  * Creates a BETWEEN expression (value BETWEEN lower AND upper)
846
852
  * @param left - Operand to check
@@ -1200,14 +1206,25 @@ interface SelectQueryNode {
1200
1206
  /** Optional set operations chaining this query with others */
1201
1207
  setOps?: SetOperationNode[];
1202
1208
  }
1209
+ interface InsertValuesSourceNode {
1210
+ type: 'InsertValues';
1211
+ /** Rows of values for INSERT rows */
1212
+ rows: OperandNode[][];
1213
+ }
1214
+ interface InsertSelectSourceNode {
1215
+ type: 'InsertSelect';
1216
+ /** SELECT query providing rows */
1217
+ query: SelectQueryNode;
1218
+ }
1219
+ type InsertSourceNode = InsertValuesSourceNode | InsertSelectSourceNode;
1203
1220
  interface InsertQueryNode {
1204
1221
  type: 'InsertQuery';
1205
1222
  /** Target table */
1206
1223
  into: TableNode;
1207
1224
  /** Column order for inserted values */
1208
1225
  columns: ColumnNode[];
1209
- /** Rows of values to insert */
1210
- values: OperandNode[][];
1226
+ /** Source of inserted rows (either literal values or a SELECT query) */
1227
+ source: InsertSourceNode;
1211
1228
  /** Optional RETURNING clause */
1212
1229
  returning?: ColumnNode[];
1213
1230
  }
@@ -1221,6 +1238,10 @@ interface UpdateQueryNode {
1221
1238
  type: 'UpdateQuery';
1222
1239
  /** Table being updated */
1223
1240
  table: TableNode;
1241
+ /** Optional FROM clause for multi-table updates */
1242
+ from?: TableSourceNode;
1243
+ /** Optional joins applied to the FROM/USING tables */
1244
+ joins?: JoinNode[];
1224
1245
  /** Assignments for SET clause */
1225
1246
  set: UpdateAssignmentNode[];
1226
1247
  /** Optional WHERE clause */
@@ -1232,6 +1253,10 @@ interface DeleteQueryNode {
1232
1253
  type: 'DeleteQuery';
1233
1254
  /** Table to delete from */
1234
1255
  from: TableNode;
1256
+ /** Optional USING clause for multi-table deletes */
1257
+ using?: TableSourceNode;
1258
+ /** Optional joins applied to the USING clause */
1259
+ joins?: JoinNode[];
1235
1260
  /** Optional WHERE clause */
1236
1261
  where?: ExpressionNode;
1237
1262
  /** Optional RETURNING clause */
@@ -1982,10 +2007,17 @@ type QueryResult = {
1982
2007
  values: unknown[][];
1983
2008
  };
1984
2009
  interface DbExecutor {
2010
+ /** Capability flags so the runtime can make correct decisions without relying on optional methods. */
2011
+ readonly capabilities: {
2012
+ /** True if begin/commit/rollback are real and should be used to provide atomicity. */
2013
+ transactions: boolean;
2014
+ };
1985
2015
  executeSql(sql: string, params?: unknown[]): Promise<QueryResult[]>;
1986
- beginTransaction?(): Promise<void>;
1987
- commitTransaction?(): Promise<void>;
1988
- rollbackTransaction?(): Promise<void>;
2016
+ beginTransaction(): Promise<void>;
2017
+ commitTransaction(): Promise<void>;
2018
+ rollbackTransaction(): Promise<void>;
2019
+ /** Release any underlying resources (connections, pool leases, etc). Must be idempotent. */
2020
+ dispose(): Promise<void>;
1989
2021
  }
1990
2022
  /**
1991
2023
  * Convert an array of row objects into a QueryResult.
@@ -1996,17 +2028,20 @@ declare function rowsToQueryResult(rows: Array<Record<string, unknown>>): QueryR
1996
2028
  */
1997
2029
  interface SimpleQueryRunner {
1998
2030
  query(sql: string, params?: unknown[]): Promise<Array<Record<string, unknown>>>;
2031
+ /** Optional: used to support real transactions. */
1999
2032
  beginTransaction?(): Promise<void>;
2000
2033
  commitTransaction?(): Promise<void>;
2001
2034
  rollbackTransaction?(): Promise<void>;
2035
+ /** Optional: release resources (connection close, pool lease release, etc). */
2036
+ dispose?(): Promise<void>;
2002
2037
  }
2003
2038
  /**
2004
2039
  * Generic factory: turn any SimpleQueryRunner into a DbExecutor.
2005
2040
  */
2006
2041
  declare function createExecutorFromQueryRunner(runner: SimpleQueryRunner): DbExecutor;
2007
2042
 
2008
- type EntityConstructor = new (...args: any[]) => any;
2009
- type EntityOrTableTarget = EntityConstructor | TableDef;
2043
+ type EntityConstructor<T = object> = new (...args: any[]) => T;
2044
+ type EntityOrTableTarget = EntityConstructor<any> | TableDef;
2010
2045
  type EntityOrTableTargetResolver = EntityOrTableTarget | (() => EntityOrTableTarget);
2011
2046
 
2012
2047
  /**
@@ -2133,30 +2168,74 @@ declare class InterceptorPipeline {
2133
2168
  run(ctx: QueryContext, executor: DbExecutor): Promise<QueryResult[]>;
2134
2169
  }
2135
2170
 
2171
+ /**
2172
+ * Options for creating an ORM instance.
2173
+ * @template E - The domain event type
2174
+ */
2136
2175
  interface OrmOptions<E extends DomainEvent = OrmDomainEvent> {
2176
+ /** The database dialect */
2137
2177
  dialect: Dialect;
2178
+ /** The database executor factory */
2138
2179
  executorFactory: DbExecutorFactory;
2180
+ /** Optional interceptors pipeline */
2139
2181
  interceptors?: InterceptorPipeline;
2182
+ /** Optional naming strategy */
2140
2183
  namingStrategy?: NamingStrategy;
2141
2184
  }
2185
+ /**
2186
+ * Database executor factory interface.
2187
+ */
2142
2188
  interface DbExecutorFactory {
2143
- createExecutor(options?: {
2144
- tx?: ExternalTransaction;
2145
- }): DbExecutor;
2189
+ /**
2190
+ * Creates a database executor.
2191
+ * @returns The database executor
2192
+ */
2193
+ createExecutor(): DbExecutor;
2194
+ /**
2195
+ * Creates a transactional database executor.
2196
+ * @returns The transactional database executor
2197
+ */
2146
2198
  createTransactionalExecutor(): DbExecutor;
2199
+ /**
2200
+ * Disposes any underlying resources (connection pools, background timers, etc).
2201
+ */
2202
+ dispose(): Promise<void>;
2147
2203
  }
2148
- interface ExternalTransaction {
2149
- }
2204
+ /**
2205
+ * ORM (Object-Relational Mapping) main class.
2206
+ * @template E - The domain event type
2207
+ */
2150
2208
  declare class Orm<E extends DomainEvent = OrmDomainEvent> {
2209
+ /** The database dialect */
2151
2210
  readonly dialect: Dialect;
2211
+ /** The interceptors pipeline */
2152
2212
  readonly interceptors: InterceptorPipeline;
2213
+ /** The naming strategy */
2153
2214
  readonly namingStrategy: NamingStrategy;
2154
2215
  private readonly executorFactory;
2216
+ /**
2217
+ * Creates a new ORM instance.
2218
+ * @param opts - ORM options
2219
+ */
2155
2220
  constructor(opts: OrmOptions<E>);
2156
- createSession(options?: {
2157
- tx?: ExternalTransaction;
2158
- }): OrmSession<E>;
2221
+ /**
2222
+ * Creates a new ORM session.
2223
+ * @param options - Optional session options
2224
+ * @returns The ORM session
2225
+ */
2226
+ createSession(): OrmSession<E>;
2227
+ /**
2228
+ * Executes a function within a transaction.
2229
+ * @template T - The return type
2230
+ * @param fn - The function to execute
2231
+ * @returns The result of the function
2232
+ * @throws If the transaction fails
2233
+ */
2159
2234
  transaction<T>(fn: (session: OrmSession<E>) => Promise<T>): Promise<T>;
2235
+ /**
2236
+ * Shuts down the ORM and releases underlying resources (pools, timers).
2237
+ */
2238
+ dispose(): Promise<void>;
2160
2239
  }
2161
2240
 
2162
2241
  declare class IdentityMap {
@@ -2170,75 +2249,327 @@ declare class IdentityMap {
2170
2249
  private toIdentityKey;
2171
2250
  }
2172
2251
 
2252
+ /**
2253
+ * Unit of Work pattern implementation for tracking entity changes.
2254
+ */
2173
2255
  declare class UnitOfWork {
2174
2256
  private readonly dialect;
2175
2257
  private readonly executor;
2176
2258
  private readonly identityMap;
2177
2259
  private readonly hookContext;
2178
2260
  private readonly trackedEntities;
2261
+ /**
2262
+ * Creates a new UnitOfWork instance.
2263
+ * @param dialect - The database dialect
2264
+ * @param executor - The database executor
2265
+ * @param identityMap - The identity map
2266
+ * @param hookContext - Function to get the hook context
2267
+ */
2179
2268
  constructor(dialect: Dialect, executor: DbExecutor, identityMap: IdentityMap, hookContext: () => unknown);
2269
+ /**
2270
+ * Gets the identity buckets map.
2271
+ */
2180
2272
  get identityBuckets(): Map<string, Map<string, TrackedEntity>>;
2273
+ /**
2274
+ * Gets all tracked entities.
2275
+ * @returns Array of tracked entities
2276
+ */
2181
2277
  getTracked(): TrackedEntity[];
2278
+ /**
2279
+ * Gets an entity by table and primary key.
2280
+ * @param table - The table definition
2281
+ * @param pk - The primary key value
2282
+ * @returns The entity or undefined if not found
2283
+ */
2182
2284
  getEntity(table: TableDef, pk: string | number): any | undefined;
2285
+ /**
2286
+ * Gets all tracked entities for a specific table.
2287
+ * @param table - The table definition
2288
+ * @returns Array of tracked entities
2289
+ */
2183
2290
  getEntitiesForTable(table: TableDef): TrackedEntity[];
2291
+ /**
2292
+ * Finds a tracked entity.
2293
+ * @param entity - The entity to find
2294
+ * @returns The tracked entity or undefined if not found
2295
+ */
2184
2296
  findTracked(entity: any): TrackedEntity | undefined;
2297
+ /**
2298
+ * Sets an entity in the identity map.
2299
+ * @param table - The table definition
2300
+ * @param pk - The primary key value
2301
+ * @param entity - The entity instance
2302
+ */
2185
2303
  setEntity(table: TableDef, pk: string | number, entity: any): void;
2304
+ /**
2305
+ * Tracks a new entity.
2306
+ * @param table - The table definition
2307
+ * @param entity - The entity instance
2308
+ * @param pk - Optional primary key value
2309
+ */
2186
2310
  trackNew(table: TableDef, entity: any, pk?: string | number): void;
2311
+ /**
2312
+ * Tracks a managed entity.
2313
+ * @param table - The table definition
2314
+ * @param pk - The primary key value
2315
+ * @param entity - The entity instance
2316
+ */
2187
2317
  trackManaged(table: TableDef, pk: string | number, entity: any): void;
2318
+ /**
2319
+ * Marks an entity as dirty (modified).
2320
+ * @param entity - The entity to mark as dirty
2321
+ */
2188
2322
  markDirty(entity: any): void;
2323
+ /**
2324
+ * Marks an entity as removed.
2325
+ * @param entity - The entity to mark as removed
2326
+ */
2189
2327
  markRemoved(entity: any): void;
2328
+ /**
2329
+ * Flushes pending changes to the database.
2330
+ */
2190
2331
  flush(): Promise<void>;
2332
+ /**
2333
+ * Resets the unit of work by clearing all tracked entities and identity map.
2334
+ */
2191
2335
  reset(): void;
2336
+ /**
2337
+ * Flushes an insert operation for a new entity.
2338
+ * @param tracked - The tracked entity to insert
2339
+ */
2192
2340
  private flushInsert;
2341
+ /**
2342
+ * Flushes an update operation for a modified entity.
2343
+ * @param tracked - The tracked entity to update
2344
+ */
2193
2345
  private flushUpdate;
2346
+ /**
2347
+ * Flushes a delete operation for a removed entity.
2348
+ * @param tracked - The tracked entity to delete
2349
+ */
2194
2350
  private flushDelete;
2351
+ /**
2352
+ * Runs a table hook if defined.
2353
+ * @param hook - The hook function
2354
+ * @param tracked - The tracked entity
2355
+ */
2195
2356
  private runHook;
2357
+ /**
2358
+ * Computes changes between current entity state and original snapshot.
2359
+ * @param tracked - The tracked entity
2360
+ * @returns Object with changed column values
2361
+ */
2196
2362
  private computeChanges;
2363
+ /**
2364
+ * Extracts column values from an entity.
2365
+ * @param table - The table definition
2366
+ * @param entity - The entity instance
2367
+ * @returns Object with column values
2368
+ */
2197
2369
  private extractColumns;
2370
+ /**
2371
+ * Executes a compiled query.
2372
+ * @param compiled - The compiled query
2373
+ * @returns Query results
2374
+ */
2198
2375
  private executeCompiled;
2376
+ /**
2377
+ * Gets columns for RETURNING clause.
2378
+ * @param table - The table definition
2379
+ * @returns Array of column nodes
2380
+ */
2199
2381
  private getReturningColumns;
2382
+ /**
2383
+ * Applies RETURNING clause results to the tracked entity.
2384
+ * @param tracked - The tracked entity
2385
+ * @param results - Query results
2386
+ */
2200
2387
  private applyReturningResults;
2388
+ /**
2389
+ * Normalizes a column name by removing quotes and table prefixes.
2390
+ * @param column - The column name to normalize
2391
+ * @returns Normalized column name
2392
+ */
2201
2393
  private normalizeColumnName;
2394
+ /**
2395
+ * Registers an entity in the identity map.
2396
+ * @param tracked - The tracked entity to register
2397
+ */
2202
2398
  private registerIdentity;
2399
+ /**
2400
+ * Creates a snapshot of an entity's current state.
2401
+ * @param table - The table definition
2402
+ * @param entity - The entity instance
2403
+ * @returns Object with entity state
2404
+ */
2203
2405
  private createSnapshot;
2406
+ /**
2407
+ * Gets the primary key value from a tracked entity.
2408
+ * @param tracked - The tracked entity
2409
+ * @returns Primary key value or null
2410
+ */
2204
2411
  private getPrimaryKeyValue;
2205
2412
  }
2206
2413
 
2414
+ /**
2415
+ * Extracts domain events of a specific type.
2416
+ * @template E - The domain event type
2417
+ * @template TType - The specific event type
2418
+ */
2207
2419
  type EventOfType<E extends DomainEvent, TType extends E['type']> = Extract<E, {
2208
2420
  type: TType;
2209
2421
  }>;
2422
+ /**
2423
+ * Domain event handler function.
2424
+ * @template E - The domain event type
2425
+ * @template Context - The context type
2426
+ * @param event - The domain event
2427
+ * @param ctx - The context
2428
+ */
2210
2429
  type DomainEventHandler<E extends DomainEvent, Context> = (event: E, ctx: Context) => Promise<void> | void;
2430
+ /**
2431
+ * Initial handlers for domain events.
2432
+ * @template E - The domain event type
2433
+ * @template Context - The context type
2434
+ */
2211
2435
  type InitialHandlers<E extends DomainEvent, Context> = {
2212
2436
  [K in E['type']]?: DomainEventHandler<EventOfType<E, K>, Context>[];
2213
2437
  };
2438
+ /**
2439
+ * Domain event bus for managing and dispatching domain events.
2440
+ * @template E - The domain event type
2441
+ * @template Context - The context type
2442
+ */
2214
2443
  declare class DomainEventBus<E extends DomainEvent, Context> {
2215
2444
  private readonly handlers;
2445
+ /**
2446
+ * Creates a new DomainEventBus instance.
2447
+ * @param initialHandlers - Optional initial event handlers
2448
+ */
2216
2449
  constructor(initialHandlers?: InitialHandlers<E, Context>);
2450
+ /**
2451
+ * Registers an event handler for a specific event type.
2452
+ * @template TType - The event type
2453
+ * @param type - The event type
2454
+ * @param handler - The event handler
2455
+ */
2217
2456
  on<TType extends E['type']>(type: TType, handler: DomainEventHandler<EventOfType<E, TType>, Context>): void;
2457
+ /**
2458
+ * Registers an event handler for a specific event type (alias for on).
2459
+ * @template TType - The event type
2460
+ * @param type - The event type
2461
+ * @param handler - The event handler
2462
+ */
2218
2463
  register<TType extends E['type']>(type: TType, handler: DomainEventHandler<EventOfType<E, TType>, Context>): void;
2464
+ /**
2465
+ * Dispatches domain events for tracked entities.
2466
+ * @param trackedEntities - Iterable of tracked entities
2467
+ * @param ctx - The context to pass to handlers
2468
+ */
2219
2469
  dispatch(trackedEntities: Iterable<TrackedEntity>, ctx: Context): Promise<void>;
2220
2470
  }
2471
+ /**
2472
+ * Adds a domain event to an entity.
2473
+ * @template E - The domain event type
2474
+ * @param entity - The entity to add the event to
2475
+ * @param event - The domain event to add
2476
+ */
2221
2477
  declare const addDomainEvent: <E extends DomainEvent>(entity: HasDomainEvents<E>, event: E) => void;
2222
2478
 
2479
+ /**
2480
+ * Processes relation changes for entity relationships.
2481
+ */
2223
2482
  declare class RelationChangeProcessor {
2224
2483
  private readonly unitOfWork;
2225
2484
  private readonly dialect;
2226
2485
  private readonly executor;
2227
2486
  private readonly relationChanges;
2487
+ /**
2488
+ * Creates a new RelationChangeProcessor instance.
2489
+ * @param unitOfWork - The unit of work instance
2490
+ * @param dialect - The database dialect
2491
+ * @param executor - The database executor
2492
+ */
2228
2493
  constructor(unitOfWork: UnitOfWork, dialect: Dialect, executor: DbExecutor);
2494
+ /**
2495
+ * Registers a relation change for processing.
2496
+ * @param entry - The relation change entry
2497
+ */
2229
2498
  registerChange(entry: RelationChangeEntry): void;
2499
+ /**
2500
+ * Resets the relation change processor by clearing all pending changes.
2501
+ */
2230
2502
  reset(): void;
2503
+ /**
2504
+ * Processes all pending relation changes.
2505
+ */
2231
2506
  process(): Promise<void>;
2507
+ /**
2508
+ * Handles changes for has-many relations.
2509
+ * @param entry - The relation change entry
2510
+ */
2232
2511
  private handleHasManyChange;
2512
+ /**
2513
+ * Handles changes for has-one relations.
2514
+ * @param entry - The relation change entry
2515
+ */
2233
2516
  private handleHasOneChange;
2517
+ /**
2518
+ * Handles changes for belongs-to relations.
2519
+ * @param _entry - The relation change entry (reserved for future use)
2520
+ */
2234
2521
  private handleBelongsToChange;
2522
+ /**
2523
+ * Handles changes for belongs-to-many relations.
2524
+ * @param entry - The relation change entry
2525
+ */
2235
2526
  private handleBelongsToManyChange;
2527
+ /**
2528
+ * Assigns a foreign key for has-many relations.
2529
+ * @param child - The child entity
2530
+ * @param relation - The has-many relation
2531
+ * @param rootValue - The root entity's primary key value
2532
+ */
2236
2533
  private assignHasManyForeignKey;
2534
+ /**
2535
+ * Detaches a child entity from has-many relations.
2536
+ * @param child - The child entity
2537
+ * @param relation - The has-many relation
2538
+ */
2237
2539
  private detachHasManyChild;
2540
+ /**
2541
+ * Assigns a foreign key for has-one relations.
2542
+ * @param child - The child entity
2543
+ * @param relation - The has-one relation
2544
+ * @param rootValue - The root entity's primary key value
2545
+ */
2238
2546
  private assignHasOneForeignKey;
2547
+ /**
2548
+ * Detaches a child entity from has-one relations.
2549
+ * @param child - The child entity
2550
+ * @param relation - The has-one relation
2551
+ */
2239
2552
  private detachHasOneChild;
2553
+ /**
2554
+ * Inserts a pivot row for belongs-to-many relations.
2555
+ * @param relation - The belongs-to-many relation
2556
+ * @param rootId - The root entity's primary key value
2557
+ * @param targetId - The target entity's primary key value
2558
+ */
2240
2559
  private insertPivotRow;
2560
+ /**
2561
+ * Deletes a pivot row for belongs-to-many relations.
2562
+ * @param relation - The belongs-to-many relation
2563
+ * @param rootId - The root entity's primary key value
2564
+ * @param targetId - The target entity's primary key value
2565
+ */
2241
2566
  private deletePivotRow;
2567
+ /**
2568
+ * Resolves the primary key value from an entity.
2569
+ * @param entity - The entity
2570
+ * @param table - The table definition
2571
+ * @returns The primary key value or null
2572
+ */
2242
2573
  private resolvePrimaryKeyValue;
2243
2574
  }
2244
2575
 
@@ -2297,52 +2628,226 @@ interface HydrationContext<E extends DomainEvent = AnyDomainEvent> {
2297
2628
  entityContext: EntityContext;
2298
2629
  }
2299
2630
 
2631
+ interface SaveGraphOptions {
2632
+ /** Remove existing collection members that are not present in the payload */
2633
+ pruneMissing?: boolean;
2634
+ }
2635
+
2636
+ /**
2637
+ * Interface for ORM interceptors that allow hooking into the flush lifecycle.
2638
+ */
2300
2639
  interface OrmInterceptor {
2640
+ /**
2641
+ * Called before the flush operation begins.
2642
+ * @param ctx - The entity context
2643
+ */
2301
2644
  beforeFlush?(ctx: EntityContext): Promise<void> | void;
2645
+ /**
2646
+ * Called after the flush operation completes.
2647
+ * @param ctx - The entity context
2648
+ */
2302
2649
  afterFlush?(ctx: EntityContext): Promise<void> | void;
2303
2650
  }
2651
+ /**
2652
+ * Options for creating an OrmSession instance.
2653
+ * @template E - The domain event type
2654
+ */
2304
2655
  interface OrmSessionOptions<E extends DomainEvent = OrmDomainEvent> {
2656
+ /** The ORM instance */
2305
2657
  orm: Orm<E>;
2658
+ /** The database executor */
2306
2659
  executor: DbExecutor;
2660
+ /** Optional query logger for debugging */
2307
2661
  queryLogger?: QueryLogger;
2662
+ /** Optional interceptors for flush lifecycle hooks */
2308
2663
  interceptors?: OrmInterceptor[];
2664
+ /** Optional domain event handlers */
2309
2665
  domainEventHandlers?: InitialHandlers<E, OrmSession<E>>;
2310
2666
  }
2667
+ /**
2668
+ * ORM Session that manages entity lifecycle, identity mapping, and database operations.
2669
+ * @template E - The domain event type
2670
+ */
2311
2671
  declare class OrmSession<E extends DomainEvent = OrmDomainEvent> implements EntityContext {
2672
+ /** The ORM instance */
2312
2673
  readonly orm: Orm<E>;
2674
+ /** The database executor */
2313
2675
  readonly executor: DbExecutor;
2676
+ /** The identity map for tracking entity instances */
2314
2677
  readonly identityMap: IdentityMap;
2678
+ /** The unit of work for tracking entity changes */
2315
2679
  readonly unitOfWork: UnitOfWork;
2680
+ /** The domain event bus */
2316
2681
  readonly domainEvents: DomainEventBus<E, OrmSession<E>>;
2682
+ /** The relation change processor */
2317
2683
  readonly relationChanges: RelationChangeProcessor;
2318
2684
  private readonly interceptors;
2685
+ /**
2686
+ * Creates a new OrmSession instance.
2687
+ * @param opts - Session options
2688
+ */
2319
2689
  constructor(opts: OrmSessionOptions<E>);
2690
+ /**
2691
+ * Releases resources associated with this session (executor/pool leases) and resets tracking.
2692
+ * Must be safe to call multiple times.
2693
+ */
2694
+ dispose(): Promise<void>;
2695
+ /**
2696
+ * Gets the database dialect.
2697
+ */
2320
2698
  get dialect(): Dialect;
2699
+ /**
2700
+ * Gets the identity buckets map.
2701
+ */
2321
2702
  get identityBuckets(): Map<string, Map<string, TrackedEntity>>;
2703
+ /**
2704
+ * Gets all tracked entities.
2705
+ */
2322
2706
  get tracked(): TrackedEntity[];
2707
+ /**
2708
+ * Gets an entity by table and primary key.
2709
+ * @param table - The table definition
2710
+ * @param pk - The primary key value
2711
+ * @returns The entity or undefined if not found
2712
+ */
2323
2713
  getEntity(table: TableDef, pk: any): any | undefined;
2714
+ /**
2715
+ * Sets an entity in the identity map.
2716
+ * @param table - The table definition
2717
+ * @param pk - The primary key value
2718
+ * @param entity - The entity instance
2719
+ */
2324
2720
  setEntity(table: TableDef, pk: any, entity: any): void;
2721
+ /**
2722
+ * Tracks a new entity.
2723
+ * @param table - The table definition
2724
+ * @param entity - The entity instance
2725
+ * @param pk - Optional primary key value
2726
+ */
2325
2727
  trackNew(table: TableDef, entity: any, pk?: any): void;
2728
+ /**
2729
+ * Tracks a managed entity.
2730
+ * @param table - The table definition
2731
+ * @param pk - The primary key value
2732
+ * @param entity - The entity instance
2733
+ */
2326
2734
  trackManaged(table: TableDef, pk: any, entity: any): void;
2735
+ /**
2736
+ * Marks an entity as dirty (modified).
2737
+ * @param entity - The entity to mark as dirty
2738
+ */
2327
2739
  markDirty(entity: any): void;
2740
+ /**
2741
+ * Marks an entity as removed.
2742
+ * @param entity - The entity to mark as removed
2743
+ */
2328
2744
  markRemoved(entity: any): void;
2745
+ /**
2746
+ * Registers a relation change.
2747
+ * @param root - The root entity
2748
+ * @param relationKey - The relation key
2749
+ * @param rootTable - The root table definition
2750
+ * @param relationName - The relation name
2751
+ * @param relation - The relation definition
2752
+ * @param change - The relation change
2753
+ */
2329
2754
  registerRelationChange: (root: any, relationKey: RelationKey, rootTable: TableDef, relationName: string, relation: RelationDef, change: RelationChange<any>) => void;
2755
+ /**
2756
+ * Gets all tracked entities for a specific table.
2757
+ * @param table - The table definition
2758
+ * @returns Array of tracked entities
2759
+ */
2330
2760
  getEntitiesForTable(table: TableDef): TrackedEntity[];
2761
+ /**
2762
+ * Registers an interceptor for flush lifecycle hooks.
2763
+ * @param interceptor - The interceptor to register
2764
+ */
2331
2765
  registerInterceptor(interceptor: OrmInterceptor): void;
2766
+ /**
2767
+ * Registers a domain event handler.
2768
+ * @param type - The event type
2769
+ * @param handler - The event handler
2770
+ */
2332
2771
  registerDomainEventHandler<TType extends E['type']>(type: TType, handler: DomainEventHandler<Extract<E, {
2333
2772
  type: TType;
2334
2773
  }>, OrmSession<E>>): void;
2335
- find<TTable extends TableDef>(entityClass: EntityConstructor, id: any): Promise<EntityInstance<TTable> | null>;
2774
+ /**
2775
+ * Finds an entity by its primary key.
2776
+ * @template TCtor - The entity constructor type
2777
+ * @param entityClass - The entity constructor
2778
+ * @param id - The primary key value
2779
+ * @returns The entity instance or null if not found
2780
+ * @throws If entity metadata is not bootstrapped or table has no primary key
2781
+ */
2782
+ find<TCtor extends EntityConstructor<any>>(entityClass: TCtor, id: any): Promise<InstanceType<TCtor> | null>;
2783
+ /**
2784
+ * Finds a single entity using a query builder.
2785
+ * @template TTable - The table type
2786
+ * @param qb - The query builder
2787
+ * @returns The first entity instance or null if not found
2788
+ */
2336
2789
  findOne<TTable extends TableDef>(qb: SelectQueryBuilder<any, TTable>): Promise<EntityInstance<TTable> | null>;
2790
+ /**
2791
+ * Finds multiple entities using a query builder.
2792
+ * @template TTable - The table type
2793
+ * @param qb - The query builder
2794
+ * @returns Array of entity instances
2795
+ */
2337
2796
  findMany<TTable extends TableDef>(qb: SelectQueryBuilder<any, TTable>): Promise<EntityInstance<TTable>[]>;
2797
+ /**
2798
+ * Saves an entity graph (root + nested relations) based on a DTO-like payload.
2799
+ * @param entityClass - Root entity constructor
2800
+ * @param payload - DTO payload containing column values and nested relations
2801
+ * @param options - Graph save options
2802
+ * @returns The root entity instance
2803
+ */
2804
+ saveGraph<TCtor extends EntityConstructor<any>>(entityClass: TCtor, payload: Record<string, any>, options?: SaveGraphOptions & {
2805
+ transactional?: boolean;
2806
+ }): Promise<InstanceType<TCtor>>;
2807
+ /**
2808
+ * Persists an entity (either inserts or updates).
2809
+ * @param entity - The entity to persist
2810
+ * @throws If entity metadata is not bootstrapped
2811
+ */
2338
2812
  persist(entity: object): Promise<void>;
2813
+ /**
2814
+ * Marks an entity for removal.
2815
+ * @param entity - The entity to remove
2816
+ */
2339
2817
  remove(entity: object): Promise<void>;
2818
+ /**
2819
+ * Flushes pending changes to the database.
2820
+ */
2340
2821
  flush(): Promise<void>;
2822
+ /**
2823
+ * Flushes pending changes with interceptors and relation processing.
2824
+ */
2341
2825
  private flushWithHooks;
2826
+ /**
2827
+ * Commits the current transaction.
2828
+ */
2342
2829
  commit(): Promise<void>;
2830
+ /**
2831
+ * Executes a function within a transaction.
2832
+ * @template T - The return type
2833
+ * @param fn - The function to execute
2834
+ * @returns The result of the function
2835
+ * @throws If the transaction fails
2836
+ */
2343
2837
  transaction<T>(fn: (session: OrmSession<E>) => Promise<T>): Promise<T>;
2838
+ /**
2839
+ * Rolls back the current transaction.
2840
+ */
2344
2841
  rollback(): Promise<void>;
2842
+ /**
2843
+ * Gets the execution context.
2844
+ * @returns The execution context
2845
+ */
2345
2846
  getExecutionContext(): ExecutionContext;
2847
+ /**
2848
+ * Gets the hydration context.
2849
+ * @returns The hydration context
2850
+ */
2346
2851
  getHydrationContext(): HydrationContext<E>;
2347
2852
  }
2348
2853
 
@@ -2804,7 +3309,12 @@ declare class InsertQueryState {
2804
3309
  readonly ast: InsertQueryNode;
2805
3310
  constructor(table: TableDef, ast?: InsertQueryNode);
2806
3311
  private clone;
3312
+ private ensureColumnsFromRow;
3313
+ private appendValues;
3314
+ private getTableColumns;
2807
3315
  withValues(rows: Record<string, unknown>[]): InsertQueryState;
3316
+ withColumns(columns: ColumnNode[]): InsertQueryState;
3317
+ withSelect(query: SelectQueryNode, columns: ColumnNode[]): InsertQueryState;
2808
3318
  withReturning(columns: ColumnNode[]): InsertQueryState;
2809
3319
  }
2810
3320
 
@@ -2818,7 +3328,11 @@ declare class InsertQueryBuilder<T> {
2818
3328
  constructor(table: TableDef, state?: InsertQueryState);
2819
3329
  private clone;
2820
3330
  values(rowOrRows: Record<string, unknown> | Record<string, unknown>[]): InsertQueryBuilder<T>;
3331
+ columns(...columns: (ColumnDef | ColumnNode)[]): InsertQueryBuilder<T>;
3332
+ fromSelect(query: SelectQueryNode | SelectQueryBuilder<any, TableDef<any>>, columns?: (ColumnDef | ColumnNode)[]): InsertQueryBuilder<T>;
2821
3333
  returning(...columns: (ColumnDef | ColumnNode)[]): InsertQueryBuilder<T>;
3334
+ private resolveColumnNodes;
3335
+ private resolveSelectQuery;
2822
3336
  compile(compiler: InsertCompiler): CompiledQuery;
2823
3337
  compile(dialect: InsertDialectInput): CompiledQuery;
2824
3338
  toSql(arg: InsertCompiler | InsertDialectInput): string;
@@ -2836,6 +3350,9 @@ declare class UpdateQueryState {
2836
3350
  withSet(values: Record<string, unknown>): UpdateQueryState;
2837
3351
  withWhere(expr: ExpressionNode): UpdateQueryState;
2838
3352
  withReturning(columns: ColumnNode[]): UpdateQueryState;
3353
+ withFrom(from: TableSourceNode): UpdateQueryState;
3354
+ withJoin(join: JoinNode): UpdateQueryState;
3355
+ withTableAlias(alias: string): UpdateQueryState;
2839
3356
  }
2840
3357
 
2841
3358
  type UpdateDialectInput = Dialect | DialectKey;
@@ -2847,9 +3364,14 @@ declare class UpdateQueryBuilder<T> {
2847
3364
  private readonly state;
2848
3365
  constructor(table: TableDef, state?: UpdateQueryState);
2849
3366
  private clone;
3367
+ as(alias: string): UpdateQueryBuilder<T>;
3368
+ from(source: TableDef | TableSourceNode): UpdateQueryBuilder<T>;
3369
+ join(table: TableDef | TableSourceNode | string, condition: ExpressionNode, kind?: JoinKind, relationName?: string): UpdateQueryBuilder<T>;
2850
3370
  set(values: Record<string, unknown>): UpdateQueryBuilder<T>;
2851
3371
  where(expr: ExpressionNode): UpdateQueryBuilder<T>;
2852
3372
  returning(...columns: (ColumnDef | ColumnNode)[]): UpdateQueryBuilder<T>;
3373
+ private resolveTableSource;
3374
+ private resolveJoinTarget;
2853
3375
  compile(compiler: UpdateCompiler): CompiledQuery;
2854
3376
  compile(dialect: UpdateDialectInput): CompiledQuery;
2855
3377
  toSql(arg: UpdateCompiler | UpdateDialectInput): string;
@@ -2866,6 +3388,9 @@ declare class DeleteQueryState {
2866
3388
  private clone;
2867
3389
  withWhere(expr: ExpressionNode): DeleteQueryState;
2868
3390
  withReturning(columns: ColumnNode[]): DeleteQueryState;
3391
+ withUsing(source: TableSourceNode): DeleteQueryState;
3392
+ withJoin(join: JoinNode): DeleteQueryState;
3393
+ withTableAlias(alias: string): DeleteQueryState;
2869
3394
  }
2870
3395
 
2871
3396
  type DeleteDialectInput = Dialect | DialectKey;
@@ -2878,7 +3403,12 @@ declare class DeleteQueryBuilder<T> {
2878
3403
  constructor(table: TableDef, state?: DeleteQueryState);
2879
3404
  private clone;
2880
3405
  where(expr: ExpressionNode): DeleteQueryBuilder<T>;
3406
+ as(alias: string): DeleteQueryBuilder<T>;
3407
+ using(source: TableDef | TableSourceNode): DeleteQueryBuilder<T>;
3408
+ join(table: TableDef | TableSourceNode | string, condition: ExpressionNode, kind?: JoinKind, relationName?: string): DeleteQueryBuilder<T>;
2881
3409
  returning(...columns: (ColumnDef | ColumnNode)[]): DeleteQueryBuilder<T>;
3410
+ private resolveTableSource;
3411
+ private resolveJoinTarget;
2882
3412
  compile(compiler: DeleteCompiler): CompiledQuery;
2883
3413
  compile(dialect: DeleteDialectInput): CompiledQuery;
2884
3414
  toSql(arg: DeleteCompiler | DeleteDialectInput): string;
@@ -2929,11 +3459,12 @@ declare abstract class SqlDialectBase extends Dialect {
2929
3459
  private compileSelectWithSetOps;
2930
3460
  protected compileInsertAst(ast: InsertQueryNode, ctx: CompilerContext): string;
2931
3461
  protected compileReturning(returning: ColumnNode[] | undefined, ctx: CompilerContext): string;
3462
+ private compileInsertSource;
2932
3463
  private compileInsertColumnList;
2933
- private compileInsertValues;
2934
3464
  private compileSelectCore;
2935
3465
  protected compileUpdateAst(ast: UpdateQueryNode, ctx: CompilerContext): string;
2936
3466
  private compileUpdateAssignments;
3467
+ protected compileQualifiedColumn(column: ColumnNode, table: TableNode): string;
2937
3468
  protected compileDeleteAst(ast: DeleteQueryNode, ctx: CompilerContext): string;
2938
3469
  protected formatReturningColumns(returning: ColumnNode[]): string;
2939
3470
  protected compileDistinct(ast: SelectQueryNode): string;
@@ -2945,7 +3476,15 @@ declare abstract class SqlDialectBase extends Dialect {
2945
3476
  protected compileTableName(table: {
2946
3477
  name: string;
2947
3478
  schema?: string;
3479
+ alias?: string;
2948
3480
  }): string;
3481
+ protected compileTableReference(table: {
3482
+ name: string;
3483
+ schema?: string;
3484
+ alias?: string;
3485
+ }): string;
3486
+ private compileUpdateFromClause;
3487
+ private compileDeleteUsingClause;
2949
3488
  protected compileHaving(ast: SelectQueryNode, ctx: CompilerContext): string;
2950
3489
  protected stripTrailingSemicolon(sql: string): string;
2951
3490
  protected wrapSetOperand(sql: string): string;
@@ -2979,7 +3518,7 @@ declare class MySqlDialect extends SqlDialectBase {
2979
3518
  /**
2980
3519
  * Microsoft SQL Server dialect implementation
2981
3520
  */
2982
- declare class SqlServerDialect extends Dialect {
3521
+ declare class SqlServerDialect extends SqlDialectBase {
2983
3522
  protected readonly dialect = "mssql";
2984
3523
  /**
2985
3524
  * Creates a new SqlServerDialect instance
@@ -3010,18 +3549,11 @@ declare class SqlServerDialect extends Dialect {
3010
3549
  * @returns SQL Server SQL string
3011
3550
  */
3012
3551
  protected compileSelectAst(ast: SelectQueryNode, ctx: CompilerContext): string;
3013
- protected compileInsertAst(ast: InsertQueryNode, ctx: CompilerContext): string;
3014
- protected compileUpdateAst(ast: UpdateQueryNode, ctx: CompilerContext): string;
3015
3552
  protected compileDeleteAst(ast: DeleteQueryNode, ctx: CompilerContext): string;
3016
- private compileSelectCore;
3553
+ private compileSelectCoreForMssql;
3017
3554
  private compileOrderBy;
3018
3555
  private compilePagination;
3019
- private renderOrderByNulls;
3020
- private renderOrderByCollation;
3021
- private compileTableSource;
3022
- private compileDerivedTable;
3023
3556
  private compileCtes;
3024
- private wrapSetOperand;
3025
3557
  }
3026
3558
 
3027
3559
  /**
@@ -3045,6 +3577,7 @@ declare class SqliteDialect extends SqlDialectBase {
3045
3577
  * @returns SQLite JSON path expression
3046
3578
  */
3047
3579
  protected compileJsonPath(node: JsonPathNode): string;
3580
+ protected compileQualifiedColumn(column: ColumnNode, _table: TableNode): string;
3048
3581
  protected compileReturning(returning: ColumnNode[] | undefined, ctx: CompilerContext): string;
3049
3582
  protected formatReturningColumns(returning: ColumnNode[]): string;
3050
3583
  supportsReturning(): boolean;
@@ -3671,7 +4204,27 @@ declare class TypeScriptGenerator implements ExpressionVisitor<string>, OperandV
3671
4204
  private mapOp;
3672
4205
  }
3673
4206
 
4207
+ /**
4208
+ * Creates an entity proxy with lazy loading capabilities.
4209
+ * @template TTable - The table type
4210
+ * @template TLazy - The lazy relation keys
4211
+ * @param ctx - The entity context
4212
+ * @param table - The table definition
4213
+ * @param row - The database row
4214
+ * @param lazyRelations - Optional lazy relations
4215
+ * @returns The entity instance
4216
+ */
3674
4217
  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>;
4218
+ /**
4219
+ * Creates an entity instance from a database row.
4220
+ * @template TTable - The table type
4221
+ * @template TResult - The result type
4222
+ * @param ctx - The entity context
4223
+ * @param table - The table definition
4224
+ * @param row - The database row
4225
+ * @param lazyRelations - Optional lazy relations
4226
+ * @returns The entity instance
4227
+ */
3675
4228
  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
4229
 
3677
4230
  type Rows$3 = Record<string, any>[];
@@ -3843,8 +4396,60 @@ declare function BelongsTo(options: BelongsToOptions): DualModePropertyDecorator
3843
4396
  declare function BelongsToMany(options: BelongsToManyOptions): DualModePropertyDecorator;
3844
4397
 
3845
4398
  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>;
4399
+ declare const getTableDefFromEntity: <TTable extends TableDef = TableDef>(ctor: EntityConstructor<any>) => TTable | undefined;
4400
+ declare const selectFromEntity: <TTable extends TableDef = TableDef>(ctor: EntityConstructor<any>) => SelectQueryBuilder<any, TTable>;
4401
+
4402
+ type PoolOptions = {
4403
+ /** Maximum number of live resources (idle + leased). */
4404
+ max: number;
4405
+ /** Minimum number of idle resources to keep warm (best-effort). */
4406
+ min?: number;
4407
+ /** How long an idle resource can sit before being destroyed. */
4408
+ idleTimeoutMillis?: number;
4409
+ /** How often to reap idle resources. Defaults to idleTimeoutMillis / 2 (min 1s). */
4410
+ reapIntervalMillis?: number;
4411
+ /** How long callers wait for a resource before acquire() rejects. */
4412
+ acquireTimeoutMillis?: number;
4413
+ };
4414
+ interface PoolAdapter<TResource> {
4415
+ create(): Promise<TResource>;
4416
+ destroy(resource: TResource): Promise<void>;
4417
+ validate?(resource: TResource): Promise<boolean>;
4418
+ }
4419
+ interface PoolLease<TResource> {
4420
+ readonly resource: TResource;
4421
+ /** Returns the resource to the pool. Idempotent. */
4422
+ release(): Promise<void>;
4423
+ /** Permanently removes the resource from the pool. Idempotent. */
4424
+ destroy(): Promise<void>;
4425
+ }
4426
+
4427
+ declare class Pool<TResource> {
4428
+ private readonly adapter;
4429
+ private readonly options;
4430
+ private destroyed;
4431
+ private creating;
4432
+ private leased;
4433
+ private readonly idle;
4434
+ private readonly waiters;
4435
+ private reapTimer;
4436
+ constructor(adapter: PoolAdapter<TResource>, options: PoolOptions);
4437
+ /**
4438
+ * Acquire a resource lease.
4439
+ * The returned lease MUST be released or destroyed.
4440
+ */
4441
+ acquire(): Promise<PoolLease<TResource>>;
4442
+ /** Destroy pool and all idle resources; waits for in-flight creations to settle. */
4443
+ destroy(): Promise<void>;
4444
+ private totalLive;
4445
+ private makeLease;
4446
+ private releaseResource;
4447
+ private destroyResource;
4448
+ private takeIdleValidated;
4449
+ private reapIdle;
4450
+ private warm;
4451
+ private trimToMinMax;
4452
+ }
3848
4453
 
3849
4454
  interface PostgresClientLike {
3850
4455
  query(text: string, params?: unknown[]): Promise<{
@@ -3917,4 +4522,24 @@ interface CreateTediousClientOptions {
3917
4522
  declare function createTediousMssqlClient(connection: TediousConnectionLike, { Request, TYPES }: TediousModule, options?: CreateTediousClientOptions): MssqlClientLike;
3918
4523
  declare function createTediousExecutor(connection: TediousConnectionLike, module: TediousModule, options?: CreateTediousClientOptions): DbExecutor;
3919
4524
 
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 };
4525
+ interface PooledConnectionAdapter<TConn> {
4526
+ query(conn: TConn, sql: string, params?: unknown[]): Promise<Array<Record<string, unknown>>>;
4527
+ beginTransaction(conn: TConn): Promise<void>;
4528
+ commitTransaction(conn: TConn): Promise<void>;
4529
+ rollbackTransaction(conn: TConn): Promise<void>;
4530
+ }
4531
+ type PooledExecutorFactoryOptions<TConn> = {
4532
+ pool: Pool<TConn>;
4533
+ adapter: PooledConnectionAdapter<TConn>;
4534
+ };
4535
+ /**
4536
+ * Creates a first-class DbExecutorFactory backed by MetalORM's Pool.
4537
+ *
4538
+ * Design goals:
4539
+ * - No leaks by default: pool leases are always released in `finally`.
4540
+ * - Correct transactions: one leased connection per transaction.
4541
+ * - Session-friendly: createExecutor() supports transactions without permanently leasing a connection.
4542
+ */
4543
+ declare function createPooledExecutorFactory<TConn>(opts: PooledExecutorFactoryOptions<TConn>): DbExecutorFactory;
4544
+
4545
+ 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 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, 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, tan, toColumnRef, toTableRef, trim, trunc, truncate, unixTimestamp, upper, utcNow, valueToOperand, visitExpression, visitOperand, weekOfYear, windowFunction, year };