Class: DbContextOptionsBuilder
Defined in: src/context/DbContextOptionsBuilder.ts:41
Fluent options builder for configuring a DbContext instance.
Provides methods for configuring database drivers, connection strings, logging, caching providers, query lifecycle hooks, naming conventions, read replicas, and retry resilience.
Constructors
Constructor
new DbContextOptionsBuilder():
DbContextOptionsBuilder
Returns
DbContextOptionsBuilder
Methods
useSqlServer()
useSqlServer(
config):this
Defined in: src/context/DbContextOptionsBuilder.ts:69
Configures the context to connect to a Microsoft SQL Server database.
Parameters
| Parameter | Type | Description |
|---|---|---|
config | string | MssqlAdapterConfig | Connection configuration object with credentials or a standard ADO.NET connection string. |
Returns
this
this builder instance for chaining.
Usecase
Connect to Microsoft SQL Server on-premise, AWS RDS for SQL Server, or Azure SQL Database instances.
Example
Connection String:
options.useSqlServer('Server=localhost,1433;Database=appdb;User Id=sa;Password=Secret123!;Encrypt=false;');
Structured Configuration:
options.useSqlServer({
server: 'localhost',
port: 1433,
database: 'appdb',
user: 'sa',
password: 'SecretPassword!',
options: { encrypt: true, trustServerCertificate: false }
});
usePostgres()
usePostgres(
config):this
Defined in: src/context/DbContextOptionsBuilder.ts:102
Configures the context to connect to a PostgreSQL database.
Parameters
| Parameter | Type | Description |
|---|---|---|
config | string | PostgresAdapterConfig | Connection URI string or node-postgres pg.PoolConfig object. |
Returns
this
this builder instance for chaining.
Usecase
Connect to standard PostgreSQL instances, AWS RDS Postgres, Google Cloud SQL, Supabase, or Railway.
Example
Connection URI:
options.usePostgres('postgresql://postgres:secret@localhost:5432/appdb?sslmode=prefer');
Structured Configuration:
options.usePostgres({
host: 'localhost',
port: 5432,
database: 'appdb',
user: 'postgres',
password: 'secretpassword',
max: 20,
idleTimeoutMillis: 30000,
});
useMysql()
useMysql(
config):this
Defined in: src/context/DbContextOptionsBuilder.ts:134
Configures the context to connect to a MySQL or MariaDB database.
Parameters
| Parameter | Type | Description |
|---|---|---|
config | string | MysqlAdapterConfig | Connection URI string or mysql2.PoolOptions configuration object. |
Returns
this
this builder instance for chaining.
Usecase
Connect to MySQL 5.7/8.x or MariaDB database servers across local containers, AWS RDS, or Google Cloud SQL.
Example
Connection URI:
options.useMysql('mysql://root:secret@localhost:3306/appdb?timezone=Z');
Structured Configuration:
options.useMysql({
host: 'localhost',
port: 3306,
database: 'appdb',
user: 'root',
password: 'secretpassword',
connectionLimit: 15,
});
useSqlite()
useSqlite(
config):this
Defined in: src/context/DbContextOptionsBuilder.ts:158
Configures the context to connect to a SQLite database.
Parameters
| Parameter | Type | Description |
|---|---|---|
config | string | SqliteAdapterConfig | Database file path string (e.g. './data.db' or ':memory:') or configuration object. |
Returns
this
this builder instance for chaining.
Usecase
Connect to local file-based or in-memory SQLite databases for development, testing, CLI tools, or Electron/desktop apps.
Example
File Path / In-Memory:
// File database:
options.useSqlite('./data/app.db');
// Fast in-memory database for unit testing:
options.useSqlite(':memory:');
useNeon()
useNeon(
config):this
Defined in: src/context/DbContextOptionsBuilder.ts:177
Configures the context to connect to a Neon Serverless PostgreSQL database over HTTP/WebSockets.
Parameters
| Parameter | Type | Description |
|---|---|---|
config | string | NeonAdapterConfig | Neon connection string URI or @neondatabase/serverless configuration object. |
Returns
this
this builder instance for chaining.
Usecase
Connect to Neon serverless Postgres with instant branching, autoscaling, and connection pooling.
Example
options.useNeon(process.env.NEON_DATABASE_URL || 'postgresql://user:pass@ep-cool-branch-12345.us-east-2.aws.neon.tech/neondb?sslmode=require');
usePlanetScale()
usePlanetScale(
config):this
Defined in: src/context/DbContextOptionsBuilder.ts:198
Configures the context to connect to PlanetScale MySQL via HTTP.
Parameters
| Parameter | Type | Description |
|---|---|---|
config | string | PlanetScaleAdapterConfig | PlanetScale connection string or @planetscale/database configuration object. |
Returns
this
this builder instance for chaining.
Usecase
Connect to PlanetScale's serverless MySQL platform in serverless functions, Vercel, or AWS Lambda without connection pool exhaustion.
Example
options.usePlanetScale({
url: process.env.DATABASE_URL,
});
useTurso()
useTurso(
config):this
Defined in: src/context/DbContextOptionsBuilder.ts:220
Configures the context to connect to Turso (libSQL) distributed edge database.
Parameters
| Parameter | Type | Description |
|---|---|---|
config | string | TursoAdapterConfig | Turso database URL or @libsql/client configuration object. |
Returns
this
this builder instance for chaining.
Usecase
Connect to Turso edge SQLite databases with distributed replication and sub-millisecond global queries.
Example
options.useTurso({
url: process.env.TURSO_DATABASE_URL!,
authToken: process.env.TURSO_AUTH_TOKEN!,
});
useCockroachDb()
useCockroachDb(
config):this
Defined in: src/context/DbContextOptionsBuilder.ts:239
Configures the context to connect to a CockroachDB distributed SQL cluster.
Parameters
| Parameter | Type | Description |
|---|---|---|
config | string | CockroachDbAdapterConfig | CockroachDB connection string or configuration object. |
Returns
this
this builder instance for chaining.
Usecase
Connect to CockroachDB for multi-region active-active high availability and global ACID transactions.
Example
options.useCockroachDb('postgresql://user:pass@free-tier14.gcp-us-east1.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full');
useD1()
useD1(
bindingOrConfig):this
Defined in: src/context/DbContextOptionsBuilder.ts:265
Configures the context to connect to Cloudflare D1 serverless database.
Parameters
| Parameter | Type | Description |
|---|---|---|
bindingOrConfig | D1DatabaseLike | D1AdapterConfig | Cloudflare D1 environment binding (env.DB) or config object. |
Returns
this
this builder instance for chaining.
Usecase
Run queries directly on Cloudflare Workers edge runtime bound to Cloudflare D1.
Example
export default {
async fetch(req, env) {
const options = new DbContextOptionsBuilder().useD1(env.DB).build();
const db = new AppDbContext(options);
const users = await db.users.toList();
return Response.json(users);
}
};
useSupabase()
useSupabase(
config):this
Defined in: src/context/DbContextOptionsBuilder.ts:284
Configures the context to connect to a Supabase Postgres database.
Parameters
| Parameter | Type | Description |
|---|---|---|
config | string | SupabaseAdapterConfig | Supabase connection string or configuration object. |
Returns
this
this builder instance for chaining.
Usecase
Connect to Supabase Postgres database with support for Row-Level Security (RLS) and pgvector embeddings.
Example
options.useSupabase('postgresql://postgres.xxx:pass@aws-0-us-east-1.pooler.supabase.com:6543/postgres?pgbouncer=true');
useAdapter()
useAdapter(
adapter):this
Defined in: src/context/DbContextOptionsBuilder.ts:298
Supplies a custom database adapter implementing the IDbAdapter interface.
Parameters
| Parameter | Type | Description |
|---|---|---|
adapter | IDbAdapter | An instance of IDbAdapter. |
Returns
this
this builder instance for chaining.
Usecase
Use a customized adapter, database wrapper, or driver not bundled by default.
useMock()
useMock(
mockOptions?):this
Defined in: src/context/DbContextOptionsBuilder.ts:311
Configures an in-memory mock database adapter for fast unit testing.
Parameters
| Parameter | Type | Description |
|---|---|---|
mockOptions? | MockDbAdapterOptions | Mock behavior configuration. |
Returns
this
this builder instance for chaining.
Usecase
Ideal for unit testing business logic and services without spinning up a live database server.
withLogging()
withLogging(
logging):this
Defined in: src/context/DbContextOptionsBuilder.ts:337
Enables query logging in structured EF Core format, JSON, compact one-line format, or via a custom logger callback.
Parameters
| Parameter | Type | Description |
|---|---|---|
logging | LogMode | 'structured' (or true) for formatted multi-line logs, 'json', 'compact', or a custom (sql, params, ms) => void callback. |
Returns
this
this builder instance for chaining.
Usecase
Debug executed SQL queries with duration, parameter bindings, and error states.
Example
// 1. Formatted multi-line logging:
options.withLogging(true);
// 2. Structured JSON for cloud log aggregators (Datadog, CloudWatch):
options.withLogging('json');
// 3. Custom logger (e.g. Winston / Pino):
options.withLogging((sql, params, ms) => logger.info({ sql, params, durationMs: ms }));
withHooks()
withHooks(
hooks):this
Defined in: src/context/DbContextOptionsBuilder.ts:349
Registers global query lifecycle hooks for auditing, tracing, or telemetry.
Parameters
| Parameter | Type | Description |
|---|---|---|
hooks | QueryHooks | Object with beforeExecute, afterExecute, and onError handlers. |
Returns
this
this builder instance for chaining.
Usecase
Add OpenTelemetry spans, metrics, security audits, or performance alerts on slow queries.
withQueryPlanner()
withQueryPlanner(
planOpts?):this
Defined in: src/context/DbContextOptionsBuilder.ts:385
Attaches a live query plan analyzer that transparently runs EXPLAIN [ANALYZE] alongside
each SELECT query and prints a detailed plan report — including estimated/actual row counts,
planner cost, index usage, Seq Scan detection, and Nested Loop warnings.
Supported providers: postgres, neon, cockroachdb, supabase, mysql, sqlite, turso, d1.
Parameters
| Parameter | Type | Description |
|---|---|---|
planOpts? | Omit<QueryPlanLoggerOptions, "adapter"> | Configuration: analyze flag, thresholdMs, warnOnSeqScan, and more. The adapter property is automatically filled from the configured adapter. |
Returns
this
this builder instance for chaining.
Usecase
Identify missing indexes, full-table scans, and join strategy issues directly in server logs during development or staging without needing an external database GUI.
Example
// In onConfiguring — EXPLAIN (no re-execution) on every SELECT:
options.withQueryPlanner();
// EXPLAIN ANALYZE on queries slower than 50ms, with alerting:
options.withQueryPlanner({
analyze: true,
thresholdMs: 50,
warnOnSeqScan: true,
onPlan: (plan) => {
if (plan.hasSeqScan) alerting.warn('seq_scan', plan.sql);
},
});
withCache()
withCache(
cache):this
Defined in: src/context/DbContextOptionsBuilder.ts:399
Registers a query cache provider (e.g. Redis, Memcached, or in-memory LRU).
Parameters
| Parameter | Type | Description |
|---|---|---|
cache | IQueryCache | Implementation of IQueryCache. |
Returns
this
this builder instance for chaining.
Usecase
Enables .cache(ttlMs) queries on DbSet to reduce database load on frequent reads.
withNamingConvention()
withNamingConvention(
convention):this
Defined in: src/context/DbContextOptionsBuilder.ts:411
Configures column and table naming conventions (e.g. snake_case, camelCase, PascalCase).
Parameters
| Parameter | Type | Description |
|---|---|---|
convention | NamingConvention | Target naming convention. |
Returns
this
this builder instance for chaining.
Usecase
Automatically convert TypeScript camelCase property names to database snake_case columns.
withCommandTimeout()
withCommandTimeout(
timeoutMs):this
Defined in: src/context/DbContextOptionsBuilder.ts:423
Sets the default command timeout for all queries executed through this context.
Parameters
| Parameter | Type | Description |
|---|---|---|
timeoutMs | number | Command timeout in milliseconds. |
Returns
this
this builder instance for chaining.
Usecase
Prevent slow or stalled queries from hanging server processes indefinitely.
withTenant()
withTenant(
tenantId):this
Defined in: src/context/DbContextOptionsBuilder.ts:437
Sets the active tenant identifier for multi-tenant data isolation.
All entities with @TenantId() will be automatically partitioned by this identifier.
Parameters
| Parameter | Type | Description |
|---|---|---|
tenantId | string | number | The active tenant identifier (string or number). |
Returns
this
this builder instance for chaining.
Usecase
Multi-tenant SaaS applications scoping requests to a specific organization or account.
withReadReplicas()
withReadReplicas(
replicas,options?):this
Defined in: src/context/DbContextOptionsBuilder.ts:452
Configures one or more read replicas for automatic query load balancing.
Read queries (SELECT) route to replicas using round-robin or random distribution, while writes route to primary.
Parameters
| Parameter | Type | Description |
|---|---|---|
replicas | any[] | Array of replica adapters or connection configurations. |
options? | ReplicaRoutingOptions | Replica routing configuration (e.g. strategy, health checks). |
Returns
this
this builder instance for chaining.
Usecase
Scale database read capacity horizontally across read replicas.
withExecutionStrategy()
withExecutionStrategy(
strategyOrOptions?):this
Defined in: src/context/DbContextOptionsBuilder.ts:468
Configures a custom execution strategy or options for handling retries and transient failures.
Parameters
| Parameter | Type | Description |
|---|---|---|
strategyOrOptions? | IExecutionStrategy | ExecutionStrategyOptions | An IExecutionStrategy instance or ExecutionStrategyOptions. |
Returns
this
this builder instance for chaining.
Usecase
Implement custom retry policies for cloud database environments.
enableRetryOnFailure()
enableRetryOnFailure(
maxRetryCount?,maxDelayMs?):this
Defined in: src/context/DbContextOptionsBuilder.ts:501
Enables automatic retry with exponential backoff for transient connection errors and deadlocks.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
maxRetryCount | number | 3 | Maximum number of retry attempts (default: 3). |
maxDelayMs | number | 2000 | Maximum delay between retries in milliseconds (default: 2000). |
Returns
this
this builder instance for chaining.
Usecase
Guard against transient network hiccups and temporary database locking deadlocks.
Example
options.enableRetryOnFailure(3, 2000);
useQueryTrackingBehavior()
useQueryTrackingBehavior(
behavior):this
Defined in: src/context/DbContextOptionsBuilder.ts:517
Configures default query change tracking behavior for queries executed through this context.
Parameters
| Parameter | Type | Description |
|---|---|---|
behavior | QueryTrackingBehavior | 'trackAll' to enable automatic change tracking for all LINQ queries by default, or 'noTracking' to require explicit .asTracking() on query chains. |
Returns
this
this builder instance for chaining.
useTracking()
useTracking():
this
Defined in: src/context/DbContextOptionsBuilder.ts:527
Configures all LINQ queries to automatically track returned entities by default.
Returns
this
this builder instance for chaining.
useNoTracking()
useNoTracking():
this
Defined in: src/context/DbContextOptionsBuilder.ts:536
Configures all LINQ queries to disable entity tracking by default (the recommended default for read performance).
Returns
this
this builder instance for chaining.
withConnectionPool()
withConnectionPool(
options?):this
Defined in: src/context/DbContextOptionsBuilder.ts:546
Configures connection pooling, active connection bounds, and background health heartbeats.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | ConnectionPoolOptions | Connection pool settings (min/max connections, idle/acquire timeouts, heartbeat). |
Returns
this
this builder instance for chaining.
build()
build():
DbContextOptions
Defined in: src/context/DbContextOptionsBuilder.ts:556
Builds and resolves the final DbContextOptions object.
Returns
Configured DbContextOptions object.