Interfaces
All methods are available directly on the datrix instance and identically on
datrix.crud. Use datrix.raw to bypass plugin hooks — signatures are the same.
DatrixId is number by default and string when the project uses
idType: "uuid" and the
generated types register it (datrix generate types).
CRUD Methods
findOne
findOne<T extends DatrixEntry = DatrixRecord>(
model: string, // registered schema name
where: WhereClause<T>, // filter criteria — must match exactly one record
options?: RawCrudOptions<T>, // select, populate
): Promise<T | null>
Returns the first record matching where, or null if none found.
Options: select and populate are supported. noReturning has no effect on any find operations.
findById
findById<T extends DatrixEntry = DatrixRecord>(
model: string, // registered schema name
id: DatrixId, // record ID
options?: RawCrudOptions<T>, // select, populate
): Promise<T | null>
Shorthand for findOne with where: { id }. Returns null if not found.
findMany
findMany<T extends DatrixEntry = DatrixRecord>(
model: string, // registered schema name
options?: RawFindManyOptions<T>, // where, select, populate, orderBy, limit, offset, distinct, groupBy, having
): Promise<T[]>
Returns all records matching the given options. Returns an empty array if none found.
distinct deduplicates rows on the selected fields — requires an explicit select (a wildcard select would silently defeat deduplication via the unique id column). groupBy groups by scalar fields (relation fields cannot be grouped on); having filters groups after aggregation and can only reference fields present in groupBy.
count
count<T extends DatrixEntry = DatrixRecord>(
model: string, // registered schema name
where?: WhereClause<T>, // filter criteria — omit to count all records
): Promise<number>
Returns the number of records matching where.
countMany
countMany<T extends DatrixEntry = DatrixRecord>(
model: string,
options: {
where?: WhereClause<T>
groupBy: string[] // required — countMany without a grouping is just count()
having?: WhereClause<T> // fields must be a subset of groupBy
},
): Promise<(Record<string, unknown> & { count: number })[]>
Returns one entry per distinct group — each carrying that group's groupBy field values plus a count. No matches (or having filters every group out) resolve to [], never a bare 0. This is a different shape from count() on purpose: count always returns a single number, countMany always returns an array, so callers never have to guess.
await datrix.countMany('user', {
where: { isActive: true },
groupBy: ['role'],
})
// → [{ role: 'admin', count: 2 }, { role: 'editor', count: 5 }]
create
create<T extends DatrixEntry = DatrixRecord, TInput extends FallbackInput = FallbackInput>(
model: string, // registered schema name
data: TInput, // field values to insert
options?: RawCrudOptions<T>, // select, populate on returned record
): Promise<T>
Inserts a single record and returns it. Runs full field validation and injects
createdAt / updatedAt automatically. See Relations
for all accepted formats in the data argument.
Options:
| Option | Type | Default | Description |
|---|---|---|---|
select | SelectClause<T> | "*" | Fields to return. Omit to return all fields. |
populate | PopulateClause<T> | — | Relations to populate on the returned record. |
noReturning | boolean | false | Skip the post-insert SELECT. Returns only the inserted IDs instead of the full record. Use when you don't need the created record and want to avoid the extra query. |
createMany
createMany<T extends DatrixEntry = DatrixRecord, TInput extends FallbackInput = FallbackInput>(
model: string, // registered schema name
data: TInput[], // array of field values
options?: RawCrudOptions<T>, // select, populate on returned records
): Promise<T[]>
Inserts multiple records in a single transaction and returns them all.
See create for a full description of available options.
Relating to an existing record (id shortcut) can differ per item. Relating to
a new record (create) must be the same for every item — otherwise use
create in a loop instead.
update
update<T extends DatrixEntry = DatrixRecord, TInput extends FallbackInput = FallbackInput>(
model: string, // registered schema name
id: DatrixId, // record ID to update
data: TInput, // fields to update (partial)
options?: RawCrudOptions<T>, // select, populate on returned record
): Promise<T>
Updates a single record by ID and returns it. Throws RECORD_NOT_FOUND if the ID does not exist.
See Relations for all accepted formats in the data argument.
Options:
| Option | Type | Default | Description |
|---|---|---|---|
select | SelectClause<T> | "*" | Fields to return on the updated record. |
populate | PopulateClause<T> | — | Relations to populate on the returned record. |
noReturning | boolean | false | Skip the post-update SELECT. Returns only the updated record's ID instead of the full record. |
updateMany
updateMany<T extends DatrixEntry = DatrixRecord, TInput extends FallbackInput = FallbackInput>(
model: string, // registered schema name
where: WhereClause<T>, // filter criteria
data: TInput, // fields to update (partial)
options?: RawCrudOptions<T>, // select, populate on returned records
): Promise<T[]>
Updates all records matching where and returns them. Returns an empty array if no records matched.
See update for a full description of available options.
upsert
New in 0.2.2.
upsert<T extends DatrixEntry = DatrixRecord, TInput extends FallbackInput = FallbackInput>(
model: string, // registered schema name
data: TInput, // field values to insert or apply
options: RawUpsertOptions<T>, // conflictOn, update, select, populate
): Promise<T>
Inserts a record, or updates the existing one when it matches on conflictOn,
and returns it. A matched record is updated with the row's own incoming values.
Rows are validated as creates (required fields etc.), even if they end up
updating. See Relations for the accepted formats in the
data argument.
Options:
| Option | Type | Default | Description |
|---|---|---|---|
conflictOn | readonly string[] | required | Conflict target: a field with unique: true, id, or exactly the fields of a unique index (indexes: [{ fields: [...], unique: true }], order-insensitive). A belongsTo relation name maps to its foreign key column. |
update | readonly string[] | every field set in all rows | Fields overwritten on conflict. Omitted: every field set in all rows, except id, createdAt, updatedAt and the conflict fields. [] leaves matched records untouched (relations included) while new rows are still inserted. |
select | SelectClause<T> | "*" | Fields to return. |
populate | PopulateClause<T> | — | Relations to populate on the returned record. |
noReturning | boolean | false | Skip the post-upsert SELECT. Returns only the record IDs. |
updatedAt is refreshed on conflict when update is non-empty; createdAt is
never overwritten.
The query builder rejects a non-unique conflictOn, a row without a value for
a conflictOn field, two rows with the same conflictOn values in one batch,
update fields that are not set in every row, and reserved fields (id,
createdAt, updatedAt) in update.
Schema beforeUpsert / afterUpsert hooks
fire for upserts; beforeCreate, afterCreate, beforeUpdate and afterUpdate
do not.
upsertMany
upsertMany<T extends DatrixEntry = DatrixRecord, TInput extends FallbackInput = FallbackInput>(
model: string, // registered schema name
data: TInput[], // array of field values
options: RawUpsertOptions<T>, // conflictOn, update, select, populate
): Promise<T[]>
Upserts multiple records in a single statement and returns them all.
See upsert for a full description of available options.
Relations follow the same rule as createMany: the relation set of
the first row is applied to every returned record. With update: [] it is
applied only to newly inserted records.
On MySQL and MariaDB, a row conflicts with any unique key of the table, not
only conflictOn.
delete
delete<T extends DatrixEntry = DatrixRecord>(
model: string, // registered schema name
id: DatrixId, // record ID to delete
options?: RawCrudOptions<T>, // select, populate on returned record
): Promise<T>
Deletes a single record by ID and returns it. Throws RECORD_NOT_FOUND if the ID does not exist.
Options:
| Option | Type | Default | Description |
|---|---|---|---|
select | SelectClause<T> | — | Fields to return. Triggers a pre-fetch SELECT before the delete. |
populate | PopulateClause<T> | — | Relations to populate. Triggers a pre-fetch SELECT before the delete. |
noReturning | boolean | true (when no select/populate) | By default, delete only returns the deleted record's ID — no extra query is made. Pass select or populate to fetch the full record before deletion. Set noReturning: false explicitly to force a pre-fetch with all fields. |
deleteMany
deleteMany<T extends DatrixEntry = DatrixRecord>(
model: string, // registered schema name
where: WhereClause<T>, // filter criteria
options?: RawCrudOptions<T>, // select, populate on returned records
): Promise<T[]>
Deletes all records matching where and returns them.
See delete for a full description of available options.
Schema Access
getSchemas
getSchemas(): SchemaRegistry
Returns the full schema registry. Useful for inspecting registered schemas at runtime.
getSchema
getSchema(
name: string, // registered schema name
): SchemaDefinition | undefined
Returns a single schema by name, or undefined if not registered.
hasSchema
hasSchema(
name: string, // registered schema name
): boolean
Returns true if a schema with the given name is registered.
getAllSchemas
getAllSchemas(): readonly SchemaDefinition[]
Returns all registered schemas as a readonly array.
Plugin System
getPlugin
getPlugin<T extends DatrixPlugin = DatrixPlugin>(
name: string, // plugin name as registered
): T | null
Returns the plugin instance by name, or null if not found. Use the generic
to get a typed reference to a specific plugin.
getPlugins
getPlugins(): readonly DatrixPlugin[]
Returns all registered plugin instances.
hasPlugin
hasPlugin(
name: string, // plugin name as registered
): boolean
Returns true if a plugin with the given name is registered.
Lifecycle
isInitialized
isInitialized(): boolean
Returns true if datrix has been initialized. Safe to call before initialization.
getConfig
getConfig(): DatrixConfig
Returns the active configuration object. Throws if called before initialization.
getAdapter
getAdapter<T extends DatabaseAdapter = DatabaseAdapter>(): T
Returns the active adapter instance. Use the generic to get a typed reference to a specific adapter implementation.
shutdown
shutdown(): Promise<void>
Destroys all plugins, closes the database connection, and resets the instance.
After shutdown, datrix must be re-initialized before use.
Transactions
transaction
transaction<R>(
fn: (tx: DatrixTransaction) => Promise<R>,
options?: TransactionOptions,
): Promise<R>
Runs fn inside a database transaction. Commits when fn resolves and returns
its value; rolls back and rethrows when fn throws. tx exposes the same CRUD
methods as the instance, plus tx.raw, tx.afterCommit and tx.rollback.
See Transactions for rollback semantics, hooks and
afterCommit.
CLI Internals
beginMigrate
beginMigrate(): Promise<MigrationSession>
Compares current schemas against the live database and returns a
MigrationSession for reviewing and applying changes.
This method is used internally by the Datrix CLI (datrix migrate). Direct use
is possible but not the intended workflow — prefer the CLI for migrations.
const session = await datrix.beginMigrate()
if (session.hasAmbiguous) {
session.resolveAmbiguous("user.name->lastname", "rename")
}
const plan = session.getPlan()
await session.apply()