Class: BenchmarkDbContext
Defined in: src/benchmark/ExecutionBenchmarkSuite.ts:31
Base database context class representing a session with the database.
DbContext manages database connections, transactions, change tracking, entity sets (DbSet),
query execution, and schema migrations. Subclass this to define your application's data context.
Example
export class AppDbContext extends DbContext {
public readonly users = this.set(User);
public readonly posts = this.set(Post);
protected onConfiguring(options: DbContextOptionsBuilder): void {
options.useSqlite('./app.db').withLogging(true);
}
}
Extends
Accessors
idempotency
Get Signature
get idempotency():
IdempotencyManager
Defined in: src/context/DbContext.ts:148
Request idempotency manager. Guarantees that duplicate requests or network retries never execute twice.
Returns
Inherited from
outbox
Get Signature
get outbox():
OutboxDispatcher
Defined in: src/context/DbContext.ts:158
Transactional Outbox dispatcher for guaranteed at-least-once domain event publishing.
Returns
Inherited from
pool
Get Signature
get pool():
IConnectionPool|undefined
Defined in: src/context/DbContext.ts:168
The connection pool managing active connections, heartbeat, and diagnostics, if configured.
Returns
IConnectionPool | undefined
Inherited from
provider
Get Signature
get provider():
DbProvider
Defined in: src/context/DbContext.ts:297
Returns the database provider type currently active (e.g. 'sqlite', 'postgres', 'mysql', 'mssql').
Usecase
Use this to write provider-conditional logic or display diagnostics in status dashboards.
Example
if (context.provider === 'postgres') {
// perform postgres-specific JSONB query
}
Returns
The active DbProvider identifier.
Inherited from
adapter
Get Signature
get adapter():
IDbAdapter
Defined in: src/context/DbContext.ts:307
Provides direct access to the underlying low-level database adapter.
Usecase
Use this when low-level adapter operations or driver-specific utilities are needed.
Returns
The active IDbAdapter instance.
Inherited from
cache
Get Signature
get cache():
IQueryCache|undefined
Defined in: src/context/DbContext.ts:778
Returns the configured query cache provider if one was registered in DbContextOptions.
Usecase
Use this to manually inspect or clear cached query entries across the application.
Returns
IQueryCache | undefined
Inherited from
Constructors
Constructor
new BenchmarkDbContext(
options?):BenchmarkDbContext
Defined in: src/context/DbContext.ts:202
Initializes a new instance of the DbContext class.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | DbContextOptions | Optional pre-built DbContextOptions configuration. |
Returns
BenchmarkDbContext
Inherited from
Methods
getUserSummary()
getUserSummary(
minScore):Promise<unknown>
Defined in: src/benchmark/ExecutionBenchmarkSuite.ts:34
Parameters
| Parameter | Type |
|---|---|
minScore | number |
Returns
Promise<unknown>
forTenant()
forTenant(
tenantId):this
Defined in: src/context/DbContext.ts:85
Sets the active tenant identifier on this context instance and returns this for chaining.
Parameters
| Parameter | Type | Description |
|---|---|---|
tenantId | string | number | The tenant identifier (string or number). |
Returns
this
this DbContext instance.
Usecase
Scope a DbContext instance to a specific tenant in Express/Fastify request middleware.
Example
const ctx = new AppDbContext().forTenant(req.headers['x-tenant-id']);
const customers = await ctx.customers.toList(); // auto-filtered by tenant_id
Inherited from
on()
on<
T>(event,handler):this
Defined in: src/context/DbContext.ts:113
Registers a domain or lifecycle event handler (e.g. 'Account:created', '*:deleted', 'EntityCreated').
Type Parameters
| Type Parameter | Default type |
|---|---|
T | any |
Parameters
| Parameter | Type | Description |
|---|---|---|
event | string | The event name or pattern to listen to. |
handler | EventHandler<T> | Callback function invoked with the event payload or entity. |
Returns
this
this DbContext instance for chaining.
Example
db.on('Account:created', async (entity) => {
await eventBus.publish(new AccountCreatedEvent(entity));
});
Inherited from
once()
once<
T>(event,handler):this
Defined in: src/context/DbContext.ts:121
Registers a one-time domain or lifecycle event handler.
Type Parameters
| Type Parameter | Default type |
|---|---|
T | any |
Parameters
| Parameter | Type |
|---|---|
event | string |
handler | EventHandler<T> |
Returns
this
Inherited from
off()
off(
event,handler?):this
Defined in: src/context/DbContext.ts:129
Unregisters a domain or lifecycle event handler.
Parameters
| Parameter | Type |
|---|---|
event | string |
handler? | EventHandler |
Returns
this
Inherited from
emit()
emit(
event,payload,alias?):Promise<void>
Defined in: src/context/DbContext.ts:137
Emits a domain or lifecycle event to all matching registered listeners.
Parameters
| Parameter | Type |
|---|---|
event | string |
payload | any |
alias? | string |
Returns
Promise<void>
Inherited from
withIdempotencyKey()
withIdempotencyKey<
T>(key,fn,options?):Promise<T>
Defined in: src/context/DbContext.ts:180
Executes an operation with automatic idempotency deduplication. If the key has already been completed, returns the cached result without repeating the operation.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | Unique client idempotency key (e.g. UUID, orderId, request ref). |
fn | () => Promise<T> | Business transaction function. |
options? | IdempotencyOptions | Idempotency lock and TTL configurations. |
Returns
Promise<T>
Inherited from
createUnitOfWork()
createUnitOfWork():
UnitOfWork<BenchmarkDbContext>
Defined in: src/context/DbContext.ts:193
Creates a new Unit of Work instance bound to this DbContext session. Enables batching multiple DbSet operations with topological dependency ordering and single-transaction commit.
Returns
UnitOfWork<BenchmarkDbContext>
Inherited from
onConfiguring()
protectedonConfiguring(options):void
Defined in: src/context/DbContext.ts:264
Override this method to configure database providers, connection strings, replica routing, and logging.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | DbContextOptionsBuilder | Fluent builder for database configuration. |
Returns
void
Usecase
Implement this lifecycle hook in your DbContext subclass to specify how to connect to your database.
Example
protected onConfiguring(options: DbContextOptionsBuilder): void {
options.usePostgres(process.env.DATABASE_URL!)
.withLogging(true)
.enableRetryOnFailure(3);
}
Inherited from
onModelCreating()
protectedonModelCreating(modelBuilder):void
Defined in: src/context/DbContext.ts:281
Override this method to configure entity mappings, relationships, composite keys, and table names using fluent API.
Parameters
| Parameter | Type | Description |
|---|---|---|
modelBuilder | ModelBuilder | Fluent builder for model schema definitions. |
Returns
void
Usecase
Implement this lifecycle hook to configure your entity models without adding decorators to domain classes.
Example
protected onModelCreating(modelBuilder: ModelBuilder): void {
modelBuilder.entity(User).toTable('app_users');
modelBuilder.entity(Order).hasOne(User).withForeignKey('userId');
}
Inherited from
set()
set<
T>(entity):DbSet<T>
Defined in: src/context/DbContext.ts:327
Creates or returns a cached DbSet<T> for the specified entity class or table name.
Type Parameters
| Type Parameter |
|---|
T extends object |
Parameters
| Parameter | Type | Description |
|---|---|---|
entity | EntityTarget<T> | The entity class constructor (e.g. User) or table name string. |
Returns
DbSet<T>
A typed DbSet<T> for the requested entity.
Usecase
Access repository methods (CRUD, LINQ querying, batch mutations, change tracking) for any registered entity.
Example
const users = context.set(User);
const activeAdmins = await users
.where(u => u.role === 'admin' && u.isActive === true)
.orderByDescending(u => u.createdAt)
.toList();
Inherited from
procedure()
procedure(
name):StoredProcedureBuilder
Defined in: src/context/DbContext.ts:374
Initiates a fluent stored procedure execution builder.
Enables execution of database stored procedures, routines, and user-defined functions across MSSQL, MySQL, PostgreSQL, and Oracle with full support for input/output/inout parameters, multiple result sets, and transaction binding.
Parameters
| Parameter | Type | Description |
|---|---|---|
name | string | The name of the stored procedure in the database. |
Returns
A StoredProcedureBuilder configured for the procedure.
Usecase
Execute database-native procedures for high performance, complex batch transactions, or legacy procedure integrations.
Example
SQL Server (MSSQL):
const { records, out } = await context.procedure('usp_GetCustomerDashboard')
.input({ CustomerId: 101 })
.output<{ TotalSpent: number }>()
.query<OrderSummary>();
MySQL:
const { out } = await context.procedure('sp_create_user')
.input({ p_email: 'user@example.com' })
.output<{ out_id: number }>()
.run();
PostgreSQL:
const users = await context.procedure('fn_get_active_users')
.input({ min_rank: 5 })
.query<User>();
Inherited from
fromSql()
fromSql<
T>(sql,params?):Promise<T[]>
Defined in: src/context/DbContext.ts:403
Executes a raw parameterized SELECT SQL query returning typed rows.
Type Parameters
| Type Parameter | Default type |
|---|---|
T | unknown |
Parameters
| Parameter | Type | Description |
|---|---|---|
sql | string | Raw SQL query string with parameter placeholders (@p0, @p1, etc.). |
params? | unknown[] | Optional parameter array to bind safely into the query. |
Returns
Promise<T[]>
A Promise resolving to an array of typed row objects.
Usecase
Execute complex analytical queries, CTEs (WITH RECURSIVE), window functions, or custom aggregations.
Example
PostgreSQL / SQLite:
const stats = await context.fromSql<{ department: string; avgSalary: number }>(
'SELECT department, AVG(salary) as "avgSalary" FROM employees GROUP BY department HAVING COUNT(*) > @p0',
[5]
);
MySQL / MSSQL:
const results = await context.fromSql<SalesReport>(
'SELECT CategoryId, SUM(Total) AS Revenue FROM Orders WHERE OrderDate >= @p0 GROUP BY CategoryId',
[new Date(2026, 0, 1)]
);
Inherited from
executeSql()
executeSql(
sql,params?):Promise<{rowsAffected:number; }>
Defined in: src/context/DbContext.ts:428
Executes a raw parameterized SQL command (e.g. INSERT, UPDATE, DELETE, DDL).
Parameters
| Parameter | Type | Description |
|---|---|---|
sql | string | Raw SQL command string with parameter placeholders. |
params? | unknown[] | Optional array of parameter values to bind safely. |
Returns
Promise<{ rowsAffected: number; }>
A Promise resolving to an object with rowsAffected.
Usecase
Perform bulk updates, table truncates, partition management, or raw administrative DML.
Example
PostgreSQL / MySQL / SQLite / MSSQL:
const result = await context.executeSql(
'UPDATE users SET status = @p0, updated_at = @p1 WHERE last_login < @p2',
['dormant', new Date(), sixMonthsAgo]
);
console.log(`Updated ${result.rowsAffected} dormant users`);
Inherited from
beginTransaction()
beginTransaction(
isolationLevel?):Promise<DbTransaction>
Defined in: src/context/DbContext.ts:456
Begins a new database transaction.
Parameters
| Parameter | Type | Description |
|---|---|---|
isolationLevel? | IsolationLevel | Optional transaction isolation level (READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE, SNAPSHOT). |
Returns
Promise<DbTransaction>
A Promise resolving to the active DbTransaction.
Usecase
Gain manual control over transaction boundaries across multiple operations, distributed services, or conditional rollbacks.
Example
PostgreSQL / MySQL / MSSQL:
const tx = await context.beginTransaction(IsolationLevel.SERIALIZABLE);
try {
await context.users.inTransaction(tx).add({ name: 'Bob', email: 'bob@example.com' });
await context.auditLogs.inTransaction(tx).add({ action: 'USER_CREATED', target: 'Bob' });
await tx.commit();
} catch (err) {
await tx.rollback();
throw err;
}
Inherited from
useTransaction()
useTransaction<
T>(fn,isolationLevel?):Promise<T>
Defined in: src/context/DbContext.ts:478
Executes a callback within a managed transaction, auto-committing on success or rolling back on error.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type | Description |
|---|---|---|
fn | (tx) => Promise<T> | Async callback receiving the active DbTransaction. |
isolationLevel? | IsolationLevel | Optional transaction isolation level. |
Returns
Promise<T>
A Promise resolving to the result of the callback.
Usecase
Recommended pattern for executing transactional units of work safely without boilerplate try/catch/commit/rollback.
Example
PostgreSQL / MySQL / MSSQL / SQLite:
const transferResult = await context.useTransaction(async tx => {
await context.accounts.inTransaction(tx).update(fromId, { balance: sourceBal - amt });
await context.accounts.inTransaction(tx).update(toId, { balance: targetBal + amt });
return { success: true, transferred: amt };
});
Inherited from
inTransaction()
inTransaction(
tx):this
Defined in: src/context/DbContext.ts:499
Binds this DbContext instance to an active database transaction. All DbSet instances accessed via this context will automatically execute within the transaction.
Parameters
| Parameter | Type | Description |
|---|---|---|
tx | DbTransaction | The active DbTransaction. |
Returns
this
Inherited from
queryRaw()
queryRaw<
T>(sql,params?):Promise<T[]>
Defined in: src/context/DbContext.ts:527
Executes a parameterized SELECT query returning typed rows.
Type Parameters
| Type Parameter | Default type |
|---|---|
T | unknown |
Parameters
| Parameter | Type |
|---|---|
sql | string |
params? | unknown[] |
Returns
Promise<T[]>
Inherited from
executeRaw()
executeRaw(
sql,params?):Promise<{rowsAffected:number; }>
Defined in: src/context/DbContext.ts:541
Executes a parameterized command (INSERT, UPDATE, DELETE, DDL) returning rowsAffected.
Parameters
| Parameter | Type |
|---|---|
sql | string |
params? | unknown[] |
Returns
Promise<{ rowsAffected: number; }>
Inherited from
queryScalar()
queryScalar<
T>(sql,params?):Promise<T|null>
Defined in: src/context/DbContext.ts:555
Executes a query returning the first column value of the first row (e.g. COUNT(*), SUM(x)).
Type Parameters
| Type Parameter | Default type |
|---|---|
T | unknown |
Parameters
| Parameter | Type |
|---|---|
sql | string |
params? | unknown[] |
Returns
Promise<T | null>
Inherited from
withTransaction()
withTransaction<
T>(fn,isolationLevel?):Promise<T>
Defined in: src/context/DbContext.ts:582
Shorthand callback to execute database work inside a managed transaction, auto-committing on completion or rolling back on error.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type | Description |
|---|---|---|
fn | (tx) => Promise<T> | Async callback receiving the active DbTransaction. |
isolationLevel? | IsolationLevel | Optional transaction isolation level. |
Returns
Promise<T>
A Promise resolving to the result of the callback.
Usecase
Safe, concise transactional block preventing manual try/catch/commit/rollback boilerplate.
Example
const order = await context.withTransaction(async tx => {
const created = await context.orders.inTransaction(tx).add(newOrder);
await context.inventory.inTransaction(tx).update(stockId, { count: remaining });
return created;
});
Inherited from
executeResilientTransaction()
executeResilientTransaction<
T>(fn,isolationLevel?):Promise<T>
Defined in: src/context/DbContext.ts:604
Executes a callback within a managed transaction using the configured execution strategy, automatically retrying with exponential backoff if transient errors or deadlocks occur.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type | Description |
|---|---|---|
fn | (tx) => Promise<T> | Async callback receiving the transaction. |
isolationLevel? | IsolationLevel | Optional isolation level. |
Returns
Promise<T>
A Promise resolving to the callback result.
Usecase
Ideal for cloud databases (Neon, Supabase, PlanetScale, CockroachDB) prone to transient network blips or serialization deadlocks.
Example
const result = await context.executeResilientTransaction(async tx => {
return await context.orders.inTransaction(tx).add(newOrder);
});
Inherited from
DbContext.executeResilientTransaction
executeResilient()
executeResilient<
T>(operation):Promise<T>
Defined in: src/context/DbContext.ts:627
Executes an async operation with automatic retry on transient errors or deadlocks with exponential backoff.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type | Description |
|---|---|---|
operation | () => Promise<T> | Async operation to execute. |
Returns
Promise<T>
A Promise resolving to the operation result.
Usecase
Use this to wrap critical idempotent queries or external database operations to increase fault tolerance.
Example
const data = await context.executeResilient(() => context.users.toList());
Inherited from
connect()
connect():
Promise<void>
Defined in: src/context/DbContext.ts:644
Explicitly establishes a connection pool to the database.
Returns
Promise<void>
Usecase
Call this during application bootstrap to verify database connectivity before accepting incoming traffic.
Example
await context.connect();
console.log('Connected to database successfully');
Inherited from
disconnect()
disconnect():
Promise<void>
Defined in: src/context/DbContext.ts:660
Closes all active connections and cleans up connection pool resources.
Returns
Promise<void>
Usecase
Call this during graceful application shutdown (e.g. SIGTERM, SIGINT) or test teardown.
Example
process.on('SIGTERM', async () => {
await context.disconnect();
process.exit(0);
});
Inherited from
dispose()
dispose():
Promise<void>
Defined in: src/context/DbContext.ts:669
Disposes the context instance, closing all underlying database connections (alias for disconnect()).
Returns
Promise<void>
Usecase
Standard disposal pattern for dependency injection containers and scoped service lifetimes.
Inherited from
ping()
ping():
Promise<boolean>
Defined in: src/context/DbContext.ts:686
Tests database connectivity by executing a lightweight heartbeat query.
Returns
Promise<boolean>
true if database is reachable, otherwise false.
Usecase
Use this in HTTP health check endpoints (GET /healthz or Kubernetes liveness/readiness probes).
Example
app.get('/health', async (req, res) => {
const isHealthy = await context.ping();
res.status(isHealthy ? 200 : 503).json({ database: isHealthy ? 'up' : 'down' });
});
Inherited from
health()
health():
Promise<DbHealthResult>
Defined in: src/context/DbContext.ts:703
Comprehensive health check diagnostic measuring query latency, connectivity status, and server version.
Returns
Promise<DbHealthResult>
Detailed DbHealthResult with latency in milliseconds, connection status, provider, and server version.
Usecase
Ideal for Kubernetes liveness/readiness probes, AWS ALB health checks, and /healthz HTTP monitoring endpoints.
Example
app.get('/healthz', async (req, res) => {
const status = await context.health();
res.status(status.connected ? 200 : 503).json(status);
});
Inherited from
seed()
seed():
Promise<void>
Defined in: src/context/DbContext.ts:753
Executes database seeding logic to populate initial, default, or mock reference data.
Calls this.onSeeding() which can be overridden in application DbContext subclasses.
Returns
Promise<void>
Usecase
Seed admin accounts, lookup tables, test fixtures, or default system configuration.
Example
await context.seed();
Inherited from
onSeeding()
protectedonSeeding():Promise<void>
Defined in: src/context/DbContext.ts:769
Override this method in your DbContext subclass to define custom seeding operations.
Returns
Promise<void>
Example
protected async onSeeding(): Promise<void> {
if (await this.roles.count() === 0) {
await this.roles.addRange([{ name: 'admin' }, { name: 'user' }]);
}
}
Inherited from
saveChanges()
saveChanges():
Promise<number>
Defined in: src/context/DbContext.ts:796
Flushes all tracked entity mutations (Added, Modified, Deleted) in the ChangeTracker in a single transaction.
Detects dirty properties, checks optimistic concurrency versions, updates timestamps, and accepts changes upon commit.
Returns
Promise<number>
The total number of state entries saved to the database.
Usecase
Use this in the Unit of Work pattern where entities are loaded, mutated in memory, and persisted as a batch.
Example
const user = await context.users.track(1);
user.name = 'Updated Name';
const savedCount = await context.saveChanges();
Inherited from
sql()
sql<
T>(strings, ...values):Promise<T[]>
Defined in: src/context/DbContext.ts:879
Safe tagged template literal for executing parameterized raw SQL queries with automatic parameter binding.
Interpolated variables are automatically extracted and converted into parameterized values to prevent SQL injection.
Type Parameters
| Type Parameter | Default type |
|---|---|
T | unknown |
Parameters
| Parameter | Type | Description |
|---|---|---|
strings | TemplateStringsArray | SQL template string parts. |
...values | any[] | Interpolated values to safely parameterize. |
Returns
Promise<T[]>
A Promise resolving to an array of mapped row results.
Usecase
Ideal for complex queries where full SQL syntax is desired without risking SQL injection vulnerabilities.
Example
const minPrice = 50;
const category = 'Electronics';
const items = await context.sql<Product>`
SELECT * FROM products WHERE price > ${minPrice} AND category = ${category}
`;
Inherited from
ensureCreated()
ensureCreated(
entityClasses?):Promise<void>
Defined in: src/context/DbContext.ts:911
Code-First schema synchronization: creates all entity tables, columns, and primary keys if they do not already exist.
Parameters
| Parameter | Type | Description |
|---|---|---|
entityClasses? | Function[] | Optional explicit array of entity classes to generate. If omitted, all decorated classes are used. |
Returns
Promise<void>
Usecase
Ideal for quick prototyping, test setup, local development, and microservices needing zero-friction database initialization.
Example
const context = new AppDbContext();
await context.ensureCreated();
Inherited from
migrate()
migrate(
migrations):Promise<{applied:string[]; }>
Defined in: src/context/DbContext.ts:932
Runs all pending migration modules sequentially.
Parameters
| Parameter | Type | Description |
|---|---|---|
migrations | MigrationModule[] | Array of migration modules containing up() and down() definitions. |
Returns
Promise<{ applied: string[]; }>
A Promise resolving to an object containing an array of applied migration names.
Usecase
Use this during production deployments or CI/CD pipelines to apply schema migrations reliably.
Example
import * as m1 from './migrations/001_initial_schema';
const { applied } = await context.migrate([m1]);
console.log('Applied migrations:', applied);
Inherited from
fetchRelation()
fetchRelation<
E,R>(entity,relationName):Promise<R>
Defined in: src/context/DbContext.ts:948
Dynamically fetches a related navigation property on an entity instance.
Type Parameters
| Type Parameter | Default type |
|---|---|
E extends object | - |
R | any |
Parameters
| Parameter | Type | Description |
|---|---|---|
entity | E | The parent entity instance containing the relation. |
relationName | string | The navigation property name to fetch. |
Returns
Promise<R>
A Promise resolving to the loaded relation data.
Example
const orders = await db.fetchRelation(user, 'orders');
Inherited from
loadRelation()
loadRelation<
E,R>(entity,relationName):Promise<R>
Defined in: src/context/DbContext.ts:964
Alias for fetchRelation().
Type Parameters
| Type Parameter | Default type |
|---|---|
E extends object | - |
R | any |
Parameters
| Parameter | Type |
|---|---|
entity | E |
relationName | string |
Returns
Promise<R>
Inherited from
Properties
users
users:
DbSet<BenchmarkUser>
Defined in: src/benchmark/ExecutionBenchmarkSuite.ts:32
_options
protectedreadonly_options:DbContextOptions
Defined in: src/context/DbContext.ts:58
Inherited from
_adapter
protected_adapter:IDbAdapter
Defined in: src/context/DbContext.ts:59
Inherited from
_currentTransaction?
protectedoptional_currentTransaction?:DbTransaction
Defined in: src/context/DbContext.ts:60
Inherited from
currentUser?
optionalcurrentUser?:string
Defined in: src/context/DbContext.ts:66
The current user or principal identifier for automatic audit logging (@CreatedBy).
Inherited from
tenantId?
optionaltenantId?:string|number
Defined in: src/context/DbContext.ts:71
The current tenant identifier for multi-tenant data isolation (@TenantId).
Inherited from
changeTracker
readonlychangeTracker:ChangeTracker
Defined in: src/context/DbContext.ts:93
The active change tracker recording entity state modifications for saveChanges().
Inherited from
events
readonlyevents:EntityEventBus
Defined in: src/context/DbContext.ts:98
Entity domain and lifecycle event bus.