Skip to main content

Class: DbSet<T>

Defined in: src/set/DbSet.ts:76

Represents a typed collection of entities in the database for querying and mutation operations.

DbSet<T> provides a fluent LINQ-style query builder, CRUD operations, bulk batching, pagination, relation loading, and transaction binding for a specific entity type or table.

Type Parameters​

Type ParameterDefault type
T extends objectany

Constructors​

Constructor​

new DbSet<T>(adapter, entityTarget, queryBuilder?, transaction?, context?, options?): DbSet<T>

Defined in: src/set/DbSet.ts:95

Initializes a new instance of the DbSet class for a specific entity model or table name.

Parameters​

ParameterTypeDescription
adapterIDbAdapterThe low-level database adapter (e.g. SQLite, PostgreSQL, MySQL, SQL Server).
entityTargetEntityTarget<T>The entity class constructor (decorated with @Entity) or raw table name string.
queryBuilder?QueryBuilder<T>Optional internal QueryBuilder state for immutable method chaining.
transaction?DbTransactionOptional active database transaction context.
context?anyOptional parent DbContext instance.
options?DbSetOptionsOptional query configuration flags (soft deletes, caching, relation includes).

Returns​

DbSet<T>

Methods​

getTableName()​

getTableName(): string

Defined in: src/set/DbSet.ts:126

Returns the underlying database table name associated with this DbSet.

Returns​

string

The resolved table name as a string.

Usecase​

Use this when constructing dynamic SQL queries, generating log messages, or verifying table names.

Example​

const tableName = context.users.getTableName(); // returns 'users'

inTransaction()​

inTransaction(tx): DbSet<T>

Defined in: src/set/DbSet.ts:147

Attaches this DbSet query or mutation operation to an active database transaction.

Parameters​

ParameterTypeDescription
txDbTransactionThe active DbTransaction instance obtained from context.beginTransaction().

Returns​

DbSet<T>

A new cloned DbSet scoped to the provided transaction.

Usecase​

Use this to execute queries or mutations within a unit-of-work transaction to guarantee ACID consistency.

Example​

const tx = await context.beginTransaction();
try {
await context.users.inTransaction(tx).add({ name: 'Alice' });
await tx.commit();
} catch (err) {
await tx.rollback();
}

on()​

on<E>(event, handler): this

Defined in: src/set/DbSet.ts:158

Registers a lifecycle event listener on this DbSet (e.g. 'created', 'updated', 'deleted').

Type Parameters​

Type ParameterDefault type
ET

Parameters​

ParameterTypeDescription
eventstringLifecycle event name or pattern.
handlerEventHandler<E>Asynchronous or synchronous event callback.

Returns​

this

this instance for chaining.


off()​

off(event, handler?): this

Defined in: src/set/DbSet.ts:169

Unregisters a lifecycle event listener from this DbSet.

Parameters​

ParameterType
eventstring
handler?EventHandler

Returns​

this


withDeleted()​

withDeleted(): DbSet<T>

Defined in: src/set/DbSet.ts:228

Disables the soft-delete filter, causing subsequent query execution to return both active and soft-deleted records.

Returns​

DbSet<T>

A new cloned DbSet configured to include soft-deleted records.

Usecase​

Use this when building audit logs, admin dashboards, or compliance reports where deleted items must be visible.

Example​

// Fetch all users including previously soft-deleted ones
const allUsers = await context.users.withDeleted().toList();

onlyDeleted()​

onlyDeleted(): DbSet<T>

Defined in: src/set/DbSet.ts:243

Scopes the query to return only records that have been soft-deleted (where deletedAt IS NOT NULL).

Returns​

DbSet<T>

A new cloned DbSet configured to filter exclusively for deleted records.

Usecase​

Use this to display a "Trash" or "Recycle Bin" screen allowing users to inspect or restore deleted items.

Example​

// Fetch records in the recycle bin
const trashedUsers = await context.users.onlyDeleted().toList();

ignoreQueryFilters()​

ignoreQueryFilters(): DbSet<T>

Defined in: src/set/DbSet.ts:258

Ignores all global and model-level query filters for this query execution.

Returns​

DbSet<T>

A new cloned DbSet with global query filters bypassed.

Usecase​

Use this in multi-tenant systems for cross-tenant super-admin tasks or background jobs that need system-wide access.

Example​

// Query records across all tenants by bypassing tenant isolation filters
const allTenantsUsers = await context.users.ignoreQueryFilters().toList();

ignoreTenant()​

ignoreTenant(): DbSet<T>

Defined in: src/set/DbSet.ts:272

Bypasses automatic tenant isolation filters for cross-tenant super-admin queries.

Returns​

DbSet<T>

A new cloned DbSet ignoring @TenantId filtering.

Usecase​

System analytics, global reporting, or platform administrative consoles.

Example​

const allTenantsUsers = await context.users.ignoreTenant().toList();

withLazy()​

withLazy(): DbSet<T>

Defined in: src/set/DbSet.ts:286

Automatically initializes unpopulated relation properties as LazyRelation instances.

Returns​

DbSet<T>

A new cloned DbSet with lazy relation resolution enabled.

Example​

const users = await context.users.withLazy().toList();
const posts = await users[0].posts.fetch();

forUpdate()​

forUpdate(options?): DbSet<T>

Defined in: src/set/DbSet.ts:309

Applies pessimistic row locking (e.g. FOR UPDATE or WITH (UPDLOCK, ROWLOCK)). Ensures rows selected cannot be modified by concurrent transactions until this transaction commits. Essential for inventory reservation, financial records, and high-contention row updates.

Parameters​

ParameterTypeDescription
options?{ noWait?: boolean; skipLocked?: boolean; }Optional lock modifiers: - noWait: Throw immediately if row is locked rather than waiting. - skipLocked: Skip locked rows (useful for worker queue polling).
options.noWait?boolean-
options.skipLocked?boolean-

Returns​

DbSet<T>

A new cloned DbSet configured with row locking.

Example​

await db.useTransaction(async (tx) => {
const account = await db.accounts.inTransaction(tx)
.where({ id: 101 })
.forUpdate()
.firstOrThrow();
});

forShare()​

forShare(): DbSet<T>

Defined in: src/set/DbSet.ts:320

Applies shared read locking (e.g. FOR SHARE / LOCK IN SHARE MODE / WITH (HOLDLOCK)).

Returns​

DbSet<T>

A new cloned DbSet configured with shared locking.


forUpdateNoWait()​

forUpdateNoWait(): DbSet<T>

Defined in: src/set/DbSet.ts:331

Applies exclusive row locking with NOWAIT (fails immediately if rows are locked).

Returns​

DbSet<T>

A new cloned DbSet configured with row locking.


forUpdateSkipLocked()​

forUpdateSkipLocked(): DbSet<T>

Defined in: src/set/DbSet.ts:342

Applies exclusive row locking skipping already locked rows (ideal for queue workers).

Returns​

DbSet<T>

A new cloned DbSet configured with row locking.


withLock()​

withLock(mode): DbSet<T>

Defined in: src/set/DbSet.ts:354

Fluent helper to set locking strategy explicitly.

Parameters​

ParameterTypeDescription
mode"exclusive" | "shared" | "no-wait" | "skip-locked"Lock strategy: 'exclusive'

Returns​

DbSet<T>

A new cloned DbSet configured with row locking.


lock()​

lock(mode): DbSet<T>

Defined in: src/set/DbSet.ts:392

Applies a pessimistic row lock using a human-readable lock mode string.

This is a semantic alias over forUpdate(), forShare(), etc., providing a clean and unified API for all locking strategies across dialects.

modeSQL emitted (PostgreSQL)SQL emitted (MSSQL)
'pessimistic'FOR UPDATEWITH (UPDLOCK, ROWLOCK, HOLDLOCK)
'shared'FOR SHAREWITH (HOLDLOCK, ROWLOCK)
'no-wait'FOR UPDATE NOWAITWITH (UPDLOCK, ROWLOCK, NOWAIT)
'skip-locked'FOR UPDATE SKIP LOCKEDWITH (UPDLOCK, ROWLOCK, READPAST)
'optimistic'(no SQL modifier — handled via @Version)

Parameters​

ParameterTypeDescription
mode"shared" | "no-wait" | "skip-locked" | "pessimistic" | "optimistic"Lock strategy to apply.

Returns​

DbSet<T>

A new cloned DbSet with the specified row lock applied.

Example​

// Prevent concurrent updates to an account during a balance transfer
await db.useTransaction(async (tx) => {
const account = await db.accounts
.inTransaction(tx)
.where({ id: accountId })
.lock('pessimistic')
.firstOrThrow();

await db.accounts.inTransaction(tx).update(account.id, {
balance: account.balance - transferAmount,
});
});

cache()​

cache(ttlMs?, cacheKey?): DbSet<T>

Defined in: src/set/DbSet.ts:422

Caches the result of this query in the registered query cache provider (e.g., Redis or in-memory) for the given TTL.

Parameters​

ParameterTypeDefault valueDescription
ttlMsnumber60000Time-to-live in milliseconds (defaults to 60,000ms / 1 minute).
cacheKey?stringundefinedOptional custom key string. If omitted, an MD5/hash of SQL + parameters is auto-generated.

Returns​

DbSet<T>

A new cloned DbSet configured with caching options.

Usecase​

Use this for high-read, low-write lookup tables (like system settings or product categories) to reduce database load.

Example​

// Cache product catalog results for 5 minutes
const products = await context.products.cache(300000, 'active_products').toList();

invalidateCache()​

invalidateCache(cacheKey?): Promise<void>

Defined in: src/set/DbSet.ts:437

Invalidates and clears query cache entries matching a specific key, or clears the entire cache if no key is supplied.

Parameters​

ParameterTypeDescription
cacheKey?stringOptional specific cache key to remove. If omitted, the entire query cache is purged.

Returns​

Promise<void>

Usecase​

Use this after an update or delete mutation to invalidate stale cached lists.

Example​

await context.products.update(productId, { price: 19.99 });
await context.products.invalidateCache('active_products');

include()​

Call Signature​

include<V>(navigationProperty): DbSet<T>

Defined in: src/set/DbSet.ts:459

Eagerly loads related navigation properties (@HasMany, @HasOne, @BelongsTo) in a single efficient batch using a lambda selector.

Type Parameters​
Type Parameter
V
Parameters​
ParameterTypeDescription
navigationProperty(entity) => VProperty accessor lambda (e.g. u => u.posts).
Returns​

DbSet<T>

A new cloned DbSet configured to eager load the specified navigation property.

Usecase​

Prevent the N+1 query problem by loading parent-child relationships upfront with compile-time type safety.

Example​
const users = await context.users.include(u => u.posts).toList();

Call Signature​

include<K>(navigationProperty, enabled?): DbSet<WithLoaded<T, K>>

Defined in: src/set/DbSet.ts:467

Eagerly loads related navigation properties using a relation property name.

Type Parameters​
Type ParameterDefault type
K extends stringColumnKey<T>
Parameters​
ParameterTypeDescription
navigationPropertyKRelation property name or dot-nested path.
enabled?booleanOptional boolean flag (defaults to true). If false, inclusion is skipped.
Returns​

DbSet<WithLoaded<T, K>>

A new cloned DbSet configured to eager load the specified navigation property.


thenInclude()​

thenInclude(navigationProperty): DbSet<T>

Defined in: src/set/DbSet.ts:507

Eagerly loads a nested relationship following a preceding .include().

Parameters​

ParameterTypeDescription
navigationPropertystring | ((entity) => unknown)Property accessor lambda or relation property name on the child entity.

Returns​

DbSet<T>

A new cloned DbSet configured to eager load the nested relation.

Usecase​

Load multi-level relationships (e.g. User -> Posts -> Comments).

Example​

const feed = await context.users
.include(u => u.posts)
.thenInclude((p: any) => p.comments)
.toList();

fetchRelation()​

fetchRelation<R>(entity, relationName): Promise<R>

Defined in: src/set/DbSet.ts:532

Programmatically fetches and hydrates an unpopulated relation on an existing entity.

Type Parameters​

Type ParameterDefault type
Rany

Parameters​

ParameterTypeDescription
entityTThe parent entity instance.
relationNamestringName of the navigation property to resolve.

Returns​

Promise<R>


loadRelation()​

loadRelation<R>(entity, relationName): Promise<R>

Defined in: src/set/DbSet.ts:544

Alias for fetchRelation.

Type Parameters​

Type ParameterDefault type
Rany

Parameters​

ParameterType
entityT
relationNamestring

Returns​

Promise<R>


select()​

select<K>(...fields): DbSet<Pick<T, K>>

Defined in: src/set/DbSet.ts:564

Projects only specific columns/properties from the table into a typed partial entity result.

Type Parameters​

Type Parameter
K extends string | number | symbol

Parameters​

ParameterTypeDescription
...fieldsK[]Names of the entity properties to include in the SELECT clause.

Returns​

DbSet<Pick<T, K>>

A new DbSet typed with only the selected fields (Pick<T, K>).

Usecase​

Use this to minimize network bandwidth and database memory overhead by querying only the columns your view requires.

Example​

// Select only id, name, and email for a lightweight dropdown list
const summaries = await context.users
.select('id', 'name', 'email')
.toList();

where()​

Call Signature​

where<K>(column, operator, value): DbSet<T>

Defined in: src/set/DbSet.ts:594

Filters records using a column comparison (column, operator, value).

Type Parameters​
Type Parameter
K extends string
Parameters​
ParameterTypeDescription
columnK | ((entity) => unknown)The column name or entity property key.
operator"=" | "!=" | "<>" | ">" | ">=" | "<" | "<=" | "LIKE" | "NOT LIKE" | "IN" | "NOT IN" | "ILIKE"Relational operator (=, !=, <, >, LIKE, IN, etc.).
valueanyComparison value.
Returns​

DbSet<T>

A new cloned DbSet with the filter condition applied.

Usecase​

Filter records using standard relational comparison operators.

Example​
const activeAdmins = await context.users
.where('role', '=', 'admin')
.toList();

Call Signature​

where(column, operator, value): DbSet<T>

Defined in: src/set/DbSet.ts:600

Filters records using a column comparison (column, operator, value).

Parameters​
ParameterTypeDescription
columnstring | ((entity) => unknown)The column name or entity property key.
operator"=" | "!=" | "<>" | ">" | ">=" | "<" | "<=" | "LIKE" | "NOT LIKE" | "IN" | "NOT IN" | "ILIKE"Relational operator (=, !=, <, >, LIKE, IN, etc.).
valueanyComparison value.
Returns​

DbSet<T>

A new cloned DbSet with the filter condition applied.

Usecase​

Filter records using standard relational comparison operators.

Example​
const activeAdmins = await context.users
.where('role', '=', 'admin')
.toList();

Call Signature​

where(predicate): DbSet<T>

Defined in: src/set/DbSet.ts:611

Filters records using an object of property-value pairs (equality, IN arrays, or IS NULL).

Parameters​
ParameterTypeDescription
predicatePartial<T>An object with entity keys and expected values.
Returns​

DbSet<T>

Call Signature​

where(fn): DbSet<T>

Defined in: src/set/DbSet.ts:617

Filters records using a fluent WhereClause builder callback.

Parameters​
ParameterTypeDescription
fn(clause) => boolean | void | WhereClause<T>Callback receiving a WhereClause builder or entity predicate (entity: T) => boolean.
Returns​

DbSet<T>

Call Signature​

where(...conditions): DbSet<T>

Defined in: src/set/DbSet.ts:618

Filters records using a column comparison (column, operator, value).

Parameters​
ParameterType
...conditions(Partial<T> | ((clause) => boolean | void | WhereClause<T>))[]
Returns​

DbSet<T>

A new cloned DbSet with the filter condition applied.

Usecase​

Filter records using standard relational comparison operators.

Example​
const activeAdmins = await context.users
.where('role', '=', 'admin')
.toList();

whereRaw()​

whereRaw(sql, params?): DbSet<T>

Defined in: src/set/DbSet.ts:694

Injects a raw SQL WHERE condition with parameterized values for advanced provider-specific expressions.

Parameters​

ParameterTypeDescription
sqlstringRaw SQL expression to append to WHERE (use parameter placeholders, e.g. p0, ?).
params?unknown[]Optional array of parameter values to bind safely against SQL injection.

Returns​

DbSet<T>

A new cloned DbSet with the raw condition appended.

Usecase​

Use this for vendor-specific SQL functions, spatial queries, or complex math calculations not expressible via standard operators.

Example​

const nearbyStores = await context.stores
.whereRaw('ST_Distance(location, ST_Point(@p0, @p1)) < 5000', [lng, lat])
.toList();

withCte()​

withCte(name, query, recursive?): DbSet<T>

Defined in: src/set/DbSet.ts:707

Adds a Common Table Expression (WITH clause) to the query.

Parameters​

ParameterTypeDefault valueDescription
namestringundefinedThe CTE identifier name.
querystring | QueryBuilder<any> | Subquery<any> | DbSet<any> | ((qb) => any)undefinedThe query or subquery defining the CTE.
recursivebooleanfalseWhether the CTE is RECURSIVE.

Returns​

DbSet<T>


asSubquery()​

asSubquery(alias): Subquery<T>

Defined in: src/set/DbSet.ts:724

Converts this DbSet query into an aliased Subquery.

Parameters​

ParameterTypeDescription
aliasstringAlias for referencing this subquery.

Returns​

Subquery<T>


whereExists()​

whereExists(subquery, joinPredicate?): DbSet<T>

Defined in: src/set/DbSet.ts:734

Adds an SQL EXISTS subquery condition.

Parameters​

ParameterTypeDescription
subqueryanySubquery, DbSet, QueryBuilder, or SQL string.
joinPredicate?(outer, inner) => voidCallback defining join predicate between outer entity and subquery.

Returns​

DbSet<T>


whereNotExists()​

whereNotExists(subquery, joinPredicate?): DbSet<T>

Defined in: src/set/DbSet.ts:746

Adds an SQL NOT EXISTS subquery condition.

Parameters​

ParameterTypeDescription
subqueryanySubquery, DbSet, QueryBuilder, or SQL string.
joinPredicate?(outer, inner) => voidCallback defining join predicate between outer entity and subquery.

Returns​

DbSet<T>


nearest()​

nearest(column, vector, options?): DbSet<T>

Defined in: src/set/DbSet.ts:759

Performs semantic / vector distance search on an embedding column using pgvector operators.

Parameters​

ParameterTypeDescription
columnstring | keyof TVector column or property name.
vectornumber[]Query embedding coordinates array.
options?NearestOptionsDistance metric ('cosine', 'l2', 'inner_product') and limit.

Returns​

DbSet<T>


whereJson()​

whereJson(column, path, operatorOrValue, value?): DbSet<T>

Defined in: src/set/DbSet.ts:782

Queries inside a JSON or JSONB column using dialect-specific extraction operators.

Parameters​

ParameterTypeDescription
columnColumnKey<T>The property or column holding the JSON payload.
pathstringJSON property path (e.g., 'address.city' or 'tier').
operatorOrValueunknownComparison operator ('=', '>', etc.) or direct value when testing for equality.
value?unknownTarget value to compare against when an explicit operator is provided.

Returns​

DbSet<T>

A new cloned DbSet with the JSON filter condition applied.

Usecase​

Use this to filter documents or flexible schema attributes stored inside JSON columns (e.g. metadata, settings, tags).

Example​

const goldUsers = await context.users
.whereJson('metadata', 'tier', '=', 'gold')
.toList();

whereSearch()​

whereSearch(columns, query, options?): DbSet<T>

Defined in: src/set/DbSet.ts:809

Applies a native full-text search condition across one or more columns with dialect-specific fallback.

Parameters​

ParameterTypeDescription
columns(ColumnKey<T> | ((entity) => unknown))[]Array of property names or property accessor functions to search within.
querystringThe search query term or phrase.
options?SearchOptionsOptional search options (e.g. language, prefix matching).

Returns​

DbSet<T>

A new cloned DbSet with full-text search filtering applied.

Usecase​

Use this to implement search bars, catalog searches, or document matching across multiple text fields.

Example​

const searchResults = await context.products
.whereSearch(['title', 'description'], 'wireless headphones')
.toList();

whereBetween()​

whereBetween<K>(field, range): DbSet<T>

Defined in: src/set/DbSet.ts:837

Filters records where a column value falls within an inclusive range [lower, upper].

Type Parameters​

Type Parameter
K extends string

Parameters​

ParameterTypeDescription
fieldK | ((entity) => unknown)Property accessor lambda or property name key.
range[unknown, unknown]Tuple containing [lowerBound, upperBound].

Returns​

DbSet<T>

A new cloned DbSet with the range condition applied.

Usecase​

Query date intervals, price ranges, age brackets, or numerical ranges directly.

Example​

const q = await context.orders
.whereBetween('createdAt', [startDate, endDate])
.toList();

whereIn()​

whereIn<K>(field, values): DbSet<T>

Defined in: src/set/DbSet.ts:860

Filters records where a column value matches any value in the provided array (IN (...)).

Type Parameters​

Type Parameter
K extends string

Parameters​

ParameterTypeDescription
fieldK | ((entity) => unknown)Property accessor lambda or property name key.
valuesunknown[]Array of matching values.

Returns​

DbSet<T>

A new cloned DbSet with the IN filter applied.

Usecase​

Query items matching multiple IDs, statuses, or category codes without raw callbacks.

Example​

const orders = await context.orders.whereIn('status', ['paid', 'shipped']).toList();

whereNotIn()​

whereNotIn<K>(field, values): DbSet<T>

Defined in: src/set/DbSet.ts:879

Filters records where a column value does NOT match any value in the provided array (NOT IN (...)).

Type Parameters​

Type Parameter
K extends string

Parameters​

ParameterTypeDescription
fieldK | ((entity) => unknown)Property accessor lambda or property name key.
valuesunknown[]Array of values to exclude.

Returns​

DbSet<T>

A new cloned DbSet with the NOT IN filter applied.

Usecase​

Exclude specific record IDs, statuses, or categories.


whereLike()​

whereLike<K>(field, pattern): DbSet<T>

Defined in: src/set/DbSet.ts:898

Filters records matching a SQL LIKE pattern (e.g. '%example.com').

Type Parameters​

Type Parameter
K extends string

Parameters​

ParameterTypeDescription
fieldK | ((entity) => unknown)Property accessor lambda or property name key.
patternstringPattern with SQL % or _ wildcards.

Returns​

DbSet<T>

A new cloned DbSet with the LIKE filter applied.

Usecase​

Simple prefix, suffix, or substring pattern searches.


whereNotLike()​

whereNotLike<K>(field, pattern): DbSet<T>

Defined in: src/set/DbSet.ts:912

Filters records NOT matching a SQL NOT LIKE pattern.

Type Parameters​

Type Parameter
K extends string

Parameters​

ParameterType
fieldK | ((entity) => unknown)
patternstring

Returns​

DbSet<T>


whereNull()​

whereNull<K>(field): DbSet<T>

Defined in: src/set/DbSet.ts:926

Filters records where a column value is NULL.

Type Parameters​

Type Parameter
K extends string

Parameters​

ParameterType
fieldK | ((entity) => unknown)

Returns​

DbSet<T>


whereNotNull()​

whereNotNull<K>(field): DbSet<T>

Defined in: src/set/DbSet.ts:937

Filters records where a column value is NOT NULL.

Type Parameters​

Type Parameter
K extends string

Parameters​

ParameterType
fieldK | ((entity) => unknown)

Returns​

DbSet<T>


orderBy()​

Call Signature​

orderBy<V>(field, direction?): DbSet<T>

Defined in: src/set/DbSet.ts:961

Sorts the query results by a property or column in ascending or descending order.

Type Parameters​
Type Parameter
V
Parameters​
ParameterTypeDescription
field(entity) => VProperty accessor lambda or property name key.
direction?"desc" | "asc"Sort direction: 'asc' (default) or 'desc'.
Returns​

DbSet<T>

A new cloned DbSet with the sort order applied.

Usecase​

Use this to order lists chronologically, alphabetically, or by numerical ranking.

Example​
const users = await context.users
.orderBy(u => u.createdAt, 'desc')
.toList();

Call Signature​

orderBy<K>(field, direction?): DbSet<T>

Defined in: src/set/DbSet.ts:962

Sorts the query results by a property or column in ascending or descending order.

Type Parameters​
Type Parameter
K extends string
Parameters​
ParameterTypeDescription
fieldKProperty accessor lambda or property name key.
direction?"desc" | "asc"Sort direction: 'asc' (default) or 'desc'.
Returns​

DbSet<T>

A new cloned DbSet with the sort order applied.

Usecase​

Use this to order lists chronologically, alphabetically, or by numerical ranking.

Example​
const users = await context.users
.orderBy(u => u.createdAt, 'desc')
.toList();

Call Signature​

orderBy(field, direction?): DbSet<T>

Defined in: src/set/DbSet.ts:963

Sorts the query results by a property or column in ascending or descending order.

Parameters​
ParameterTypeDescription
fieldstring & objectProperty accessor lambda or property name key.
direction?"desc" | "asc"Sort direction: 'asc' (default) or 'desc'.
Returns​

DbSet<T>

A new cloned DbSet with the sort order applied.

Usecase​

Use this to order lists chronologically, alphabetically, or by numerical ranking.

Example​
const users = await context.users
.orderBy(u => u.createdAt, 'desc')
.toList();

orderByDescending()​

Call Signature​

orderByDescending<V>(field): DbSet<T>

Defined in: src/set/DbSet.ts:987

Sorts the query results by a property or column in descending order (highest/newest first).

Type Parameters​
Type Parameter
V
Parameters​
ParameterTypeDescription
field(entity) => VProperty accessor lambda or property name key.
Returns​

DbSet<T>

A new cloned DbSet sorted in descending order.

Usecase​

Convenience method to sort by newest created records or highest prices/scores.

Example​
const topScores = await context.players
.orderByDescending(p => p.score)
.toList();

Call Signature​

orderByDescending<K>(field): DbSet<T>

Defined in: src/set/DbSet.ts:988

Sorts the query results by a property or column in descending order (highest/newest first).

Type Parameters​
Type Parameter
K extends string
Parameters​
ParameterTypeDescription
fieldKProperty accessor lambda or property name key.
Returns​

DbSet<T>

A new cloned DbSet sorted in descending order.

Usecase​

Convenience method to sort by newest created records or highest prices/scores.

Example​
const topScores = await context.players
.orderByDescending(p => p.score)
.toList();

Call Signature​

orderByDescending(field): DbSet<T>

Defined in: src/set/DbSet.ts:989

Sorts the query results by a property or column in descending order (highest/newest first).

Parameters​
ParameterTypeDescription
fieldstring & objectProperty accessor lambda or property name key.
Returns​

DbSet<T>

A new cloned DbSet sorted in descending order.

Usecase​

Convenience method to sort by newest created records or highest prices/scores.

Example​
const topScores = await context.players
.orderByDescending(p => p.score)
.toList();

thenBy()​

Call Signature​

thenBy<V>(field, direction?): DbSet<T>

Defined in: src/set/DbSet.ts:1009

Adds a secondary sorting criteria after an initial orderBy or orderByDescending.

Type Parameters​
Type Parameter
V
Parameters​
ParameterTypeDescription
field(entity) => VProperty accessor lambda or property name key.
direction?"desc" | "asc"Sort direction: 'asc' (default) or 'desc'.
Returns​

DbSet<T>

A new cloned DbSet with secondary sorting criteria added.

Usecase​

Use this to break ties in sorting, e.g. sort by category ascending, then by price descending.

Example​
const products = await context.products
.orderBy('category', 'asc')
.thenBy('price', 'desc')
.toList();

Call Signature​

thenBy<K>(field, direction?): DbSet<T>

Defined in: src/set/DbSet.ts:1010

Adds a secondary sorting criteria after an initial orderBy or orderByDescending.

Type Parameters​
Type Parameter
K extends string
Parameters​
ParameterTypeDescription
fieldKProperty accessor lambda or property name key.
direction?"desc" | "asc"Sort direction: 'asc' (default) or 'desc'.
Returns​

DbSet<T>

A new cloned DbSet with secondary sorting criteria added.

Usecase​

Use this to break ties in sorting, e.g. sort by category ascending, then by price descending.

Example​
const products = await context.products
.orderBy('category', 'asc')
.thenBy('price', 'desc')
.toList();

Call Signature​

thenBy(field, direction?): DbSet<T>

Defined in: src/set/DbSet.ts:1011

Adds a secondary sorting criteria after an initial orderBy or orderByDescending.

Parameters​
ParameterTypeDescription
fieldstring & objectProperty accessor lambda or property name key.
direction?"desc" | "asc"Sort direction: 'asc' (default) or 'desc'.
Returns​

DbSet<T>

A new cloned DbSet with secondary sorting criteria added.

Usecase​

Use this to break ties in sorting, e.g. sort by category ascending, then by price descending.

Example​
const products = await context.products
.orderBy('category', 'asc')
.thenBy('price', 'desc')
.toList();

thenByDescending()​

Call Signature​

thenByDescending<V>(field): DbSet<T>

Defined in: src/set/DbSet.ts:1019

Type Parameters​
Type Parameter
V
Parameters​
ParameterType
field(entity) => V
Returns​

DbSet<T>

Call Signature​

thenByDescending<K>(field): DbSet<T>

Defined in: src/set/DbSet.ts:1020

Type Parameters​
Type Parameter
K extends string
Parameters​
ParameterType
fieldK
Returns​

DbSet<T>

Call Signature​

thenByDescending(field): DbSet<T>

Defined in: src/set/DbSet.ts:1021

Parameters​
ParameterType
fieldstring & object
Returns​

DbSet<T>


skip()​

skip(n): DbSet<T>

Defined in: src/set/DbSet.ts:1039

Skips the specified number of rows from the beginning of the result set.

Parameters​

ParameterTypeDescription
nnumberThe number of rows to skip.

Returns​

DbSet<T>

A new cloned DbSet with the OFFSET clause set.

Usecase​

Use this together with .take() for offset-based pagination.

Example​

const page2 = await context.users.skip(20).take(10).toList();

take()​

take(n): DbSet<T>

Defined in: src/set/DbSet.ts:1056

Limits the number of rows returned by the query.

Parameters​

ParameterTypeDescription
nnumberThe maximum number of rows to return.

Returns​

DbSet<T>

A new cloned DbSet with the LIMIT clause set.

Usecase​

Use this to restrict result set size for top-N queries or pagination.

Example​

const topFive = await context.products.orderByDescending('sales').take(5).toList();

paginate()​

paginate(page, pageSize): DbSet<T>

Defined in: src/set/DbSet.ts:1074

Configures pagination using 1-based page numbers and page size.

Parameters​

ParameterTypeDescription
pagenumberThe 1-based page number (e.g. 1 for first page).
pageSizenumberNumber of items per page.

Returns​

DbSet<T>

A new cloned DbSet with appropriate skip and take applied.

Usecase​

Use this to cleanly paginate REST API endpoints with query parameters ?page=1&pageSize=20.

Example​

const items = await context.users.paginate(2, 25).toList();

tap()​

tap(fn): DbSet<T>

Defined in: src/set/DbSet.ts:1094

Executes a callback with the current DbSet instance for side-effects, debugging, or logging, without breaking the fluent query chain.

Parameters​

ParameterTypeDescription
fn(set) => voidInspection callback receiving this DbSet.

Returns​

DbSet<T>

The same DbSet instance.

Usecase​

Peek into query state, log intermediate SQL, or perform diagnostics mid-chain.

Example​

const users = await context.users
.where({ isActive: true })
.tap(set => console.log('Querying table:', set.getTableName()))
.orderBy('createdAt', 'desc')
.toList();

join()​

join<R>(target, on, type?, alias?): DbSet<T & Partial<R>>

Defined in: src/set/DbSet.ts:1117

Performs an SQL JOIN operation against another table or entity model.

Type Parameters​

Type Parameter
R extends object

Parameters​

ParameterTypeDefault valueDescription
targetEntityTarget<R>undefinedTarget entity class or table name to join with.
on{ left: ColumnKey<T>; right: ColumnKey<R>; }undefinedJoin key pairing { left: 'userId', right: 'id' }.
on.leftColumnKey<T>undefined-
on.rightColumnKey<R>undefined-
type?"INNER" | "LEFT" | "RIGHT" | "FULL"'INNER'Join type ('INNER', 'LEFT', 'RIGHT', or 'FULL'), defaults to 'INNER'.
alias?stringundefinedOptional SQL table alias for the joined entity.

Returns​

DbSet<T & Partial<R>>

A new DbSet representing the merged entity type T & Partial<R>.

Usecase​

Use this to query across related tables when eager loading or projection across boundaries is needed.

Example​

const userOrders = await context.users
.join(Order, { left: 'id', right: 'userId' }, 'INNER')
.toList();

leftJoin()​

leftJoin<R>(target, on, alias?): DbSet<T & Partial<R>>

Defined in: src/set/DbSet.ts:1166

Performs a LEFT OUTER JOIN operation against another table or entity model.

Type Parameters​

Type Parameter
R extends object

Parameters​

ParameterTypeDescription
targetEntityTarget<R>Target entity class or table name to join with.
on{ left: ColumnKey<T>; right: ColumnKey<R>; }Join key pairing { left: 'userId', right: 'id' }.
on.leftColumnKey<T>-
on.right?ColumnKey<R>-
alias?stringOptional SQL table alias.

Returns​

DbSet<T & Partial<R>>

A new DbSet representing the merged entity type T & Partial<R>.

Usecase​

Convenience method to retrieve all rows from the primary table even if no matching row exists in the joined table.

Example​

const usersWithProfiles = await context.users
.leftJoin(Profile, { left: 'id', right: 'userId' })
.toList();

toList()​

toList(): Promise<T[]>

Defined in: src/set/DbSet.ts:1186

Executes the constructed query and returns all matching entities as an array.

Returns​

Promise<T[]>

A Promise resolving to an array of entity instances.

Usecase​

Terminal execution method to retrieve results into memory, applying any soft-delete filters, query caching, and eager-loaded relations.

Example​

const activeUsers = await context.users.where({ isActive: true }).toList();

toArray()​

toArray(): Promise<T[]>

Defined in: src/set/DbSet.ts:1241

Alias for toList() for developers accustomed to array-oriented method names.

Returns​

Promise<T[]>

A Promise resolving to an array of entity instances.

Usecase​

Retrieve all matching entities as an array.


toMap()​

toMap<K>(keySelector): Promise<Map<K, T>>

Defined in: src/set/DbSet.ts:1257

Executes the query and transforms the results into a JavaScript Map<K, T> keyed by the specified selector.

Type Parameters​

Type Parameter
K

Parameters​

ParameterTypeDescription
keySelector(entity) => KFunction returning the key to use for each item in the map.

Returns​

Promise<Map<K, T>>

A Promise resolving to a Map where each entry maps a key to its corresponding entity.

Usecase​

Perform O(1) in-memory lookups by ID or unique key without writing manual .reduce() loops.

Example​

const userMap = await context.users.where({ isActive: true }).toMap(u => u.id);
const user = userMap.get(42);

selectAs()​

selectAs<TDto>(mapFn): Promise<TDto[]>

Defined in: src/set/DbSet.ts:1279

Projects each entity in the query result into a custom DTO or mapped shape in a type-safe manner.

Type Parameters​

Type Parameter
TDto

Parameters​

ParameterTypeDescription
mapFn(entity) => TDtoMapping function transforming each entity T to TDto.

Returns​

Promise<TDto[]>

A Promise resolving to an array of mapped TDto objects.

Usecase​

Retrieve and map entities directly into API response models or lightweight view models.

Example​

const summaries = await context.users
.where({ isActive: true })
.selectAs(u => ({ id: u.id, displayName: `${u.firstName} ${u.lastName}` }));

selectWindow()​

selectWindow(fn): DbSet<T>

Defined in: src/set/DbSet.ts:1287

Adds a window function projection to the query builder.

Parameters​

ParameterType
fn(w) => WindowFunctionExpression

Returns​

DbSet<T>


toSql()​

toSql(): string

Defined in: src/set/DbSet.ts:1300

Compiles and returns the generated SQL statement for this query.

Returns​

string


toSelectSql()​

toSelectSql(): object

Defined in: src/set/DbSet.ts:1307

Compiles and returns the SQL and parameter bindings for this query.

Returns​

object

NameTypeDefined in
sqlstringsrc/set/DbSet.ts:1307
paramsany[]src/set/DbSet.ts:1307

chunk()​

chunk(size, callback): Promise<number>

Defined in: src/set/DbSet.ts:1325

Processes large datasets in manageable batches (chunks) using sequential paging, avoiding memory exhaustion.

Parameters​

ParameterTypeDescription
sizenumberThe number of records to fetch and process in each batch.
callback(batch, index) => boolean | void | Promise<boolean | void>Async function executed for each batch of items.

Returns​

Promise<number>

Usecase​

Ideal for background jobs, data migrations, ETL pipelines, or bulk notifications.

Example​

await context.orders.where({ status: 'pending' }).chunk(500, async (batch, pageIndex) => {
console.log(`Processing batch #${pageIndex} with ${batch.length} items`);
await notifyWarehouse(batch);
});

stream()​

stream(batchSize?): AsyncGenerator<T>

Defined in: src/set/DbSet.ts:1375

Returns an async iterable stream yielding entities row by row in configurable batch sizes.

Parameters​

ParameterTypeDefault valueDescription
batchSizenumber100Batch size for underlying chunk fetching (default: 100).

Returns​

AsyncGenerator<T>

An AsyncIterable<T> compatible with for await (const entity of set.stream()).

Usecase​

Process large datasets, CSV exports, or background streams with minimal memory overhead.

Example​

for await (const user of context.users.where({ isActive: true }).stream(250)) {
await processUser(user);
}

[asyncIterator]()​

[asyncIterator](): AsyncGenerator<T>

Defined in: src/set/DbSet.ts:1408

Allows direct async iteration over the DbSet (for await (const entity of set)).

Returns​

AsyncGenerator<T>


toPagedList()​

toPagedList(pageOrOptions, maybePageSize?): Promise<PagedResult<T>>

Defined in: src/set/DbSet.ts:1425

Executes a paginated query returning both the page of items and comprehensive pagination metadata (totalCount, totalPages, hasNext, hasPrevious).

Parameters​

ParameterTypeDescription
pageOrOptionsnumber | PagedListOptionsThe 1-based page number or a PagedListOptions object.
maybePageSize?numberNumber of items per page if first argument is a number.

Returns​

Promise<PagedResult<T>>

A Promise resolving to PagedResult<T> containing items, totalCount, totalPages, etc.

Usecase​

Use this in data tables, UI grids, and search endpoints where total record counts and page controls are required.

Example​

const page = await context.products.where({ isActive: true }).toPagedList(1, 10);
console.log(`Showing ${page.items.length} of ${page.totalCount} products across ${page.totalPages} pages`);

toCursorPage()​

toCursorPage(options): Promise<CursorPageResult<T>>

Defined in: src/set/DbSet.ts:1477

Executes keyset (cursor-based) pagination with constant O(1) row navigation and zero offset performance degradation.

Parameters​

ParameterTypeDescription
optionsCursorPaginationOptions<T>Pagination options specifying cursor, limit, orderBy column, and tie-breaker column.

Returns​

Promise<CursorPageResult<T>>

A Promise resolving to CursorPageResult<T> containing items, nextCursor, and navigation flags.

Usecase​

Ideal for infinite scroll feeds, real-time activity timelines, and large data export pipelines where offset pagination gets slow.

Example​

const page = await context.posts.toCursorPage({
limit: 20,
orderBy: 'createdAt',
direction: 'desc',
cursor: req.query.cursor as string,
});

first()​

first(predicate?): Promise<T | null>

Defined in: src/set/DbSet.ts:1588

Finds the first entity matching the criteria or returns null if no match is found.

Parameters​

ParameterTypeDescription
predicate?LinqPredicate<T>Optional filter object to narrow the search.

Returns​

Promise<T | null>

A Promise resolving to the first matching entity or null.

Usecase​

Use this when a record might not exist and you want to handle null gracefully without exception handling.

Example​

const user = await context.users.first({ email: 'user@example.com' });
if (!user) {
// handle unregistered user
}

firstOrDefault()​

firstOrDefault(predicate?): Promise<T | null>

Defined in: src/set/DbSet.ts:1602

Finds the first entity matching the criteria or returns null if none found. Alias for first().

Parameters​

ParameterType
predicate?LinqPredicate<T>

Returns​

Promise<T | null>


firstOrThrow()​

firstOrThrow(predicate?): Promise<T>

Defined in: src/set/DbSet.ts:1618

Finds the first entity matching the criteria, or throws EntityNotFoundException if none exists.

Parameters​

ParameterTypeDescription
predicate?LinqPredicate<T>Optional filter object to narrow the search.

Returns​

Promise<T>

A Promise resolving to the first matching entity.

Usecase​

Use this in HTTP handlers or service methods where an entity must exist (e.g. GET /users/:id), letting your error middleware handle 404 responses.

Throws​

EntityNotFoundException when no matching record is found.

Example​

const user = await context.users.firstOrThrow({ email });

single()​

single(predicate?): Promise<T | null>

Defined in: src/set/DbSet.ts:1638

Asserts that at most one entity matches the query and returns it, or returns null if empty.

Parameters​

ParameterTypeDescription
predicate?LinqPredicate<T>Optional filter object.

Returns​

Promise<T | null>

The single matching entity or null.

Usecase​

Use this when you expect a unique record and want to detect accidental duplicate records in the database.

Throws​

DbException if more than one record matches the condition.

Example​

const uniqueSetting = await context.settings.single({ key: 'site_name' });

singleOrDefault()​

singleOrDefault(predicate?): Promise<T | null>

Defined in: src/set/DbSet.ts:1661

Asserts that at most one entity matches the criteria and returns it, or returns null if none found. Alias for single().

Parameters​

ParameterTypeDescription
predicate?LinqPredicate<T>Filter criteria object, WhereClause builder callback, or lambda predicate.

Returns​

Promise<T | null>

The single matching entity or null.


singleOrThrow()​

singleOrThrow(predicate?): Promise<T>

Defined in: src/set/DbSet.ts:1678

Asserts that exactly one entity matches the query and returns it.

Parameters​

ParameterTypeDescription
predicate?LinqPredicate<T>Optional filter object.

Returns​

Promise<T>

The single matching entity.

Usecase​

Use this when a unique record is strictly expected; throws if not found or if duplicates exist.

Throws​

EntityNotFoundException if no record is found.

Throws​

DbException if more than one record is found.

Example​

const account = await context.accounts.singleOrThrow({ accountNumber: 'ACC-12345' });

find()​

find(id): Promise<T | null>

Defined in: src/set/DbSet.ts:1702

Looks up an entity by its primary key value or returns null if not found.

Parameters​

ParameterTypeDescription
idunknownThe primary key value (e.g. number, string, or UUID).

Returns​

Promise<T | null>

A Promise resolving to the entity instance or null.

Usecase​

Fast, direct primary key lookup across any supported database engine (PostgreSQL, MySQL, SQLite, MSSQL, Neon, Turso).

Example​

PostgreSQL / MySQL / SQLite / MSSQL:

const user = await context.users.find(10);
if (user) {
console.log('Found user:', user.name);
}

findOrThrow()​

findOrThrow(id): Promise<T>

Defined in: src/set/DbSet.ts:1720

Looks up an entity by its primary key value or throws EntityNotFoundException if it does not exist.

Parameters​

ParameterTypeDescription
idunknownThe primary key value.

Returns​

Promise<T>

A Promise resolving to the matching entity instance.

Usecase​

Standard lookup for API controller show/edit endpoints where a missing entity should trigger a 404 response.

Throws​

EntityNotFoundException if no entity with the given primary key exists.

Example​

const user = await context.users.findOrThrow(req.params.id);

count()​

Call Signature​

count(): Promise<number>

Defined in: src/set/DbSet.ts:1735

Counts the total number of matching rows in the table.

Returns​

Promise<number>

A Promise resolving to the count as a number.

Usecase​

Total record counts for analytics, dashboards, and pagination calculations.

Example​
const total = await context.users.count();

Call Signature​

count(predicate): Promise<number>

Defined in: src/set/DbSet.ts:1745

Counts the total number of matching rows using an inline filter predicate.

Parameters​
ParameterTypeDescription
predicatePartial<T>Filter criteria object.
Returns​

Promise<number>

Example​
const activeAdmins = await context.users.count({ role: 'admin', isActive: true });

Call Signature​

count(fn): Promise<number>

Defined in: src/set/DbSet.ts:1755

Counts the total number of matching rows using a WhereClause builder callback.

Parameters​
ParameterTypeDescription
fn(clause) => void | WhereClause<T>Builder callback function.
Returns​

Promise<number>

Example​
const highSpenders = await context.orders.count(w => w.gt('total', 500));

Call Signature​

count(predicate?): Promise<number>

Defined in: src/set/DbSet.ts:1756

Counts the total number of matching rows in the table.

Parameters​
ParameterType
predicate?Partial<T> | ((clause) => void | WhereClause<T>)
Returns​

Promise<number>

A Promise resolving to the count as a number.

Usecase​

Total record counts for analytics, dashboards, and pagination calculations.

Example​
const total = await context.users.count();

sum()​

Call Signature​

sum(selector): Promise<number>

Defined in: src/set/DbSet.ts:1788

Computes the mathematical sum of a numeric column across matching rows.

Parameters​
ParameterTypeDescription
selector(entity) => numberProperty name key or property accessor function.
Returns​

Promise<number>

A Promise resolving to the aggregated sum as a number.

Usecase​

Use this for calculating revenue, total inventory quantities, or points totals.

Example​
const totalSales = await context.orders.where({ status: 'completed' }).sum('totalAmount');

Call Signature​

sum<K>(selector): Promise<number>

Defined in: src/set/DbSet.ts:1789

Computes the mathematical sum of a numeric column across matching rows.

Type Parameters​
Type Parameter
K extends string
Parameters​
ParameterTypeDescription
selectorKProperty name key or property accessor function.
Returns​

Promise<number>

A Promise resolving to the aggregated sum as a number.

Usecase​

Use this for calculating revenue, total inventory quantities, or points totals.

Example​
const totalSales = await context.orders.where({ status: 'completed' }).sum('totalAmount');

Call Signature​

sum(selector): Promise<number>

Defined in: src/set/DbSet.ts:1790

Computes the mathematical sum of a numeric column across matching rows.

Parameters​
ParameterTypeDescription
selectorstring & objectProperty name key or property accessor function.
Returns​

Promise<number>

A Promise resolving to the aggregated sum as a number.

Usecase​

Use this for calculating revenue, total inventory quantities, or points totals.

Example​
const totalSales = await context.orders.where({ status: 'completed' }).sum('totalAmount');

avg()​

Call Signature​

avg(selector): Promise<number>

Defined in: src/set/DbSet.ts:1811

Computes the mathematical average of a numeric column across matching rows.

Parameters​
ParameterTypeDescription
selector(entity) => numberProperty name key or property accessor function.
Returns​

Promise<number>

A Promise resolving to the average value as a number.

Usecase​

Use this for calculating average ratings, average order values, or performance metrics.

Example​
const avgRating = await context.reviews.avg(r => r.rating);

Call Signature​

avg<K>(selector): Promise<number>

Defined in: src/set/DbSet.ts:1812

Computes the mathematical average of a numeric column across matching rows.

Type Parameters​
Type Parameter
K extends string
Parameters​
ParameterTypeDescription
selectorKProperty name key or property accessor function.
Returns​

Promise<number>

A Promise resolving to the average value as a number.

Usecase​

Use this for calculating average ratings, average order values, or performance metrics.

Example​
const avgRating = await context.reviews.avg(r => r.rating);

Call Signature​

avg(selector): Promise<number>

Defined in: src/set/DbSet.ts:1813

Computes the mathematical average of a numeric column across matching rows.

Parameters​
ParameterTypeDescription
selectorstring & objectProperty name key or property accessor function.
Returns​

Promise<number>

A Promise resolving to the average value as a number.

Usecase​

Use this for calculating average ratings, average order values, or performance metrics.

Example​
const avgRating = await context.reviews.avg(r => r.rating);

min()​

Call Signature​

min<R>(selector): Promise<R>

Defined in: src/set/DbSet.ts:1834

Determines the minimum value of a column across matching rows.

Type Parameters​
Type ParameterDefault type
Runknown
Parameters​
ParameterTypeDescription
selector(entity) => RProperty name key or property accessor function.
Returns​

Promise<R>

A Promise resolving to the minimum value.

Usecase​

Use this to find lowest product price, earliest event date, or minimum score.

Example​
const lowestPrice = await context.products.min('price');

Call Signature​

min<K>(selector): Promise<T[K]>

Defined in: src/set/DbSet.ts:1835

Determines the minimum value of a column across matching rows.

Type Parameters​
Type Parameter
K extends string
Parameters​
ParameterTypeDescription
selectorKProperty name key or property accessor function.
Returns​

Promise<T[K]>

A Promise resolving to the minimum value.

Usecase​

Use this to find lowest product price, earliest event date, or minimum score.

Example​
const lowestPrice = await context.products.min('price');

Call Signature​

min<R>(selector): Promise<R>

Defined in: src/set/DbSet.ts:1836

Determines the minimum value of a column across matching rows.

Type Parameters​
Type ParameterDefault type
Runknown
Parameters​
ParameterTypeDescription
selectorstring & objectProperty name key or property accessor function.
Returns​

Promise<R>

A Promise resolving to the minimum value.

Usecase​

Use this to find lowest product price, earliest event date, or minimum score.

Example​
const lowestPrice = await context.products.min('price');

max()​

Call Signature​

max<R>(selector): Promise<R>

Defined in: src/set/DbSet.ts:1856

Determines the maximum value of a column across matching rows.

Type Parameters​
Type ParameterDefault type
Runknown
Parameters​
ParameterTypeDescription
selector(entity) => RProperty name key or property accessor function.
Returns​

Promise<R>

A Promise resolving to the maximum value.

Usecase​

Use this to find highest product price, latest update timestamp, or top score.

Example​
const maxPrice = await context.products.max('price');

Call Signature​

max<K>(selector): Promise<T[K]>

Defined in: src/set/DbSet.ts:1857

Determines the maximum value of a column across matching rows.

Type Parameters​
Type Parameter
K extends string
Parameters​
ParameterTypeDescription
selectorKProperty name key or property accessor function.
Returns​

Promise<T[K]>

A Promise resolving to the maximum value.

Usecase​

Use this to find highest product price, latest update timestamp, or top score.

Example​
const maxPrice = await context.products.max('price');

Call Signature​

max<R>(selector): Promise<R>

Defined in: src/set/DbSet.ts:1858

Determines the maximum value of a column across matching rows.

Type Parameters​
Type ParameterDefault type
Runknown
Parameters​
ParameterTypeDescription
selectorstring & objectProperty name key or property accessor function.
Returns​

Promise<R>

A Promise resolving to the maximum value.

Usecase​

Use this to find highest product price, latest update timestamp, or top score.

Example​
const maxPrice = await context.products.max('price');

any()​

any(predicate?): Promise<boolean>

Defined in: src/set/DbSet.ts:1878

Checks whether any rows in the table match the optional criteria.

Parameters​

ParameterTypeDescription
predicate?LinqPredicate<T>Optional filter condition.

Returns​

Promise<boolean>

true if at least one matching row exists, otherwise false.

Usecase​

Use this to quickly verify existence of matching records before proceeding with dependent operations.

Example​

const hasOverdueInvoices = await context.invoices.any({ status: 'overdue' });

all()​

all(predicate): Promise<boolean>

Defined in: src/set/DbSet.ts:1898

Checks whether all rows in the table match the specified condition.

Parameters​

ParameterTypeDescription
predicateLinqPredicate<T>Filter condition that all rows must satisfy.

Returns​

Promise<boolean>

true if all rows match, otherwise false.

Usecase​

Use this for validation workflows to assert that all records satisfy a rule (e.g. all tasks in a project are completed).

Example​

const allPaid = await context.orders.all({ paymentStatus: 'paid' });
const allVerified = await context.users.all(u => u.isVerified === true);

groupBy()​

groupBy<TKey>(keySelector): GroupedQueryBuilder<T, TKey>

Defined in: src/set/DbSet.ts:1919

Groups rows by a key property selector for aggregate queries (COUNT, SUM, AVG).

Type Parameters​

Type Parameter
TKey

Parameters​

ParameterTypeDescription
keySelector(entity) => TKeyFunction returning the grouping property key.

Returns​

GroupedQueryBuilder<T, TKey>

A GroupedQueryBuilder instance supporting aggregate operations.

Usecase​

Use this for reporting and charts (e.g. count of users by country, sales sum by category).

Example​

const salesByCategory = await context.products
.groupBy(p => p.category)
.sum('price');

usePrimary()​

usePrimary(use?): DbSet<T>

Defined in: src/set/DbSet.ts:1943

Routes the query explicitly to the primary/write database connection instead of read-replicas.

Parameters​

ParameterTypeDefault valueDescription
usebooleantrueWhether to force primary connection routing (defaults to true).

Returns​

DbSet<T>

A new cloned DbSet configured to route through the primary database adapter.

Usecase​

Critical for read-after-write consistency to prevent replication lag anomalies immediately following a mutation.

Example​

await context.users.add(newUser);
// Immediately read from primary to ensure updated data is returned
const created = await context.users.usePrimary().first({ email: newUser.email });

distinct()​

distinct(distinct?): DbSet<T>

Defined in: src/set/DbSet.ts:1952

Applies the DISTINCT keyword to the generated query.

Parameters​

ParameterTypeDefault value
distinctbooleantrue

Returns​

DbSet<T>


asTracking()​

asTracking(): DbSet<T>

Defined in: src/set/DbSet.ts:1971

Enables change tracking for entities returned by this query. Property mutations on returned entities will be detected by the change tracker and persisted via context.saveChanges().

Returns​

DbSet<T>

A new cloned DbSet with change tracking enabled.

Usecase​

Query entities intended for interactive modification and unit-of-work persistence.

Example​

const users = await context.users.asTracking().where(u => u.isActive, '=', true).toList();
users[0].role = 'admin';
await context.saveChanges();

asNoTracking()​

asNoTracking(): DbSet<T>

Defined in: src/set/DbSet.ts:1985

Disables change tracking for entities returned by this query for improved read-only performance.

Returns​

DbSet<T>

A new cloned DbSet with change tracking disabled.

Usecase​

High-performance read-only queries, reporting, or large list lookups where entity instances will not be modified.

Example​

const readOnlyUsers = await context.users.asNoTracking().toList();

exists()​

exists(predicate?): Promise<boolean>

Defined in: src/set/DbSet.ts:2000

Checks whether any record matching the predicate exists.

Parameters​

ParameterTypeDescription
predicate?Partial<T>Optional filter criteria.

Returns​

Promise<boolean>

true if matching record exists, otherwise false.

Usecase​

Use this for fast existence checks, e.g. checking if an email is already registered during signup.

Example​

const emailTaken = await context.users.exists({ email: 'test@example.com' });

track()​

track(id): Promise<T>

Defined in: src/set/DbSet.ts:2370

Fetches an entity by primary key and registers it in the ChangeTracker for automatic dirty checking.

Parameters​

ParameterTypeDescription
idunknownThe primary key of the entity to load and track.

Returns​

Promise<T>

A Promise resolving to the tracked proxy/entity instance.

Usecase​

Use this in enterprise architectures where modifications are applied directly to entity object properties and flushed via context.saveChanges().

Example​

const user = await context.users.track(1);
user.name = 'Updated Name';
await context.saveChanges(); // automatically issues UPDATE users SET name = 'Updated Name' WHERE id = 1

add()​

add(entity): Promise<T>

Defined in: src/set/DbSet.ts:2401

Inserts a new entity row into the database table.

Automatically handles primary key generation (RETURNING id in PostgreSQL / SQLite, OUTPUT INSERTED.id in MSSQL, insertId in MySQL), audit timestamps (@CreatedAt, @UpdatedAt), audit user (@CreatedBy), tenant scoping (@TenantId), and optimistic concurrency versioning.

Parameters​

ParameterTypeDescription
entityPartial<T>The entity attributes to insert.

Returns​

Promise<T>

A Promise resolving to the inserted entity with its generated primary key populated.

Usecase​

Persist a new entity record into the database across any supported engine with automatic identity resolution.

Example​

PostgreSQL / MySQL / SQLite / MSSQL / Neon / Turso:

const newUser = await context.users.add({
name: 'John Doe',
email: 'john@example.com',
role: 'user',
});
console.log('Generated User ID:', newUser.id);

addRange()​

addRange(entities): Promise<T[]>

Defined in: src/set/DbSet.ts:2566

Inserts multiple entities sequentially into the database within the current transaction.

Parameters​

ParameterTypeDescription
entitiesPartial<T>[]Array of entity objects to insert.

Returns​

Promise<T[]>

A Promise resolving to an array of saved entities with generated primary keys.

Usecase​

Add a collection of domain entities while triggering individual entity lifecycle hooks, validation, and audit entries.

Example​

const users = await context.users.addRange([
{ name: 'Alice', email: 'alice@example.com' },
{ name: 'Bob', email: 'bob@example.com' },
]);

update()​

update(id, patch, expectedVersion?, concurrencyOriginals?): Promise<T>

Defined in: src/set/DbSet.ts:2596

Updates an existing entity by primary key with partial field updates and optimistic concurrency checking.

Automatically refreshes updatedAt and advances @Version properties.

Parameters​

ParameterTypeDescription
idunknownThe primary key of the entity to update.
patchPartial<T>Partial object containing fields to update.
expectedVersion?unknownOptional expected version for optimistic concurrency conflict detection.
concurrencyOriginals?Record<string, unknown>Optional map of original values for columns decorated with @ConcurrencyCheck.

Returns​

Promise<T>

A Promise resolving to the refreshed updated entity from the database.

Usecase​

Update entity attributes (e.g. status changes, price updates) with concurrency conflict prevention.

Throws​

DbUpdateConcurrencyException if expected version does not match current database row.

Example​

PostgreSQL / MySQL / SQLite / MSSQL:

const updatedUser = await context.users.update(userId, {
name: 'Jane Doe',
role: 'admin',
});

executeUpdate()​

executeUpdate(patchOrSetter): Promise<number>

Defined in: src/set/DbSet.ts:2752

Performs an immediate bulk UPDATE operation on the entities matching the current query filter. Updates are compiled directly to SQL UPDATE without loading records into memory.

Parameters​

ParameterTypeDescription
patchOrSetterPartial<T> | ((setter) => void | UpdateSetBuilder<T>)Partial entity object or a builder function using UpdateSetBuilder.

Returns​

Promise<number>

The number of rows affected.

Usecase​

Direct database bulk update without loading entities into memory or tracking them.

Example​

// Using partial object
const affected = await db.users
.where(u => u.role, '=', 'guest')
.executeUpdate({ role: 'member' });

// Using builder callback
const affected2 = await db.users
.where(u => u.status, '=', 'inactive')
.executeUpdate(s => s.set(u => u.status, 'archived'));

updateWhere()​

updateWhere(predicate, patchOrSetter): Promise<number>

Defined in: src/set/DbSet.ts:2833

Updates records matching a filter predicate in a single statement.

Parameters​

ParameterTypeDescription
predicateLinqPredicate<T>Filter criteria object, WhereClause builder, or lambda predicate.
patchOrSetterPartial<T> | ((setter) => void | UpdateSetBuilder<T>)Fields to update or UpdateSetBuilder callback.

Returns​

Promise<number>

The number of rows affected.

Example​

const count = await db.users.updateWhere({ role: 'guest' }, { role: 'member' });
const count2 = await db.users.updateWhere(
w => w.eq('role', 'guest'),
s => s.set('role', 'member')
);

upsert()​

Call Signature​

upsert(conflictTarget, updatePayload): Promise<T>

Defined in: src/set/DbSet.ts:2852

Performs an atomic native database upsert using conflict target and update payload, or a select-and-insert/update fallback based on primary keys.

Parameters​
ParameterType
conflictTargetPartial<T>
updatePayloadPartial<T>
Returns​

Promise<T>

Example​
await db.accounts.upsert(
{ email: 'user@corp.com' },
{ balance: 5000, name: 'Updated' }
);

Call Signature​

upsert(args): Promise<T>

Defined in: src/set/DbSet.ts:2853

Performs an atomic native database upsert using conflict target and update payload, or a select-and-insert/update fallback based on primary keys.

Parameters​
ParameterType
args{ where: Partial<T>; update: Partial<T>; create: Partial<T>; select?: keyof T[]; }
args.wherePartial<T>
args.updatePartial<T>
args.createPartial<T>
args.select?keyof T[]
Returns​

Promise<T>

Example​
await db.accounts.upsert(
{ email: 'user@corp.com' },
{ balance: 5000, name: 'Updated' }
);

Call Signature​

upsert(entity, keys?): Promise<T>

Defined in: src/set/DbSet.ts:2859

Performs an atomic native database upsert using conflict target and update payload, or a select-and-insert/update fallback based on primary keys.

Parameters​
ParameterType
entityPartial<T>
keys?keyof T[]
Returns​

Promise<T>

Example​
await db.accounts.upsert(
{ email: 'user@corp.com' },
{ balance: 5000, name: 'Updated' }
);

upsertRange()​

upsertRange(items, keys?): Promise<T[]>

Defined in: src/set/DbSet.ts:3018

Performs a batch upsert (insert if not found, or update if existing) for multiple entities.

Parameters​

ParameterTypeDescription
itemsPartial<T>[]Array of entity data objects to insert or update.
keys?keyof T[]Optional array of property keys used to check for existing records (defaults to primary key).

Returns​

Promise<T[]>

A Promise resolving to an array of the saved entities.

Usecase​

Ideal for sync pipelines, bulk imports, catalog refreshes, and seeder routines.

Example​

const saved = await context.products.upsertRange(incomingCatalog, ['sku']);

remove()​

remove(id, expectedVersion?): Promise<void>

Defined in: src/set/DbSet.ts:3042

Deletes an entity by its primary key or entity instance.

If the entity has @SoftDelete configured, this sets deletedAt without deleting the row. Otherwise, it performs a hard DELETE. Supports optimistic concurrency checks.

Parameters​

ParameterTypeDescription
idunknownThe primary key value or the entity instance itself.
expectedVersion?unknownOptional version token for optimistic concurrency verification.

Returns​

Promise<void>

Usecase​

Standard deletion method for REST controllers (DELETE /items/:id).

Example​

await context.users.remove(userId);

hardRemove()​

hardRemove(id, expectedVersion?): Promise<void>

Defined in: src/set/DbSet.ts:3170

Permanently deletes a row from the database table regardless of @SoftDelete configuration.

Parameters​

ParameterTypeDescription
idunknownThe primary key value or entity object.
expectedVersion?unknownOptional version token for concurrency verification.

Returns​

Promise<void>

Usecase​

Use this for GDPR "Right to be Forgotten" requests, test database teardown, or permanent data purging.

Example​

await context.users.hardRemove(userId);

executeDelete()​

executeDelete(options?): Promise<number>

Defined in: src/set/DbSet.ts:3226

Performs an immediate bulk DELETE operation on the entities matching the current query filter. Respects entity soft-delete configuration unless hardDelete: true is specified.

Parameters​

ParameterTypeDescription
options?{ hardDelete?: boolean; }Optional flags (e.g. { hardDelete: true }).
options.hardDelete?boolean-

Returns​

Promise<number>

The number of rows affected.

Usecase​

Direct database bulk delete without loading entities into memory.

Example​

const count = await db.users
.where(u => u.status, '=', 'banned')
.executeDelete();

removeWhere()​

removeWhere(predicate): Promise<number>

Defined in: src/set/DbSet.ts:3323

Deletes (or soft-deletes if configured) all records matching the specified predicate.

Parameters​

ParameterTypeDescription
predicateLinqPredicate<T>Filter criteria matching the records to remove (object, WhereClause callback, or lambda predicate).

Returns​

Promise<number>

A Promise resolving to the number of rows affected.

Usecase​

Use this to remove multiple records satisfying a filter (e.g. deleting expired sessions or unverified temp accounts).

Example​

const deletedCount = await context.sessions.removeWhere({ isExpired: true });
const deletedCount2 = await context.sessions.removeWhere(w => w.lt('expiresAt', new Date()));

hardRemoveWhere()​

hardRemoveWhere(predicate): Promise<number>

Defined in: src/set/DbSet.ts:3338

Permanently deletes all records matching the specified predicate regardless of soft-delete settings.

Parameters​

ParameterTypeDescription
predicatePartial<T>Filter criteria matching the records to permanently delete.

Returns​

Promise<number>

A Promise resolving to the number of rows physically removed.

Usecase​

Use this to permanently purge old records (e.g. purging logs older than 90 days).

Example​

const purgedCount = await context.auditLogs.hardRemoveWhere({ status: 'archived' });

restore()​

restore(id): Promise<void>

Defined in: src/set/DbSet.ts:3362

Restores a single soft-deleted entity by setting its deletedAt column back to null.

If @SoftDelete({ cascade: true }) is configured, all hasMany / hasOne children that share the same foreignKey value will also be restored.

Parameters​

ParameterTypeDescription
idunknownThe primary key of the entity to restore.

Returns​

Promise<void>

Usecase​

Use this to implement a "Restore from Trash" action for soft-deleted records.

Throws​

Error if the entity does not have @SoftDelete configured.

Example​

await context.users.restore(userId);

restoreWhere()​

restoreWhere(predicate): Promise<number>

Defined in: src/set/DbSet.ts:3406

Restores all soft-deleted entities matching the given predicate by setting deletedAt to null.

Parameters​

ParameterTypeDescription
predicatePartial<T>Filter criteria matching the records to restore.

Returns​

Promise<number>

A Promise resolving to the number of rows restored.

Usecase​

Use this for bulk restoration of archived records (e.g., restoring all posts for a reactivated user).

Throws​

Error if the entity does not have @SoftDelete configured.

Example​

// Restore all posts belonging to a user
const count = await context.posts.restoreWhere({ userId: 42 });

bulkInsert()​

bulkInsert(entities, options?): Promise<number>

Defined in: src/set/DbSet.ts:3498

Performs high-performance batch insertion of multiple records in a single chunked SQL statement.

Automatically handles dialect parameter limits (e.g. SQLite 999/32766 params, PostgreSQL 65535 params, MSSQL 2100 params) by splitting large batches into optimal sub-chunks.

Parameters​

ParameterTypeDescription
entitiesPartial<T>[]Array of entities to insert in bulk.
options?BulkInsertOptionsBatching options (batch size, concurrency, transaction).

Returns​

Promise<number>

A Promise resolving to the total number of rows inserted.

Usecase​

Ideal for data imports, CSV uploads, ETL pipelines, and seeding thousands of records with optimal database throughput.

Example​

PostgreSQL / MySQL / SQLite / MSSQL:

const insertedCount = await context.products.bulkInsert(newProductList, {
batchSize: 500,
ignoreDuplicates: false,
});
console.log(`Inserted ${insertedCount} products`);

bulkUpdate()​

bulkUpdate(entities, options): Promise<number>

Defined in: src/set/DbSet.ts:3529

Performs high-performance batch updates across multiple records matching by primary key or specified keys.

Generates optimized multi-row UPDATE statements (using CASE ... WHEN or temporary staging tables based on provider).

Parameters​

ParameterTypeDescription
entitiesPartial<T>[]Array of entities containing update values and identifying keys.
optionsBulkUpdateOptions<T>Bulk update options (update columns, key columns, batch size).

Returns​

Promise<number>

A Promise resolving to the total number of rows updated.

Usecase​

Ideal for bulk price adjustments, mass status changes, and inventory level updates across thousands of records.

Example​

PostgreSQL / MySQL / SQLite / MSSQL:

await context.products.bulkUpdate(updatedProducts, {
keyColumns: ['id'],
updateColumns: ['price', 'stockQuantity'],
batchSize: 250,
});

bulkUpsert()​

bulkUpsert(entities, options): Promise<number>

Defined in: src/set/DbSet.ts:3563

Performs high-performance bulk upsert across multiple records in a single statement.

Automatically adapts to the underlying database dialect:

  • PostgreSQL: INSERT ... ON CONFLICT (key) DO UPDATE SET ...
  • MySQL: INSERT ... ON DUPLICATE KEY UPDATE ...
  • SQLite: INSERT ... ON CONFLICT (key) DO UPDATE SET ...
  • Microsoft SQL Server: MERGE INTO ... USING (VALUES ...) ON ... WHEN MATCHED THEN UPDATE ... WHEN NOT MATCHED THEN INSERT ...

Parameters​

ParameterTypeDescription
entitiesPartial<T>[]Array of entities to upsert.
optionsBulkUpsertOptions<T>Match keys, update columns, and batching configuration.

Returns​

Promise<number>

A Promise resolving to the number of rows affected.

Usecase​

Ideal for data synchronization with external APIs or CRMs where incoming records must be inserted if new or updated if existing.

Example​

PostgreSQL / MySQL / SQLite / MSSQL:

await context.products.bulkUpsert(syncedItems, {
keyColumns: ['sku'],
updateColumns: ['price', 'stock', 'title'],
batchSize: 500,
});

bulkDelete()​

bulkDelete(predicate, options?): Promise<number>

Defined in: src/set/DbSet.ts:3588

Performs high-performance bulk deletion of records matching criteria.

Parameters​

ParameterTypeDescription
predicatePartial<T>Criteria matching rows to delete.
options?BulkDeleteOptionsBatching and transaction options.

Returns​

Promise<number>

A Promise resolving to the number of rows deleted.

Usecase​

Ideal for purging historical records in bulk batches with transaction safety.

Example​

PostgreSQL / MySQL / SQLite / MSSQL:

await context.notifications.bulkDelete({ isRead: true });

fromSql()​

fromSql(sqlOrStrings, ...paramsOrValues): Promise<T[]>

Defined in: src/set/DbSet.ts:3615

Executes a raw SQL query with parameterized values and maps the resulting rows into typed entity instances.

Parameters​

ParameterType
sqlOrStringsstring | TemplateStringsArray
...paramsOrValuesany[]

Returns​

Promise<T[]>

A Promise resolving to an array of mapped typed entities.

Usecase​

Use this for complex CTEs, window functions, union queries, or database-specific optimizations while still receiving typed entities.

Example​

const topUsers = await context.users.fromSql(
'SELECT u.* FROM users u INNER JOIN orders o ON o.user_id = u.id GROUP BY u.id HAVING COUNT(o.id) > @p0',
[5]
);