Skip to main content

ModelContainer

Struct ModelContainer 

Source
pub struct ModelContainer { /* private fields */ }
Expand description

An open database and the working-set caches over it. Clone is shallow: clones share the connection and the dirty state.

Implementations§

Source§

impl ModelContainer

Source

pub fn try_cache<M: Model>(&self) -> Option<Store<Keyed<M>>>

The cache for M when it is in this container’s schema: the non-panicking ModelContainer::cache.

Source

pub fn delete<M: Model>(&self, id: impl Into<ModelId<M>>) -> Result<(), DbError>

Delete one row, honoring deny rules: a parent still referenced through a DeleteRule::Deny relation is refused with the relation named. Cascade and nullify need no checked door (a plain restructure delete triggers them), but deny cannot refuse after the row is gone, so this is deny’s contract.

Source§

impl ModelContainer

Source

pub const EXTERNAL_AUTHOR: &'static str = "database"

The author tag on changes ModelContainer::check_external merges in: the database’s own contents arriving, distinguishable by every change consumer and never persisted back. Reserved: an app writing stores under this tag would have its writes dropped by the autosave fold.

Source

pub fn open<D: SqliteDriver>( driver: D, schema: Schema, ) -> Result<ModelContainer, DbError>
where D::Connection: 'static,

Open through driver, migrate, and attach every model in schema. Attaching creates or migrates the table and nothing more: no rows load, so open cost does not grow with the file. Autosave is on: any turn that touched a store flushes at its end.

Source

pub fn open_with<D: SqliteDriver>( driver: D, schema: Schema, plan: MigrationPlan, ) -> Result<ModelContainer, DbError>
where D::Connection: 'static,

ModelContainer::open, with hand-written migration stages that run first.

Source

pub fn cache<M: Model>(&self) -> Store<Keyed<M>>

The working-set cache for M, an ordinary day-model store holding the rows currently resident and not the table: its keys() are whatever happens to be faulted in. Bindings and accessors work on it unchanged; enumerate rows through a ModelContainer::query, never through the cache. Panics only if M was not in the container’s schema!, which is a wiring bug worth stopping on.

Source

pub fn capabilities(&self) -> Capabilities

What the driver can and cannot do.

Source

pub fn set_autosave(&self, on: bool)

Autosave on/off (default on). Off, changes accumulate until ModelContainer::save, and live queries answer from the last save, since only the file can answer them.

Source

pub fn set_cache_limit(&self, rows: usize)

The soft per-table bound on resident rows (default DEFAULT_CACHE_LIMIT). Dirty rows and rows something observes never evict; beyond that, faulting past the limit releases the oldest resident rows. usize::MAX disables eviction. Lowering the limit enforces it immediately.

Source

pub fn set_blob_cache_limit(&self, bytes: usize)

Bound, in bytes, on the lazy Blob values kept in memory after a read or a flush (default DEFAULT_BLOB_CACHE_LIMIT). Lowering it releases the oldest entries now; a value larger than the limit is served but never kept.

Source

pub fn blob_cache_bytes(&self) -> usize

Bytes the blob memo currently holds.

Source

pub fn blob_cache_len(&self) -> usize

Values the blob memo currently holds.

Source

pub fn install_transaction_participant( &self, participant: impl TransactionParticipant, ) -> Result<(), DbError>

Install one transaction extension before exposing the container to writers. Registration does not initialize its schema; do that in the worker factory first. No replacement or removal is supported, preventing a sync-enabled connection silently losing journaling.

Source

pub fn last_error(&self) -> Signal<Option<String>>

The last autosave failure, if any, as a tracked signal the UI can watch.

Source

pub fn save(&self) -> Result<(), DbError>

Flush every pending change now, in one transaction. Autosave calls this at turn end; call it directly where the error matters at a known point.

Source

pub fn record_sql(&self, f: impl FnOnce()) -> Result<Vec<String>, DbError>

Run f and return the SQL one flush of everything it changed issues: the headless persistence assert (autosave is suspended for the duration so the statements land here). Twenty keystrokes into one field come back as one UPDATE.

Source

pub fn get<M: Model>(&self, id: impl Into<ModelId<M>>) -> Option<Elem<M>>

One row, made resident (faulted from the file if it was not). None when no such row exists (or a driver error surfaced, observable through ModelContainer::last_error).

Source

pub fn try_get<M: Model>( &self, id: impl Into<ModelId<M>>, ) -> Result<Option<Elem<M>>, DbError>

Read a row, distinguishing an absent key from a storage or decoding failure.

Source

pub fn ensure_resident<M: Model>(&self, keys: &[u64]) -> Result<(), DbError>

Make these rows resident, faulting the missing ones in one chunked SELECT. Rows the file does not have are not resident afterwards; rows deleted this turn are not resurrected.

Source

pub fn ensure<M: Model>( &self, ids: impl IntoIterator<Item = impl Into<ModelId<M>>>, ) -> Result<(), DbError>

Source

pub fn warm<M: Model>(&self) -> Result<usize, DbError>

Fault every row of M’s table in: the document pattern, said explicitly. A sketch’s scene or a settings table is the working set, and the app that draws all of it warms it once at open. Raise the cache limit first (set_cache_limit(usize::MAX) for a document container) so the warmed rows are not immediately eligible to leave; rows deleted this turn stay deleted. Returns how many rows are resident afterward.

Source

pub fn insert<M: Model>(&self, row: M)

Insert one row through the front door: it becomes resident and dirty, announces, and folds to one INSERT at the next flush.

Source

pub fn table_count<M: Model>(&self) -> Result<u64, DbError>

SELECT COUNT(*): the table’s true size, which the cache cannot know. Settles pending writes first (with autosave), like every other read.

Source

pub fn backup_to(&self, path: &Path) -> Result<(), DbError>

VACUUM INTO: a transactionally consistent, already-compacted snapshot, taken while the app keeps writing. Restore is an open, not a verb.

Source

pub fn integrity_check(&self) -> Result<Vec<String>, DbError>

PRAGMA integrity_check and PRAGMA foreign_key_check, parsed: an empty list means the database is sound. A foreign-key violation reads foreign key: <child> row <rowid> references missing <parent>; the structured form is ModelContainer::foreign_key_check.

Source

pub fn foreign_key_check(&self) -> Result<Vec<ForeignKeyViolation>, DbError>

PRAGMA foreign_key_check, parsed: every row whose foreign key names a parent that does not exist. Empty when every reference resolves. Runs on the whole file, which is what a migration’s post-check and a settings-page validation both want.

Source

pub fn checkpoint(&self) -> Result<Checkpoint, DbError>

Fold the WAL into the main file (PRAGMA wal_checkpoint(TRUNCATE)), before the OS copies it whole (device backup). The engine’s own answer comes back: whether a reader kept the checkpoint from completing, and how much of the log it folded.

Source

pub fn vacuum(&self) -> Result<(), DbError>

Source

pub fn size_bytes(&self) -> Result<u64, DbError>

Total size in bytes (page_count × page_size).

Source§

impl ModelContainer

Source

pub fn query<M: Model>(&self) -> QueryBuilder<'_, M>

Start a typed query over M’s rows. Panics (like ModelContainer::cache) if M is not in this container’s schema!, a wiring bug worth stopping on.

Source

pub fn query_fn<M: Model>(&self, f: impl Fn() -> Fetch + 'static) -> Query<M>

The reactive-fetch form: f is a computation, so a query whose fetch depends on signals (a search term, a filter toggle) re-derives itself when they change.

Source

pub fn count_fn<M: Model>( &self, f: impl Fn() -> Fetch + 'static, ) -> CountQuery<M>

The reactive-fetch count: a badge whose fetch depends on signals (the “Today” cutoff, a filter toggle) re-counts itself when they change.

Source

pub fn query_raw<M: Model>( &self, sql: impl Into<String>, params: Vec<Value>, tables: &[&str], ) -> Query<M>

Raw SQL, declared: a read-only SELECT returning ids, re-run whenever a flush touches one of the named tables. The price of the escape hatch is whole-query invalidation.

Source

pub fn undo(&self, levels: usize) -> UndoStack

Opt into undo: One history over every store this container manages, levels deep. Undo/redo replay flows through the same change pipeline as the user’s edits, so autosave writes the inverse statements and live queries hear rows come back. Call it once, after open; clear it on migration (UndoStack::clear). While a stack is installed, deletes materialize the rows they remove (a cascade included) so the history can restore them.

Source

pub fn with_connection<R>( &self, f: impl FnOnce(&mut dyn SqliteConnection) -> R, ) -> R

The driver’s connection, directly, for maintenance, imports, or an extension’s statements. Pending changes flush first; writes made here bypass the change log, so call ModelContainer::rescan afterward if they touched Day’s tables.

§Panics

Panics if the pending save fails. Use ModelContainer::try_with_connection when the caller needs to handle storage errors.

Source

pub fn try_with_connection<R>( &self, f: impl FnOnce(&mut dyn SqliteConnection) -> Result<R, DbError>, ) -> Result<R, DbError>

Flush pending edits before accessing the connection. The closure is never run if that save fails; its own error is returned unchanged.

Source

pub fn rescan(&self) -> Result<(), DbError>

Re-read the resident rows from the file and re-run every query: the recovery from writes that bypassed the change log (ModelContainer::with_connection, another process). O(working set + query results), never O(table).

Source

pub fn attach_database( &self, alias: &str, path: &str, schema: Schema, ) -> Result<(), DbError>

Attach another SQLite file under alias and bring schema’s models (every one declared external = "alias") into this container: their tables are read as they are, with no DDL, migration, or fingerprint, through the same caches, queries, and lists as the container’s own. Writes to them fail at flush (the file is attached read-only where the engine honors mode=ro), which is the contract: the other database has its own owner.

Calling it again with the same alias swaps the file: the old one is detached, every resident row of its models dropped, and every live query re-run: the shape a downloaded catalog update takes.

Source

pub fn detach_database(&self, alias: &str) -> Result<(), DbError>

Detach a database ModelContainer::attach_database holds, dropping every resident row of its models. Their stores stay registered (empty), so a query over them answers nothing until the alias is attached again.

Source

pub fn check_external(&self) -> Result<bool, DbError>

Look for other connections’ committed writes (another process, a sync engine, a CLI) and merge what changed. Detection is one PRAGMA data_version (the counter moves only when another connection commits, never for this one’s own writes), so this is cheap enough to wire to app foreground, window focus, or a timer.

When the counter moved, pending local edits flush first; then the resident rows are re-read and diffed: changed fields announce per column, disappearances take the structural path, every live query re-derives, all authored ModelContainer::EXTERNAL_AUTHOR, so the autosave fold declines the echo and an installed undo stack skips them (another author’s writes are not the user’s history). Rows that arrived elsewhere become visible through the re-run queries and fault in like any other row. A row another connection rewrote arrives whole, so its #[model(transient)] fields reset to their defaults, exactly as at fault.

Returns whether anything arrived. On a driver without detection (Capabilities::external_changes) this is Ok(false); writes made through ModelContainer::with_connection are this connection’s own and stay ModelContainer::rescan’s job.

Trait Implementations§

Source§

impl Clone for ModelContainer

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoReactive<T, StaticMark> for T
where T: Clone + 'static,

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.