Skip to main content

EntityTS — Enterprise TypeScript ORM

Classes​

ClassDescription
CockroachDbAdapterCockroachDB distributed database adapter. Extends PostgresAdapter with CockroachDB-specific provider identity and PostgreSQL wire compatibility.
D1AdapterCloudflare D1 serverless SQLite adapter. Runs directly on Cloudflare Workers / Pages using the environment D1 binding.
InterceptingDbAdapter-
MockDbAdapter-
MssqlAdapter-
MysqlAdapter-
NeonAdapterNeon Serverless PostgreSQL adapter using @neondatabase/serverless. Supports serverless connection pooling via WebSockets and HTTP.
PlanetScaleAdapterPlanetScale serverless MySQL adapter using @planetscale/database. Communicates with PlanetScale over HTTP with low latency.
PostgresAdapter-
ReplicaRoutingDbAdapterAn adapter wrapper that routes read operations across read replicas and locks write operations, procedures, and transactions to the primary database.
SqliteAdapter-
SupabaseAdapterSupabase PostgreSQL adapter. Extends PostgresAdapter with Supabase provider identity and SSL defaults.
TursoAdapterTurso / libSQL adapter using @libsql/client. Works with remote Turso edge databases, embedded replicas, or local libSQL files.
AuditEngineEngine that builds and persists AuditLogEntry rows to the audit changelog table.
AuditMetadataRegistryInternal registry mapping entity constructors to their AuditOptions. Populated by the @Auditable class decorator at decoration-time.
BenchmarkRunnerRunner that executes benchmark scenarios with warmup, high-precision timing, percentile distributions, and terminal table formatting.
BenchmarkUser-
BenchmarkDbContextBase database context class representing a session with the database.
BulkDeleteBuilderHigh-performance bulk delete engine for removing multiple rows matching filter conditions.
BulkInsertBuilderHigh-throughput batch insert engine that splits large entity arrays into chunked multi-row INSERT queries.
BulkUpdateBuilderHigh-performance batch update engine that processes large numbers of entity mutations in transactions.
BulkUpsertBuilderHigh-performance bulk upsert engine executing chunked batch insert-or-update operations across database engines.
EntityCacheSecond-level (L2) cache for entities keyed by their primary key. Integrates with TaggedQueryCache to enable entity-wide and per-record cache invalidation.
MemoryQueryCache-
RedisQueryCache-
TaggedQueryCacheAdvanced cache layer supporting tag-based associations and wildcard tag invalidations.
WriteThroughCacheHigh-performance Write-Through & Read-Through caching coordinator. Automatically synchronizes cache state with database operations, evicts stale entries, and handles L2 entity cache invalidation on mutations.
SchemaGeneratorCode-First schema generation utilities.
SchemaMigrationDiffBuilds migration statements from a detailed schema diff.
DbContextBase database context class representing a session with the database.
DbContextFactory-
DbContextOptionsBuilderFluent options builder for configuring a DbContext instance.
DbContextModule-
DatabaseErrorTranslator-
DbException-
ConnectionException-
ProcedureException-
QueryException-
EntityNotFoundException-
DbUpdateConcurrencyException-
IdempotencyConflictException-
EntityValidationException-
UniqueConstraintViolationException-
ForeignKeyViolationException-
CheckConstraintViolationException-
CannotNullConstraintViolationException-
SqlSyntaxErrorException-
TableNotFoundException-
ColumnNotFoundException-
ProcedureNotFoundException-
EntityCreatedEvent emitted immediately after an entity is successfully inserted/created.
EntityUpdatedEvent emitted immediately after an entity is successfully updated.
EntityDeletedEvent emitted immediately after an entity is successfully removed/deleted (soft or hard).
EntityEventBusHigh-performance, zero-dependency async event bus for entity domain and lifecycle events.
GlobalQueryFilterRegistry-
DataLoaderBatcherLightweight in-memory batcher for GraphQL relationship resolvers. Batches individual foreign-key requests across an event loop turn into a single batch query, eliminating the N+1 query problem without requiring external dependencies.
GraphQLSchemaBuilderAutomatically builds GraphQL schema definitions (SDL) and CRUD resolvers directly from EntityTS entity metadata.
IdempotencyManagerEnterprise Idempotency Engine for EntityTS. Guarantees that client retries, webhook dispatches, and duplicate mutation instructions never execute transactions twice.
DrizzleImporter-
PrismaImporter-
TypeormImporter-
ColumnBuilder-
TableBuilder-
MigrationBuilder-
MigrationRunner-
ModelMetadataRegistry-
EntityTypeBuilderFluent builder for configuring metadata, table names, primary keys, and properties of an entity.
ModelBuilderFluent model configuration builder used in DbContext.onModelCreating(modelBuilder).
PropertyBuilder-
DocumentQueryLINQ query compiler for document-oriented databases (MongoDB).
NoSqlContextTop-level context for NoSQL / MongoDB applications in entityTS.
NoSqlSetLINQ-inspired typed collection for NoSQL / MongoDB document querying and persistence.
DynamoDbAdapterAmazon DynamoDB adapter for entityTS NoSQL layer.
MockNoSqlAdapterIn-memory NoSQL document database adapter for fast, zero-dependency unit tests.
MongoDbAdapterMongoDB adapter for entityTS implementing INoSqlAdapter.
RedisAdapterRedis adapter for entityTS NoSQL and key-value/document caching.
OutboxDispatcherEnterprise Transactional Outbox Engine for EntityTS. Guarantees zero message loss and at-least-once delivery between local database transactions and distributed message brokers (e.g. Kafka, RabbitMQ, SQS, Webhooks).
ConnectionPool-
PooledDbAdapterAdapter decorator that manages connection pooling, acquisition bounds, and background health heartbeat checks over any underlying IDbAdapter.
MultipleResultsReaderForward-only reader for stored procedures that return multiple tabular result sets (tables). Modeled after Dapper's GridReader and ADO.NET SqlDataReader.NextResult().
SprocOutputBuilderIntermediate execution builder returned after defining output parameters with .output<TOut>().
StoredProcedureBuilderFluent builder for configuring and executing database stored procedures and routines across all supported database engines.
HavingExpressionBuilder-
AggregateExpression-
GroupKeyExpression-
GroupedQueryBuilderBuilds and executes fluent GROUP BY, HAVING, and projected aggregation queries.
ProjectedGroupedQueryProjected query awaiting terminal execution (toList, first, etc.)
QueryBuilderLow-level SQL AST and query compiler supporting multiple database dialects.
WhereClauseFluent builder for constructing SQL WHERE filter conditions.
WindowSpecBuilder-
WindowFunctionExpression-
WindowFunctionFluent builder for SQL window functions (ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, etc.)
SqlFragmentRepresents a raw SQL expression snippet generated by dialect-aware functions.
RdbmsFunctionBuilderCross-dialect database functions builder providing typed SQL expressions.
CdcEmitterChange Data Capture (CDC) emitter and subscriber.
DefaultExecutionStrategy-
EntityScaffolderTakes a list of IntrospectedTable descriptors and scaffolds TypeScript entity files and a DbContext subclass to the output directory.
SchemaIntrospectorQueries the live database to produce an array of IntrospectedTable descriptors. Supports PostgreSQL, MySQL, SQL Server, and SQLite.
EncryptionEngineEnterprise AES-256-GCM Authenticated Encryption Engine. Provides military-grade, tamper-evident field-level encryption for PCI-DSS, HIPAA, and enterprise PII compliance with zero external dependencies.
SeedRunnerTracks and executes structured seed modules, preventing double-execution via a __entityts_seeds table.
DbSetRepresents a typed collection of entities in the database for querying and mutation operations.
LazyRelationEncapsulates a deferred navigation property reference. Allows on-demand asynchronous resolution of related entities without upfront eager .include().
UpdateSetBuilderFluent builder for specifying property updates in LINQ executeUpdate queries.
FixtureBuilderFixture builder instance providing build(), create(), buildList(), createList().
FixtureFactoryFixture factory system for unit and integration testing in EntityTS.
InMemoryContextLightweight, zero-setup in-memory DbContext for fast unit and integration testing. Powered by MockDbAdapter with full in-memory SQL execution, query inspection, and state reset capabilities.
SqlAssertionsCustom assertions for testing SQL generation and parameter bindings.
ChangeTrackerTracks changes made to entity instances to enable unit-of-work persistence via DbContext.saveChanges().
EntityEntry-
DbTransactionEncapsulates an active database transaction.
TrpcRouterBuilderGenerates typed procedure routers for tRPC backends from EntityTS entity metadata.
UnitOfWorkEnterprise Unit of Work pattern implementation for EntityTS.
ValidationRegistry-
ValidationEngine-

Interfaces​

InterfaceDescription
AdapterParam-
CockroachDbAdapterConfig-
D1PreparedStatementLike-
D1DatabaseLike-
D1AdapterConfig-
DriverPackageInfo-
IDbAdapter-
MockProcedureHandler-
MockProcedureDef-
MockDbAdapterOptions-
MssqlAdapterConfig-
MysqlAdapterConfig-
NeonAdapterConfig-
PlanetScaleAdapterConfig-
PostgresAdapterConfig-
ReplicaRoutingOptions-
SqliteAdapterConfig-
SupabaseAdapterConfig-
TursoAdapterConfig-
AuditOptionsOptions for the @Auditable class decorator.
AuditLogEntryA single row written to the audit changelog table for every tracked mutation.
BenchmarkResultResult metrics collected for an individual benchmark scenario.
BenchmarkScenarioDefinition of an individual benchmark scenario.
BenchmarkOptionsConfiguration options for the benchmark runner.
BulkDeleteOptionsOptions for high-performance bulk deletion.
BulkInsertOptionsOptions for high-performance chunked bulk insertion.
BulkUpdateOptionsOptions for high-performance chunked bulk updates.
BulkUpsertOptionsConfiguration options for batch bulk upsert operations.
EntityCacheOptions-
IQueryCache-
MemoryQueryCacheOptions-
RedisLikeClient-
RedisQueryCacheOptions-
TaggedQueryCacheOptions-
WriteThroughCacheOptions-
ReadThroughOptions-
SchemaDiff-
SchemaGeneratorOptions-
ColumnDiffDetail-
DetailedSchemaDiff-
DbHealthResultDiagnostic health status object returned by context.health().
IDbContextFactory-
DbContextOptions-
BelongsToOptions-
ColumnOptions-
DecimalOptions-
CurrencyOptions-
HasManyOptions-
HasOneOptions-
IndexOptions-
ManyToManyOptions-
ManyToOneOptions-
OneToManyOptions-
OneToOneOptions-
PrimaryKeyOptions-
ForeignKeyOptions-
SoftDeleteOptionsOptions for the @SoftDelete decorator.
TableOptions-
EntityOptions-
VectorOptions-
VersionOptions-
DbContextMiddlewareOptions-
FastifyDbContextOptions-
DbContextModuleOptions-
DbContextModuleAsyncOptions-
IDomainEventBase interface for all typed entity lifecycle domain events.
GraphQLResolverMap-
QueryHooks-
IdempotencyOptions-
IdempotencyRecord-
GeneratedFile-
ImportResult-
ColumnDefinition-
MigrationRecord-
MigrationModule-
ColumnMetadata-
SoftDeleteMetadata-
IndexMetadata-
RelationMetadata-
VersionMetadata-
EntityLifecycleHooks-
EntityMetadata-
InsertOneResult-
InsertManyResult-
UpdateResult-
DeleteResult-
FindOptions-
UpdateOptions-
DeleteOptions-
InsertOptions-
CountOptions-
AggregateOptions-
NoSqlTransaction-
INoSqlAdapterUniversal interface for document-oriented (NoSQL) database adapters in entityTS.
NoSqlPagedResult-
DynamoDbAdapterOptions-
MongoDbAdapterConfig-
RedisAdapterOptions-
OpenTelemetryTracerLike-
PlanNodeA single node extracted from the query plan tree (PostgreSQL JSON format).
QueryPlanResultParsed result of an EXPLAIN [ANALYZE] execution.
QueryPlanLoggerOptionsOptions for createQueryPlanLogger.
SlowQueryLoggerOptions-
StructuredQueryLoggerOptions-
OutboxMessage-
DispatchOptions-
DispatchSummary-
PoolHealthResult-
ConnectionPoolOptions-
IConnectionPool-
ParamOptions-
SprocResultSimplified result returned by .output().query(), .output().queryMultiple(), and .output().run().
StoredProcedureResult-
CursorPaginationOptions-
CursorPageResult-
PagedListOptions-
HavingCondition-
IGroupProxy-
OrderByClause-
JoinClause-
PagedResult-
SqlResult-
SubqueryEncapsulates a compiled or chainable subquery with an assigned table alias.
CommonTableExpressionDefinition of a Common Table Expression (WITH clause).
NearestOptionsOptions for AI vector embedding distance search.
JoinFieldRef-
JoinComparison-
PredicateBuilder-
SearchOptions-
SubqueryCondition-
WhereCondition-
CdcEvent-
CdcSubscriptionFilter-
IExecutionStrategy-
ExecutionStrategyOptions-
EntityScaffolderOptions-
ScaffoldResult-
IntrospectedColumn-
IntrospectedForeignKey-
IntrospectedTable-
EncryptionOptions-
SeedModule-
SeedRecord-
SeedStatus-
DbSetOptions-
InMemoryContextOptions-
SqlQueryResult-
IDbTransactionDriver-
TrpcProcedureHandler-
EntityTrpcRouter-
UnitOfWorkOperation-
UnitOfWorkCommitResult-
ValidationRule-
ValidationResult-

Functions​

FunctionDescription
detectPackageManagerDetect the package manager used in the given directory or process.cwd().
getInstallCommandGet install command line for a given package and package manager.
normalizeProviderNormalizes provider aliases (e.g. 'sqlserver' -> 'mssql', 'postgresql' -> 'postgres').
loadDriverLoads a database driver dynamically and throws a targeted ConnectionException if the package is not installed in the consuming application.
AuditableClass decorator that enables automatic audit changelog tracking for an entity.
createExecutionBenchmarkSuiteCreates and configures the Execution Benchmark Suite for EntityTS.
runExecutionBenchmarksConvenience helper to run the complete execution benchmark suite.
sqlTypeToColumnTypeMaps a SqlType to a dialect-appropriate SQL column type string.
entityToMigrationBuilderConverts an EntityMetadata object into a populated MigrationBuilder that generates correct CREATE TABLE DDL for all supported adapters. Returns undefined for view entities — DDL is skipped for views.
BelongsToProperty decorator establishing a child-to-parent inverse relationship.
ColumnProperty decorator mapping a class property to a database table column.
CompositeKeyClass decorator designating a multi-column composite primary key for an entity.
ComputedProperty decorator designating a database-computed / virtual column.
CreatedAtProperty decorator indicating that this field is auto-populated with the creation timestamp (new Date()) on INSERT.
CreatedByProperty decorator indicating that this field is auto-populated with the current user / author identifier on INSERT.
DecimalProperty decorator defining a high-precision decimal database column. Typically maps to SQL DECIMAL(precision, scale) or NUMERIC(precision, scale). Default precision is 18 and scale is 4.
CurrencyProperty decorator defining an ISO 4217 3-character currency code column (e.g. 'USD', 'EUR', 'GBP').
DefaultProperty decorator designating a default value or generator function for an entity property.
EncryptedProperty decorator marking a class property for transparent AES-256-GCM field-level encryption. Automatically encrypts plaintext values before database persistence (INSERT / UPDATE) and decrypts values upon entity hydration during queries.
EnumProperty decorator restricting a column's value to a specific set of allowed enum strings.
HasManyProperty decorator establishing a one-to-many relationship with another entity.
HasOneProperty decorator establishing a one-to-one parent relationship with another entity.
IndexDecorator defining an index on an entity table.
BeforeInsertMethod decorator marking a method to run immediately before this entity is inserted into the database.
AfterInsertMethod decorator marking a method to run immediately after this entity is inserted and its ID is assigned.
BeforeUpdateMethod decorator marking a method to run immediately before an existing entity is updated.
AfterUpdateMethod decorator marking a method to run immediately after an existing entity is updated.
BeforeRemoveMethod decorator marking a method to run immediately before an entity is removed or soft-deleted.
AfterRemoveMethod decorator marking a method to run immediately after an entity is removed.
ManyToManyProperty decorator establishing a many-to-many relationship joined via a junction table.
ManyToOneProperty decorator establishing a many-to-one relationship with a parent entity. Supports both TypeORM style @ManyToOne(() => User, u => u.posts, { foreignKey: 'userId' }) and EntityTS style @ManyToOne(() => User, 'userId').
OneToManyProperty decorator establishing a one-to-many relationship with another entity. Supports both TypeORM style @OneToMany(() => Post, p => p.user, { cascade: true }) and EntityTS @OneToMany(() => Post, { foreignKey: 'userId' }).
OneToOneProperty decorator establishing a one-to-one relationship with another entity.
PrimaryKeyProperty decorator designating a property as the primary key of the entity.
ForeignKeyProperty decorator defining an explicit foreign key column referencing another entity.
IgnoreProperty decorator telling the ORM to completely ignore this property during database operations.
SoftDeleteClass or Property decorator to enable soft deletion for an entity model.
TableClass decorator mapping an entity class to a specific database table name and schema.
EntityClass decorator marking a TypeScript class as a database entity managed by DbContext.
ViewEntityClass decorator mapping an entity class to a database VIEW rather than a table.
TenantIdProperty decorator marking a field as the tenant discriminator identifier.
UniqueProperty decorator that enforces a UNIQUE constraint on the mapped database column.
UpdatedAtProperty decorator indicating that this field is auto-updated with current timestamp (new Date()) on INSERT and UPDATE.
VectorProperty decorator defining an AI vector embedding column (e.g. pgvector, OpenAI, Cohere, Llama). Supports similarity searches with cosine distance (<=>), Euclidean/L2 distance (<->), and inner product (<#>).
VersionProperty decorator for optimistic concurrency control.
RowVersionAlias for @Version() configured with the sequential numeric strategy.
ConcurrencyCheckProperty decorator that verifies an individual property hasn't changed before executing UPDATE or DELETE.
dbContextMiddlewareExpress / Connect middleware that attaches a scoped DbContext instance to req.dbContext. Automatically disconnects on response finish if autoDispose is enabled.
fastifyDbContextFastify plugin that attaches a scoped DbContext instance to request.dbContext. Automatically disposes the context on the onResponse hook if autoDispose is enabled (default true).
getDbContextToken-
InjectDbContextParameter decorator for injecting DbContext into NestJS constructors.
createDbContext-
createOpenTelemetryHooks-
createQueryPlanLoggerCreates a QueryHooks plugin that transparently runs EXPLAIN [ANALYZE] alongside each SELECT query and prints a rich, structured plan report with:
createSlowQueryLogger-
createStructuredQueryLoggerCreates a structured query logger that formats executed SQL operations like Prisma.
encodeCursorEncodes cursor data into a URL-safe Base64 string.
decodeCursorDecodes a cursor token (Base64 string or plain object) into an object.
createJoinProxyCreates a dynamic proxy tracking column access and operations for cross-table predicates.
extractColumnNameExtracts a property or column name from either a string key or a lambda property accessor.
isTransientErrorChecks whether a given database error is transient and safe to retry.
createTestContextCreates an in-memory DbContext instance for testing.
expectQueryCreates an SqlAssertions wrapper for query verification.
IsEmailValidates that the property value is a valid email address string.
LengthValidates that a string's length is between min and max inclusive.
MinValidates that a number is greater than or equal to a minimum value.
MaxValidates that a number is less than or equal to a maximum value.
IsNotEmptyValidates that a value is neither null, undefined, nor empty string/array.
MatchesValidates that a string matches a specified Regular Expression pattern.
IsUrlValidates that a string is a well-formed HTTP/HTTPS URL.
CustomValidatorValidates property using a custom validation function.

Type Aliases​

Type AliasDescription
DbProvider-
LoadBalancingStrategy-
ColumnChangeType-
NamingConvention-
LogMode-
LogFunction-
QueryTrackingBehavior-
EventHandler-
QueryFilterCallback-
PropertySelector-
EntityConstructor-
DocumentFieldSelector-
NoSqlProvider-
NoSqlFilter-
NoSqlUpdate-
AggregationStage-
CollectionTarget-
NoSqlPredicate-
NoSqlFieldSelector-
LogFormat-
OutboxStatus-
PoolStatus-
UnpackAggregate-
ProjectedResult-
JoinType-
JoinProxy-
WhereOperator-
LogicalOperator-
SearchMode-
ColumnKey-
CdcOperation-
CdcHandler-
WithLoaded-
EntityTarget-
LinqPredicate-
FactoryGenerator-
ValidationOptions-

Variables​

VariableDescription
DRIVER_REGISTRY-
fnDialect-aware RDBMS functions namespace (fn).
rdbmsAlias for fn.

Enumerations​

EnumerationDescription
ParameterDirection-
SqlType-
EntityState-
IsolationLevel-

References​

EntityCreatedEvent​

Renames and re-exports EntityCreated


EntityUpdatedEvent​

Renames and re-exports EntityUpdated


EntityDeletedEvent​

Renames and re-exports EntityDeleted