Skip to content

Database

The main entry point. A database is a directory on disk; tables live as separate JSON files.

database

The :class:Database — TinyStore's main entry point.

A database is a directory on disk. Tables live as separate JSON files, metadata in metadata.json, locking via tinystore.lock. Register Pydantic-based models, then insert / query / update / delete.

Database

Database(
    path: str | Path,
    *,
    lock_timeout: float = 30.0,
    optimistic_concurrency: bool = True,
    debug: bool = False,
    storage: JsonStorage | None = None,
    lock_manager: LockManager | None = None,
)

A TinyStore database rooted at a filesystem directory.

Parameters:

Name Type Description Default
path str | Path

Database directory. Created if missing.

required
lock_timeout float

Seconds to wait for the database-wide lock before raising :class:~tinystore.exceptions.LockTimeoutError.

30.0
optimistic_concurrency bool

If True (default), writes check a hidden row version and raise :class:~tinystore.exceptions.StaleDataError on stale updates.

True
debug bool

Enable debug logging.

False

lock

lock(
    *, timeout: float | None = None
) -> Iterator[LockHandle]

Acquire the database-wide write lock for the duration of the block.

register

register(model_cls: type[T]) -> type[T]

Register a model class with this database.

Creates its table file if missing, validates schema compatibility with any previously-persisted schema, and updates metadata.json.

reset_schema

reset_schema() -> None

Discard all stored schema metadata (destructive — does NOT delete data).

related

related(obj: Model, name: str) -> Any

Explicitly load a related model or list of models for a relationship.

For a many-to-one / one-to-one relationship (the FK lives on this side) returns a single instance, or None when the FK is null or the referenced row is gone. For a one-to-many relationship (the FK lives on the related side) returns a list of instances.

The side is inferred from the declared foreign_key: if it names a local FK field, this is the "one" end (follow the FK to its parent); otherwise the related model is found by scanning registered models for one whose field named foreign_key points back at this table.

check

check() -> list[str]

Validate on-disk state. Returns a list of problem descriptions.

Checks that every table file parses, primary keys are unique, next_id exceeds the largest id in use, and registered foreign keys resolve to an existing row in the referenced table. An empty list means the database is consistent; problems are also logged at WARNING level.

backup

backup(target: str | Path) -> Path

Snapshot the database (excluding the lock file and journals).