API reference

yatta/db

Typed SQLite: schema, relations, queries, migrations.

39 exported symbols and 143 members, read from src/types/db.ts.

Construct

and

function

Combines multiple conditions with a logical `AND`.

and(...conds: Condition[]): Condition
conds
List of conditions to combine.

Returns Combined .

tsts
and(f.age.isGreaterThan(21), f.country.isEqualTo("US"))

connect

function

Helper function for connecting existing records in relational operations.

connect<T>(row: T): T
row
Record to connect.

Returns The unchanged row.

createDatabase

function

Creates, 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.

tsts
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

function

Combines multiple conditions with a logical `OR`.

or(...conds: Condition[]): Condition
conds
List of conditions to combine.

Returns Combined .

tsts
or(f.role.isEqualTo("admin"), f.role.isEqualTo("moderator"))

resolveDatabasePath

function

Resolves 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

class

Fluent builder for defining table columns with strong typing and constraint chaining.

11 members

  • defproperty
    def: ColumnDefinition

    Internal column configuration definition.

  • clone
    clone<V2 = V, O2 extends boolean = Optional, R2 extends boolean = IsRef>(patch: Partial<ColumnDefinition>): ColumnBuilder<V2, O2, R2>
  • primaryKey
    primaryKey(): ColumnBuilder<V, Optional, IsRef>

    Designates this column as the primary key of the table.

    Returns Column builder configured as primary key.

  • autoIncrement
    autoIncrement(): ColumnBuilder<V, true, IsRef>

    Configures automatic sequence incrementation on primary key insert.

    Returns Column builder configured for auto-increment.

  • nullable
    nullable(): ColumnBuilder<V | null, true, IsRef>

    Allows the column to store `NULL` values.

    Returns Column builder typed as nullable.

  • notNull
    notNull(): ColumnBuilder<NonNullable<V>, false, IsRef>

    Enforces a `NOT NULL` constraint on the column.

    Returns Column builder typed as non-nullable.

  • unique
    unique(): ColumnBuilder<V, Optional, IsRef>

    Adds a `UNIQUE` constraint and index on this column.

    Returns Column builder with unique constraint.

  • default
    default(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.

  • index
    index(): ColumnBuilder<V, Optional, IsRef>

    Creates an SQLite index on this column for faster queries and lookups.

    Returns Column builder flagged for index creation.

  • references
    references(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" })
  • belongsTo
    belongsTo(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

class

Represents a composable filter predicate node in the English-like filtering DSL.

class Condition
tsts
const condition = f.age.isGreaterThan(18).and(f.status.isEqualTo("active"));

3 members

  • and
    and(other: Condition): Condition

    Combines this condition with another using a logical `AND`.

    other
    The other condition to combine with.

    Returns A combined .

  • or
    or(other: Condition): Condition

    Combines this condition with another using a logical `OR`.

    other
    The other condition to combine with.

    Returns A combined .

  • toWhere
    toWhere(): WhereClause<any>

    Compiles this condition tree into a standard declarative .

    Returns Compiled where clause object.

QueryBuilder

class

Fluent query builder for constructing, filtering, sorting, selecting, and executing queries.

tsts
const activeUsers = db.users  .where((f) => f.status.isEqualTo("active"))  .orderBy({ createdAt: "desc" })  .take(10)  .all();

13 members

  • optsproperty
    opts: FindOptions<T>
  • where
    where(clauseOrFn: WhereClause<T> | ((fields: FieldsProxy<T>) => Condition)): this

    Adds 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" });
  • orderBy
    orderBy(order: OrderBy<T> | OrderBy<T>[]): this

    Applies sort ordering criteria to the query.

    order
    Ordering configuration (e.g. `{ createdAt: "desc" }`).

    Returns Current query builder for chaining.

  • take
    take(n: number): this

    Sets the maximum number of rows to return (`LIMIT`).

    n
    Maximum number of rows.

    Returns Current query builder for chaining.

  • limit
    limit(n: number): this

    Alias for . Sets the maximum number of rows to return.

    n
    Maximum row limit.

    Returns Current query builder for chaining.

  • skip
    skip(n: number): this

    Sets the number of rows to skip (`OFFSET`).

    n
    Number of rows to bypass.

    Returns Current query builder for chaining.

  • select
    select<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 }[]
  • include
    include<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();
  • all
    all(): TResult[]

    Executes the query and returns all matching rows as an array.

    Returns Array of resulting records.

  • first
    first(): TResult | null

    Executes the query and returns the first matching row, or `null` if none found.

    Returns The first matching record or `null`.

  • count
    count(): number

    Counts the total number of rows matching the query filters.

    Returns Count of matching records.

  • exists
    exists(): boolean

    Checks whether at least one row matches the query filter.

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

  • paginate
    paginate(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

class

Type-safe CRUD table gateway providing querying, insertions, updates, deletions,

class Table
tsts
const 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

  • columnsproperty
    columns: Map<string, ColumnDefinition>

    Map of column definitions belonging to this table.

  • primaryKeyColumnproperty
    primaryKeyColumn: string

    The primary key column name for this table (defaults to `"id"`).

  • belongsToAliasesproperty
    belongsToAliases: Map<string, { column: string; table: string; }>

    Inferred relational foreign key aliases (e.g. `userId` -> `user`).

  • where
    where(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();
  • insert
    insert(data: TInsert): T

    Inserts 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" });
  • insertMany
    insertMany(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" },]);
  • findFirst
    findFirst<K extends keyof T>(options: FindOptions<T, K> & { select: K[]; }): Prettify<Pick<T, K>> | null

    Finds 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.

  • findFirst
    findFirst(options?: FindOptions<T, keyof T>): T | null

    Finds the first row matching the specified criteria.

    options
    Optional query criteria.

    Returns Full record or `null` if no match.

  • findFirst
    findFirst<K extends keyof T = keyof T, R = Pick<T, K>>(options?: FindOptions<T, K>): R | null
  • first
    first(): T | null

    Shorthand to retrieve the very first row in the table.

    Returns First row or `null` if table is empty.

  • findById
    findById<K extends keyof T>(id: string | number, options: { select: K[]; include?: Record<string, boolean>; }): Prettify<Pick<T, K>> | null

    Finds 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.

  • findById
    findById(id: string | number, options?: { select?: undefined; include?: Record<string, boolean>; }): T | null

    Finds a row by its primary key.

    id
    Primary key value.
    options
    Optional relation inclusion options.

    Returns Full record or `null` if not found.

  • findById
    findById<K extends keyof T = keyof T, R = Pick<T, K>>(id: string | number, options?: { select?: K[]; include?: Record<string, boolean>; }): R | null
  • findMany
    findMany<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.

  • findMany
    findMany(options?: FindOptions<T, keyof T>): T[]

    Finds all rows matching the specified criteria.

    options
    Optional query criteria.

    Returns Array of full records.

  • findMany
    findMany<K extends keyof T = keyof T, R = Pick<T, K>>(options?: FindOptions<T, K>): R[]
  • buildSetClause
    buildSetClause(data: Record<string, any>): { setSql: string; params: any[]; }
  • update
    update(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" },});
  • updateById
    updateById(id: string | number, data: Partial<TInsert | T>): T | null

    Updates 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" });
  • upsert
    upsert({ where, create, update }: UpsertOptions<T, TInsert>): T

    Atomically 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" },});
  • delete
    delete(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" } });
  • deleteById
    deleteById(id: string | number): boolean

    Deletes 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);
  • count
    count(where?: WhereClause<T>): number

    Counts the total number of rows matching an optional filter.

    where
    Optional filter condition.

    Returns Total row count.

  • exists
    exists(where?: WhereClause<T>): boolean

    Checks whether at least one row exists matching the specified criteria.

    where
    Optional filter condition.

    Returns `true` if matching row exists, `false` otherwise.

  • paginate
    paginate<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);
  • cursorPaginate
    cursorPaginate<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 });
  • resolveAliases
    resolveAliases(data: Record<string, any>): Record<string, any>
  • buildWhere
    buildWhere(where?: WhereClause<T>): { clause: string; params: any[]; }
  • buildOrderBy
    buildOrderBy(orderBy?: OrderBy<T> | OrderBy<T>[]): string
  • resolveRelations
    resolveRelations(rows: any[], include: Record<string, boolean>)
  • serializeValue
    serializeValue(column: string, v: unknown): unknown
  • deserializeRow
    deserializeRow(row: any): T

YattaDB

class

Core SQLite database engine powered by `bun:sqlite`.

class YattaDB

30 members

  • schemaproperty
    schema: DatabaseSchema

    Active database schema definition.

  • relationsproperty
    relations: RelationsConfig

    Active relational associations graph.

  • pathproperty
    path: string

    Resolved filesystem path to the database file, or `":memory:"`.

  • debugproperty
    debug: boolean
  • tablesproperty
    tables:
  • stmtCacheproperty
    stmtCache:
  • MAX_STMT_CACHEproperty
    MAX_STMT_CACHE:
  • applyPragmas
    applyPragmas(): void

    Applies 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 = ...`).

  • sqlitegetter
    sqlite: Database

    Direct access to the underlying `bun:sqlite` Database instance.

  • getOrCreateTable
    getOrCreateTable(name: string): Table<any, any>
  • table
    table<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.
  • unsafeTable
    unsafeTable<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.
  • clearStatementCache
    clearStatementCache(): void

    Finalizes and purges all cached prepared statements.

  • run
    run(sql: string, params?: any[], mode: "get" | "all" | "run"): any

    Prepares (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.

  • transaction
    transaction<R>(fn: (tx: this) => R): R

    Executes 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;});
  • rawAll
    rawAll<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.

  • rawGet
    rawGet<R = any>(sql: string, params?: any[]): R | null

    Executes a raw SQL query and returns the first row or `null`.

    sql
    SQL statement.
    params
    Parameter values.

    Returns Single row or `null`.

  • rawRun
    rawRun(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`).

  • raw
    raw<R = any>(sql: string, params?: any[], mode?: "get" | "all" | "run"): any

    Executes raw SQL in the specified execution mode.

    sql
    SQL statement.
    params
    Parameter values.
    mode
    Execution mode (`"get"`, `"all"`, or `"run"`).
  • exec
    exec(sql: string): { lastInsertRowid: number; changes: number; }

    Executes raw multi-statement SQL script directly on the database.

    sql
    SQL script.
  • checkIntegrity
    checkIntegrity(): boolean

    Performs an SQLite database integrity inspection (`PRAGMA quick_check;`).

    Returns `true` if database integrity is healthy, `false` otherwise.

  • buildColumnDefFragment
    buildColumnDefFragment(colName: string, def: ColumnDefinition, mode: "create" | "alter"): string
  • syncSchema
    syncSchema(): void

    Compares the defined TypeScript schema against the live SQLite tables and automatically:

  • syncSchemaBody
    syncSchemaBody(schemaHash: string): void

    Applies the schema inside an open transaction.

  • migrate
    migrate(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.

  • formatDefault
    formatDefault(def: ColumnDefinition): string
  • backup
    backup(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");
  • restore
    restore(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.

  • close
    close(): void

    Closes the SQLite database connection, frees prepared statements,

YattaError

class

Base error class for YattaDB database operations.

class YattaError extends Error

Types

ColumnDefinition

interface

Internal schema descriptor capturing column characteristics, constraints, and relational properties.

13 members

  • typeproperty
    type: SQLiteType

    Underlying SQLite storage affinity type.

  • primaryKeyproperty
    primaryKey?: boolean

    Whether the column serves as the table's primary key.

  • autoIncrementproperty
    autoIncrement?: boolean

    Whether values auto-increment on insert (SQLite INTEGER PRIMARY KEY only).

  • notNullproperty
    notNull?: boolean

    Whether column rejects null values (`NOT NULL` constraint).

  • uniqueproperty
    unique?: boolean

    Whether unique constraint/index is applied.

  • defaultValueproperty
    defaultValue?: unknown

    Default value expression or constant.

  • referencesproperty
    references?: { table: string; column: string; onDelete?: string; }

    Foreign key target reference metadata.

  • isIndexproperty
    isIndex?: boolean

    Whether an index should be created on this column.

  • isBooleanproperty
    isBoolean?: boolean

    Whether column is treated as a boolean (mapped between boolean and 0/1 in SQLite).

  • isJsonproperty
    isJson?: boolean

    Whether column stores JSON data (automatically serialized/deserialized).

  • isUuidproperty
    isUuid?: boolean

    Whether column is auto-generated as a UUID v4 string on insert.

  • touchOnUpdateproperty
    touchOnUpdate?: boolean

    Whether column automatically refreshes to current timestamp upon updates.

  • checkValuesproperty
    checkValues?: readonly string[]

    Constrained allowed string literal values for CHECK constraint.

CursorPaginatedResult

interface

Envelope containing cursor-paginated data and next page token.

3 members

  • dataproperty
    data: T[]

    Page of records.

  • nextCursorproperty
    nextCursor: string | null

    Base64 token for fetching the next page, or `null` if no further records exist.

  • hasMoreproperty
    hasMore: boolean

    Whether additional records exist beyond this page.

CursorPaginateOptions

interface

Options for cursor-based (keyset) pagination, ideal for infinite scroll feeds.

interface CursorPaginateOptions<T = any>

7 members

  • cursorproperty
    cursor?: string

    Base64-encoded cursor token from a previous page.

  • cursorColumnproperty
    cursorColumn?: keyof T

    Primary column to sort and paginate on (defaults to primary key).

  • tieBreakerproperty
    tieBreaker?: keyof T

    Secondary tie-breaker column to ensure deterministic sorting.

  • limitproperty
    limit?: number

    Number of items to fetch. Defaults to 10.

  • whereproperty
    where?: WhereClause<T>

    Filter conditions.

  • orderByDirectionproperty
    orderByDirection?: "asc" | "desc"

    Sort order direction. Defaults to `"desc"`.

  • includeproperty
    include?: Record<string, boolean>

    Eager-loaded relations.

DatabaseOptions

interface

Configuration options for initializing a instance.

interface DatabaseOptions

6 members

  • pathproperty
    path?: string

    File system path to the database (e.g. `"Database/app.db"`), or `":memory:"`.

  • schemaproperty
    schema?: DatabaseSchema

    Full database table schema definition dictionary.

  • relationsproperty
    relations?: RelationsConfig

    Relational associations configuration for eager loading.

  • autoMigrateproperty
    autoMigrate?: boolean

    Whether to automatically create tables and alter missing columns on startup. Defaults to `true`.

  • debugproperty
    debug?: boolean

    Whether to log executed SQL queries with millisecond execution durations to stdout.

  • forceNewproperty
    forceNew?: boolean

    If `true`, creates a new instance even if a database at this path is already cached in registry.

DBFunction

interface

Callable signature of the global `DB` accessor.

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

interface

Query options for searching and fetching table rows.

interface FindOptions<T = any, K extends keyof T = keyof T>

6 members

  • whereproperty
    where?: WhereClause<T>

    Filter conditions to restrict rows.

  • orderByproperty
    orderBy?: OrderBy<T> | OrderBy<T>[]

    Column sorting criteria.

  • takeproperty
    take?: number

    Maximum number of records to return.

  • skipproperty
    skip?: number

    Number of records to skip (offset).

  • selectproperty
    select?: K[]

    Specific columns to project/select.

  • includeproperty
    include?: Record<string, boolean>

    Eager-loaded relational associations to populate.

Migration

interface

Programmatic migration step definition.

interface Migration

3 members

  • nameproperty
    name: string

    Unique migration identifier (e.g. `"20260101_init"`).

  • upproperty
    up: (db: YattaDB) => void | Promise<void>

    Forward migration execution callback.

  • downproperty
    down?: (db: YattaDB) => void | Promise<void>

    Optional rollback migration callback.

PaginatedResult

interface

Envelope containing paginated records and metadata.

interface PaginatedResult<T>

5 members

  • dataproperty
    data: T[]

    Array of records for the requested page.

  • totalproperty
    total: number

    Total count of records matching the filter.

  • pageproperty
    page: number

    Current page number (1-indexed).

  • limitproperty
    limit: number

    Number of records per page.

  • totalPagesproperty
    totalPages: number

    Total number of pages available.

PaginateOptions

interface

Pagination options for offset-based queries.

interface PaginateOptions<T = any>

5 members

  • pageproperty
    page?: number

    Page number (1-indexed). Defaults to 1.

  • limitproperty
    limit?: number

    Number of records per page. Defaults to 10.

  • whereproperty
    where?: WhereClause<T>

    Filter conditions.

  • orderByproperty
    orderBy?: OrderBy<T> | OrderBy<T>[]

    Sorting criteria.

  • includeproperty
    include?: Record<string, boolean>

    Eager-loaded relations.

Register

interface

Global schema registry for declaration merging.

interface Register
tsts
declare module "../types/db" {  interface Register {    schema: typeof schema;  }}

UpsertOptions

interface

Configuration options for atomic insert-or-update (upsert) operations.

interface UpsertOptions<T, TInsert = Partial<T>>

3 members

  • whereproperty
    where: WhereClause<T>

    Matching criteria to determine if the record exists.

  • createproperty
    create: TInsert

    Payload to insert if no matching record is found.

  • updateproperty
    update: Partial<TInsert | T>

    Partial updates to apply if the record already exists.

DatabaseSchema

type

Represents the complete database schema mapping table names to their .

type DatabaseSchema = Record<string, TableSchema>

DBProxy

type

Combined 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]>>; } & YattaDB

FieldFilter

type

Condition applied to a single column: direct literal match, operator filter object, or `null`.

type FieldFilter<T> = T | FilterOperator<T> | null

FieldsProxy

type

Proxy object providing English comparison methods for each column in a row.

type FieldsProxy<Row> = { [K in keyof Row]-?: FieldFor<NonNullable<Row[K]>>; }

FilterOperator

type

Operator filters available for field comparisons in a .

type FilterOperator<T> = BaseFilterOps<T> & (T extends string ? TextFilterOps : {}) & (T extends number ? NumericFilterOps<T> : {})

InferInsert

type

Infers 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

type

Infers 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

type

Ordering specification mapping column names to sort directions.

type OrderBy<T = Record<string, any>> = { [K in keyof T]?: OrderDirection; }

OrderDirection

type

Direction for sorting results: ascending or descending.

type OrderDirection = "asc" | "desc" | "ASC" | "DESC"

Prettify

type

Utility type to expand mapped object types into clean, readable tooltips in IDEs.

type Prettify<T> = { [K in keyof T]: T[K]; } & {}

RegisteredSchema

type

Resolves the active schema type registered via declaration merging,

type RegisteredSchema = Register extends { schema: infer S extends DatabaseSchema; } ? S : DatabaseSchema

RelationDefinition

type

Definition 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

type

Relational graph configuration dictionary mapping tables and relation names to definitions.

type RelationsConfig = Record<string, Record<string, RelationDefinition>>

SQLiteType

type

Supported SQLite underlying column storage affinity types.

type SQLiteType = "INTEGER" | "TEXT" | "REAL" | "BLOB"

TableSchema

type

Represents a table schema mapping column identifiers to their definitions.

type TableSchema = Record<string, ColumnBuilder<any, any, any>>

TypedDatabase

type

Type-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

type

Declarative 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>[]; }
tsts
{  status: "active",  email: { contains: "@gmail.com" },  age: { gte: 18 },  OR: [    { role: "admin" },    { verified: true },  ],}
Tip
Most of the types above are inferred. You rarely import AuthConfig or JobPayload — declaring your schema once is enough for the rest to follow. See Typed keys.