yatta/db
Typed SQLite: schema, relations, queries, migrations.
39 exported symbols and 143 members, read from src/types/db.ts.
Construct
and
functionCombines multiple conditions with a logical `AND`.
- conds
- List of conditions to combine.
Returns Combined .
and(f.age.isGreaterThan(21), f.country.isEqualTo("US"))connect
functionHelper function for connecting existing records in relational operations.
connect<T>(row: T): T- row
- Record to connect.
Returns The unchanged row.
createDatabase
functionCreates, configures, and synchronizes a type-safe instance.
Automatically: - Initializes WAL mode and foreign keys in SQLite - Synchronizes schemas, creating missing tables and columns - Returns a typed proxy allowing direct `db.users` table access - Registers the database globally for zero-import `DB` usage
createDatabase<S extends DatabaseSchema = DatabaseSchema>(options?: DatabaseOptions & { schema?: S; }): TypedDatabase<S>- options
- Database configuration options.
Returns Configured instance.
import { col, createDatabase } from "./db"; export const schema = { users: { id: col.uuid(), name: col.text(), email: col.text().unique(), createdAt: col.createdAt(), },}; export const db = createDatabase({ path: "Database/app.db", schema,}); const user = db.users.insert({ name: "Bob", email: "bob@example.com" });or
functionCombines multiple conditions with a logical `OR`.
- conds
- List of conditions to combine.
Returns Combined .
or(f.role.isEqualTo("admin"), f.role.isEqualTo("moderator"))resolveDatabasePath
functionResolves and normalizes an input database path to an absolute filesystem path.
resolveDatabasePath(targetPath?: string): string- targetPath
- Relative or absolute path, or `":memory:"`.
Returns Absolute filesystem path or `":memory:"`.
ColumnBuilder
classFluent builder for defining table columns with strong typing and constraint chaining.
class ColumnBuilder11 members
defpropertydef: ColumnDefinitionInternal column configuration definition.
cloneclone<V2 = V, O2 extends boolean = Optional, R2 extends boolean = IsRef>(patch: Partial<ColumnDefinition>): ColumnBuilder<V2, O2, R2>primaryKeyprimaryKey(): ColumnBuilder<V, Optional, IsRef>Designates this column as the primary key of the table.
Returns Column builder configured as primary key.
autoIncrementautoIncrement(): ColumnBuilder<V, true, IsRef>Configures automatic sequence incrementation on primary key insert.
Returns Column builder configured for auto-increment.
nullablenullable(): ColumnBuilder<V | null, true, IsRef>Allows the column to store `NULL` values.
Returns Column builder typed as nullable.
notNullnotNull(): ColumnBuilder<NonNullable<V>, false, IsRef>Enforces a `NOT NULL` constraint on the column.
Returns Column builder typed as non-nullable.
uniqueunique(): ColumnBuilder<V, Optional, IsRef>Adds a `UNIQUE` constraint and index on this column.
Returns Column builder with unique constraint.
defaultdefault(val: V): ColumnBuilder<V, true, IsRef>Specifies a default fallback value used when inserting a row without providing this column.
- val
- Default value to assign.
Returns Column builder with default value configured.
indexindex(): ColumnBuilder<V, Optional, IsRef>Creates an SQLite index on this column for faster queries and lookups.
Returns Column builder flagged for index creation.
referencesreferences(target: `${string}.${string}`, opts?: { onDelete?: "CASCADE" | "SET NULL" | "RESTRICT"; }): ColumnBuilder<V, Optional, true>Establishes a foreign key relationship referencing another table's column.
- target
- Target in `"tableName.columnName"` format (e.g. `"users.id"`).
- opts
- Referential action options (e.g. `{ onDelete: "CASCADE" }`).
Returns Column builder configured as foreign key reference.
tsts authorId: col.text().references("users.id", { onDelete: "CASCADE" })belongsTobelongsTo(table: string, opts?: { onDelete?: "CASCADE" | "SET NULL" | "RESTRICT"; }): ColumnBuilder<V, Optional, true>Fluent shorthand helper creating a foreign key referencing the `id` column of the specified table.
- table
- Target table name.
- opts
- Referential action options (e.g. `{ onDelete: "CASCADE" }`).
Returns Column builder configured as foreign key.
tsts userId: col.text().belongsTo("users", { onDelete: "CASCADE" })
Condition
classRepresents a composable filter predicate node in the English-like filtering DSL.
class Conditionconst condition = f.age.isGreaterThan(18).and(f.status.isEqualTo("active"));3 members
andand(other: Condition): ConditionCombines this condition with another using a logical `AND`.
- other
- The other condition to combine with.
Returns A combined .
oror(other: Condition): ConditionCombines this condition with another using a logical `OR`.
- other
- The other condition to combine with.
Returns A combined .
toWheretoWhere(): WhereClause<any>Compiles this condition tree into a standard declarative .
Returns Compiled where clause object.
QueryBuilder
classFluent query builder for constructing, filtering, sorting, selecting, and executing queries.
class QueryBuilderconst activeUsers = db.users .where((f) => f.status.isEqualTo("active")) .orderBy({ createdAt: "desc" }) .take(10) .all();13 members
optspropertyopts: FindOptions<T>wherewhere(clauseOrFn: WhereClause<T> | ((fields: FieldsProxy<T>) => Condition)): thisAdds filter criteria to the query using either a declarative
- clauseOrFn
- Filter object or DSL function.
Returns Current query builder for chaining.
tsts query.where((f) => f.age.isGreaterOrEqualTo(21));query.where({ role: "member" });orderByorderBy(order: OrderBy<T> | OrderBy<T>[]): thisApplies sort ordering criteria to the query.
- order
- Ordering configuration (e.g. `{ createdAt: "desc" }`).
Returns Current query builder for chaining.
taketake(n: number): thisSets the maximum number of rows to return (`LIMIT`).
- n
- Maximum number of rows.
Returns Current query builder for chaining.
limitlimit(n: number): thisAlias for . Sets the maximum number of rows to return.
- n
- Maximum row limit.
Returns Current query builder for chaining.
skipskip(n: number): thisSets the number of rows to skip (`OFFSET`).
- n
- Number of rows to bypass.
Returns Current query builder for chaining.
selectselect<K extends keyof T>(fields: K[]): QueryBuilder<T, Prettify<Pick<T, K>>>Projects only the specified subset of columns, narrowing the resulting TypeScript type.
- fields
- Array of column names to select.
Returns Query builder typed to the picked fields.
tsts const users = db.users.where({ role: "admin" }).select(["id", "email"]).all();// users: { id: string; email: string }[]includeinclude<Inc extends Record<string, any> = Record<string, any>>(relations: Record<string, boolean>): QueryBuilder<T, Prettify<TResult & Inc>>Eagerly loads relational associations on the returned records.
- relations
- Dictionary of relation names mapped to `true`.
Returns Query builder typed to include related data.
tsts const usersWithPosts = db.users.where({ id }).include({ posts: true }).all();allall(): TResult[]Executes the query and returns all matching rows as an array.
Returns Array of resulting records.
firstfirst(): TResult | nullExecutes the query and returns the first matching row, or `null` if none found.
Returns The first matching record or `null`.
countcount(): numberCounts the total number of rows matching the query filters.
Returns Count of matching records.
existsexists(): booleanChecks whether at least one row matches the query filter.
Returns `true` if at least one matching row exists, `false` otherwise.
paginatepaginate(page?: , limit?: ): PaginatedResult<TResult>Executes an offset-based paginated query returning rows and pagination metadata.
- page
- 1-indexed page number (default: 1).
- limit
- Records per page (default: 10).
Table
classType-safe CRUD table gateway providing querying, insertions, updates, deletions,
class Tableconst user = db.users.insert({ email: "alice@example.com", name: "Alice" });const found = db.users.findById(user.id);db.users.updateById(user.id, { name: "Alice Smith" });32 members
columnspropertycolumns: Map<string, ColumnDefinition>Map of column definitions belonging to this table.
primaryKeyColumnpropertyprimaryKeyColumn: stringThe primary key column name for this table (defaults to `"id"`).
belongsToAliasespropertybelongsToAliases: Map<string, { column: string; table: string; }>Inferred relational foreign key aliases (e.g. `userId` -> `user`).
wherewhere(clauseOrFn: WhereClause<T> | ((fields: FieldsProxy<T>) => Condition)): QueryBuilder<T>Begins a fluent with an initial filter clause or English DSL callback.
- clauseOrFn
- Declarative or English DSL function.
Returns Chained .
tsts const admins = db.users.where((f) => f.role.isEqualTo("admin")).all();insertinsert(data: TInsert): TInserts a single record into the table and returns the newly created row with generated values.
- data
- Payload to insert.
Returns Persisted entity row.
tsts const user = db.users.insert({ email: "bob@example.com", name: "Bob" });insertManyinsertMany(items: TInsert[]): T[]Inserts multiple records in a single batch within an atomic SQLite transaction.
- items
- Array of records to insert.
Returns Array of persisted rows.
tsts const users = db.users.insertMany([ { email: "user1@example.com" }, { email: "user2@example.com" },]);findFirstfindFirst<K extends keyof T>(options: FindOptions<T, K> & { select: K[]; }): Prettify<Pick<T, K>> | nullFinds the first row matching the specified criteria, projecting only selected columns.
- options
- Query criteria with `select` array.
Returns Picked record columns or `null` if no match.
findFirstfindFirst(options?: FindOptions<T, keyof T>): T | nullFinds the first row matching the specified criteria.
- options
- Optional query criteria.
Returns Full record or `null` if no match.
findFirstfindFirst<K extends keyof T = keyof T, R = Pick<T, K>>(options?: FindOptions<T, K>): R | nullfirstfirst(): T | nullShorthand to retrieve the very first row in the table.
Returns First row or `null` if table is empty.
findByIdfindById<K extends keyof T>(id: string | number, options: { select: K[]; include?: Record<string, boolean>; }): Prettify<Pick<T, K>> | nullFinds a row by its primary key with selected columns projected.
- id
- Primary key value.
- options
- Selection options.
Returns Picked record columns or `null` if not found.
findByIdfindById(id: string | number, options?: { select?: undefined; include?: Record<string, boolean>; }): T | nullFinds a row by its primary key.
- id
- Primary key value.
- options
- Optional relation inclusion options.
Returns Full record or `null` if not found.
findByIdfindById<K extends keyof T = keyof T, R = Pick<T, K>>(id: string | number, options?: { select?: K[]; include?: Record<string, boolean>; }): R | nullfindManyfindMany<K extends keyof T>(options: FindOptions<T, K> & { select: K[]; }): Prettify<Pick<T, K>>[]Finds all rows matching the specified criteria, projecting only selected columns.
- options
- Query criteria with `select` array.
Returns Array of picked records.
findManyfindMany(options?: FindOptions<T, keyof T>): T[]Finds all rows matching the specified criteria.
- options
- Optional query criteria.
Returns Array of full records.
findManyfindMany<K extends keyof T = keyof T, R = Pick<T, K>>(options?: FindOptions<T, K>): R[]buildSetClausebuildSetClause(data: Record<string, any>): { setSql: string; params: any[]; }updateupdate(options: { where: WhereClause<T>; data: Partial<TInsert | T>; }): { changes: number; }Updates all rows matching the `where` filter with the provided partial data.
- options
- Object containing `where` criteria and `data` updates.
Returns Object containing the number of modified rows (`changes`).
tsts const { changes } = db.users.update({ where: { role: "guest" }, data: { role: "member" },});updateByIdupdateById(id: string | number, data: Partial<TInsert | T>): T | nullUpdates a single record identified by its primary key and returns the updated row.
- id
- Primary key value.
- data
- Partial fields to update.
Returns Updated row or `null` if not found.
tsts const updated = db.users.updateById(1, { name: "New Name" });upsertupsert({ where, create, update }: UpsertOptions<T, TInsert>): TAtomically inserts a new row or updates an existing one if a row matching `where` is found.
- options
- Upsert criteria: `where` condition, `create` payload, and `update` modifications.
Returns The newly created or updated row.
tsts const user = db.users.upsert({ where: { email: "user@example.com" }, create: { email: "user@example.com", name: "User" }, update: { name: "User Updated" },});deletedelete(options: { where: WhereClause<T>; }): { changes: number; }Deletes all rows matching the `where` criteria.
- options
- Object with `where` filter condition.
Returns Object containing the count of deleted rows (`changes`).
tsts db.users.delete({ where: { status: "inactive" } });deleteByIddeleteById(id: string | number): booleanDeletes a single record by its primary key.
- id
- Primary key value.
Returns `true` if a row was deleted, `false` otherwise.
tsts const wasDeleted = db.users.deleteById(1);countcount(where?: WhereClause<T>): numberCounts the total number of rows matching an optional filter.
- where
- Optional filter condition.
Returns Total row count.
existsexists(where?: WhereClause<T>): booleanChecks whether at least one row exists matching the specified criteria.
- where
- Optional filter condition.
Returns `true` if matching row exists, `false` otherwise.
paginatepaginate<R = T>(options?: PaginateOptions<T>): PaginatedResult<R>Performs offset-based pagination on the table.
- options
- Pagination parameters (`page`, `limit`, `where`, `orderBy`, `include`).
tsts const page = db.users.paginate({ page: 2, limit: 20 });console.log(page.data, page.total, page.totalPages);cursorPaginatecursorPaginate<R = T>(options?: CursorPaginateOptions<T>): CursorPaginatedResult<R>Performs cursor-based keyset pagination, ideal for infinite scroll feeds.
- options
- Cursor pagination options (`cursor`, `limit`, `where`, etc.).
tsts const { data, nextCursor, hasMore } = db.posts.cursorPaginate({ limit: 15, cursor });resolveAliasesresolveAliases(data: Record<string, any>): Record<string, any>buildWherebuildWhere(where?: WhereClause<T>): { clause: string; params: any[]; }buildOrderBybuildOrderBy(orderBy?: OrderBy<T> | OrderBy<T>[]): stringresolveRelationsresolveRelations(rows: any[], include: Record<string, boolean>)serializeValueserializeValue(column: string, v: unknown): unknowndeserializeRowdeserializeRow(row: any): T
YattaDB
classCore SQLite database engine powered by `bun:sqlite`.
class YattaDB30 members
schemapropertyschema: DatabaseSchemaActive database schema definition.
relationspropertyrelations: RelationsConfigActive relational associations graph.
pathpropertypath: stringResolved filesystem path to the database file, or `":memory:"`.
debugpropertydebug: booleantablespropertytables:stmtCachepropertystmtCache:MAX_STMT_CACHEpropertyMAX_STMT_CACHE:applyPragmasapplyPragmas(): voidApplies connection pragmas required for safe multi-process access.
Required when several OS processes (e.g. cluster mode via `SO_REUSEPORT`, or containers sharing a volume) write to the same database file: - `journal_mode = WAL` lets readers proceed while a writer holds the lock. - `busy_timeout` waits for a contended lock instead of throwing SQLITE_BUSY. - `synchronous = NORMAL` is safe under WAL and avoids an fsync per commit. Must be re-applied after any connection is replaced (see `restore()`).
[Symbol.dispose][Symbol.dispose]()Explicit resource management disposal hook (`using db = ...`).
sqlitegettersqlite: DatabaseDirect access to the underlying `bun:sqlite` Database instance.
getOrCreateTablegetOrCreateTable(name: string): Table<any, any>tabletable<T extends Record<string, any> = Record<string, any>, TInsert extends Record<string, any> = Partial<T>>(name: string): Table<T, TInsert>Returns a typed gateway for a defined schema table.
- name
- Table name.
unsafeTableunsafeTable<T extends Record<string, any> = Record<string, any>, TInsert extends Record<string, any> = Partial<T>>(name: string): Table<T, TInsert>Returns a gateway for an arbitrary or dynamically generated table not in the schema.
- name
- Table name.
clearStatementCacheclearStatementCache(): voidFinalizes and purges all cached prepared statements.
runrun(sql: string, params?: any[], mode: "get" | "all" | "run"): anyPrepares (or retrieves from LRU cache) and executes an SQL statement with parameters.
- sql
- SQL query string.
- params
- Parameter arguments.
- mode
- Execution mode (`"get"` for single row, `"all"` for all rows, `"run"` for DML).
Returns Query result.
transactiontransaction<R>(fn: (tx: this) => R): RExecutes a callback within an atomic transaction.
- fn
- Callback receiving transaction context.
Returns Value returned from the callback.
tsts const result = db.transaction((tx) => { tx.table("accounts").updateById(fromId, { balance: b1 }); tx.table("accounts").updateById(toId, { balance: b2 }); return true;});rawAllrawAll<R = any>(sql: string, params?: any[]): R[]Executes a raw SQL query and returns all matching rows.
- sql
- SQL statement.
- params
- Parameter values.
Returns Array of resulting rows.
rawGetrawGet<R = any>(sql: string, params?: any[]): R | nullExecutes a raw SQL query and returns the first row or `null`.
- sql
- SQL statement.
- params
- Parameter values.
Returns Single row or `null`.
rawRunrawRun(sql: string, params?: any[]): { lastInsertRowid: number; changes: number; }Executes a raw DML/DDL statement returning affected changes and last inserted row id.
- sql
- SQL statement.
- params
- Parameter values.
Returns Execution metadata (`lastInsertRowid`, `changes`).
rawraw<R = any>(sql: string, params?: any[], mode?: "get" | "all" | "run"): anyExecutes raw SQL in the specified execution mode.
- sql
- SQL statement.
- params
- Parameter values.
- mode
- Execution mode (`"get"`, `"all"`, or `"run"`).
execexec(sql: string): { lastInsertRowid: number; changes: number; }Executes raw multi-statement SQL script directly on the database.
- sql
- SQL script.
checkIntegritycheckIntegrity(): booleanPerforms an SQLite database integrity inspection (`PRAGMA quick_check;`).
Returns `true` if database integrity is healthy, `false` otherwise.
buildColumnDefFragmentbuildColumnDefFragment(colName: string, def: ColumnDefinition, mode: "create" | "alter"): stringsyncSchemasyncSchema(): voidCompares the defined TypeScript schema against the live SQLite tables and automatically:
syncSchemaBodysyncSchemaBody(schemaHash: string): voidApplies the schema inside an open transaction.
migratemigrate(migrations: Migration[]): Promise<{ applied: string[]; }>Applies programmatic migrations tracking applied versions in `_yatta_migrations`.
- migrations
- Array of steps to evaluate.
Returns Object listing newly applied migration names.
formatDefaultformatDefault(def: ColumnDefinition): stringbackupbackup(destPath: string): { success: boolean; path: string; }Performs an atomic online backup snapshot of the database using SQLite's `VACUUM INTO`.
- destPath
- Destination file path for the backup.
Returns Object indicating success and destination path.
tsts db.backup("Database/backups/backup-2026-01-01.db");restorerestore(backupPath: string): { success: boolean; }Restores the database from a backup file:
- backupPath
- File path to the SQLite backup to restore from.
Returns Object indicating success.
closeclose(): voidCloses the SQLite database connection, frees prepared statements,
YattaError
classBase error class for YattaDB database operations.
class YattaError extends ErrorTypes
ColumnDefinition
interfaceInternal schema descriptor capturing column characteristics, constraints, and relational properties.
interface ColumnDefinition13 members
typepropertytype: SQLiteTypeUnderlying SQLite storage affinity type.
primaryKeypropertyprimaryKey?: booleanWhether the column serves as the table's primary key.
autoIncrementpropertyautoIncrement?: booleanWhether values auto-increment on insert (SQLite INTEGER PRIMARY KEY only).
notNullpropertynotNull?: booleanWhether column rejects null values (`NOT NULL` constraint).
uniquepropertyunique?: booleanWhether unique constraint/index is applied.
defaultValuepropertydefaultValue?: unknownDefault value expression or constant.
referencespropertyreferences?: { table: string; column: string; onDelete?: string; }Foreign key target reference metadata.
isIndexpropertyisIndex?: booleanWhether an index should be created on this column.
isBooleanpropertyisBoolean?: booleanWhether column is treated as a boolean (mapped between boolean and 0/1 in SQLite).
isJsonpropertyisJson?: booleanWhether column stores JSON data (automatically serialized/deserialized).
isUuidpropertyisUuid?: booleanWhether column is auto-generated as a UUID v4 string on insert.
touchOnUpdatepropertytouchOnUpdate?: booleanWhether column automatically refreshes to current timestamp upon updates.
checkValuespropertycheckValues?: readonly string[]Constrained allowed string literal values for CHECK constraint.
CursorPaginatedResult
interfaceEnvelope containing cursor-paginated data and next page token.
interface CursorPaginatedResult<T>3 members
datapropertydata: T[]Page of records.
nextCursorpropertynextCursor: string | nullBase64 token for fetching the next page, or `null` if no further records exist.
hasMorepropertyhasMore: booleanWhether additional records exist beyond this page.
CursorPaginateOptions
interfaceOptions for cursor-based (keyset) pagination, ideal for infinite scroll feeds.
interface CursorPaginateOptions<T = any>7 members
cursorpropertycursor?: stringBase64-encoded cursor token from a previous page.
cursorColumnpropertycursorColumn?: keyof TPrimary column to sort and paginate on (defaults to primary key).
tieBreakerpropertytieBreaker?: keyof TSecondary tie-breaker column to ensure deterministic sorting.
limitpropertylimit?: numberNumber of items to fetch. Defaults to 10.
wherepropertywhere?: WhereClause<T>Filter conditions.
orderByDirectionpropertyorderByDirection?: "asc" | "desc"Sort order direction. Defaults to `"desc"`.
includepropertyinclude?: Record<string, boolean>Eager-loaded relations.
DatabaseOptions
interfaceConfiguration options for initializing a instance.
interface DatabaseOptions6 members
pathpropertypath?: stringFile system path to the database (e.g. `"Database/app.db"`), or `":memory:"`.
schemapropertyschema?: DatabaseSchemaFull database table schema definition dictionary.
relationspropertyrelations?: RelationsConfigRelational associations configuration for eager loading.
autoMigratepropertyautoMigrate?: booleanWhether to automatically create tables and alter missing columns on startup. Defaults to `true`.
debugpropertydebug?: booleanWhether to log executed SQL queries with millisecond execution durations to stdout.
forceNewpropertyforceNew?: booleanIf `true`, creates a new instance even if a database at this path is already cached in registry.
DBFunction
interfaceCallable signature of the global `DB` accessor.
interface DBFunction<S extends DatabaseSchema = RegisteredSchema>3 members
[call]call(): TypedDatabase<CustomSchema>[call]call(tableName: K): Table<InferRow<S[K]>, InferInsert<S[K]>>[call]call(tableName: string): Table<T, TInsert>
FindOptions
interfaceQuery options for searching and fetching table rows.
interface FindOptions<T = any, K extends keyof T = keyof T>6 members
wherepropertywhere?: WhereClause<T>Filter conditions to restrict rows.
orderBypropertyorderBy?: OrderBy<T> | OrderBy<T>[]Column sorting criteria.
takepropertytake?: numberMaximum number of records to return.
skippropertyskip?: numberNumber of records to skip (offset).
selectpropertyselect?: K[]Specific columns to project/select.
includepropertyinclude?: Record<string, boolean>Eager-loaded relational associations to populate.
Migration
interfaceProgrammatic migration step definition.
interface Migration3 members
namepropertyname: stringUnique migration identifier (e.g. `"20260101_init"`).
uppropertyup: (db: YattaDB) => void | Promise<void>Forward migration execution callback.
downpropertydown?: (db: YattaDB) => void | Promise<void>Optional rollback migration callback.
PaginatedResult
interfaceEnvelope containing paginated records and metadata.
interface PaginatedResult<T>5 members
datapropertydata: T[]Array of records for the requested page.
totalpropertytotal: numberTotal count of records matching the filter.
pagepropertypage: numberCurrent page number (1-indexed).
limitpropertylimit: numberNumber of records per page.
totalPagespropertytotalPages: numberTotal number of pages available.
PaginateOptions
interfacePagination options for offset-based queries.
interface PaginateOptions<T = any>5 members
pagepropertypage?: numberPage number (1-indexed). Defaults to 1.
limitpropertylimit?: numberNumber of records per page. Defaults to 10.
wherepropertywhere?: WhereClause<T>Filter conditions.
orderBypropertyorderBy?: OrderBy<T> | OrderBy<T>[]Sorting criteria.
includepropertyinclude?: Record<string, boolean>Eager-loaded relations.
Register
interfaceGlobal schema registry for declaration merging.
interface Registerdeclare module "../types/db" { interface Register { schema: typeof schema; }}UpsertOptions
interfaceConfiguration options for atomic insert-or-update (upsert) operations.
interface UpsertOptions<T, TInsert = Partial<T>>3 members
wherepropertywhere: WhereClause<T>Matching criteria to determine if the record exists.
createpropertycreate: TInsertPayload to insert if no matching record is found.
updatepropertyupdate: Partial<TInsert | T>Partial updates to apply if the record already exists.
DatabaseSchema
typeRepresents the complete database schema mapping table names to their .
type DatabaseSchema = Record<string, TableSchema>DBProxy
typeCombined type of the global `DB` accessor: function call, table property accessors, and YattaDB engine methods.
type DBProxy<S extends DatabaseSchema = RegisteredSchema> = DBFunction<S> & { readonly [K in keyof S]: Table<InferRow<S[K]>, InferInsert<S[K]>>; } & YattaDBFieldFilter
typeCondition applied to a single column: direct literal match, operator filter object, or `null`.
type FieldFilter<T> = T | FilterOperator<T> | nullFieldsProxy
typeProxy object providing English comparison methods for each column in a row.
type FieldsProxy<Row> = { [K in keyof Row]-?: FieldFor<NonNullable<Row[K]>>; }FilterOperator
typeOperator filters available for field comparisons in a .
type FilterOperator<T> = BaseFilterOps<T> & (T extends string ? TextFilterOps : {}) & (T extends number ? NumericFilterOps<T> : {})InferInsert
typeInfers the input payload TypeScript type accepted when inserting a new row into a table schema.
type InferInsert<S extends TableSchema> = Prettify<BaseInsert<S> & RelationAliases<S>>InferRow
typeInfers the full output row TypeScript type returned when querying a table schema.
type InferRow<S extends TableSchema> = Prettify<{ [K in keyof S]: ColumnValue<S[K]>; }>OrderBy
typeOrdering specification mapping column names to sort directions.
type OrderBy<T = Record<string, any>> = { [K in keyof T]?: OrderDirection; }OrderDirection
typeDirection for sorting results: ascending or descending.
type OrderDirection = "asc" | "desc" | "ASC" | "DESC"Prettify
typeUtility type to expand mapped object types into clean, readable tooltips in IDEs.
type Prettify<T> = { [K in keyof T]: T[K]; } & {}RegisteredSchema
typeResolves the active schema type registered via declaration merging,
type RegisteredSchema = Register extends { schema: infer S extends DatabaseSchema; } ? S : DatabaseSchemaRelationDefinition
typeDefinition of a relationship between two tables for eager loading via `include`.
type RelationDefinition = { hasMany: string; foreignKey: string; } | { belongsTo: string; foreignKey: string; } | { hasOne: string; foreignKey: string; }RelationsConfig
typeRelational graph configuration dictionary mapping tables and relation names to definitions.
type RelationsConfig = Record<string, Record<string, RelationDefinition>>SQLiteType
typeSupported SQLite underlying column storage affinity types.
type SQLiteType = "INTEGER" | "TEXT" | "REAL" | "BLOB"TableSchema
typeRepresents a table schema mapping column identifiers to their definitions.
type TableSchema = Record<string, ColumnBuilder<any, any, any>>TypedDatabase
typeType-safe database interface offering table properties (`db.users`),
type TypedDatabase<S extends DatabaseSchema = DatabaseSchema> = YattaDB & { readonly [K in keyof S]: Table<InferRow<S[K]>, InferInsert<S[K]>>; } & { <K extends keyof S>(tableName: K): Table<InferRow<S[K]>, InferInsert<S[K]>>; (): TypedDatabase<S>; (tableName: string): Table<any, any>; }WhereClause
typeDeclarative WHERE clause supporting field conditions, boolean logical groupings (`AND`, `OR`), and nested filters.
type WhereClause<T = Record<string, any>> = { [K in keyof T]?: FieldFilter<T[K]>; } & { OR?: WhereClause<T>[]; AND?: WhereClause<T>[]; }{ status: "active", email: { contains: "@gmail.com" }, age: { gte: 18 }, OR: [ { role: "admin" }, { verified: true }, ],}AuthConfig or JobPayload — declaring your schema once is enough for the rest to follow. See Typed keys.