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
impl ModelContainer
Sourcepub fn try_cache<M: Model>(&self) -> Option<Store<Keyed<M>>>
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.
Sourcepub fn delete<M: Model>(&self, id: impl Into<ModelId<M>>) -> Result<(), DbError>
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
impl ModelContainer
Sourcepub const EXTERNAL_AUTHOR: &'static str = "database"
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.
Sourcepub fn open<D: SqliteDriver>(
driver: D,
schema: Schema,
) -> Result<ModelContainer, DbError>where
D::Connection: 'static,
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.
Sourcepub fn open_with<D: SqliteDriver>(
driver: D,
schema: Schema,
plan: MigrationPlan,
) -> Result<ModelContainer, DbError>where
D::Connection: 'static,
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.
Sourcepub fn cache<M: Model>(&self) -> Store<Keyed<M>>
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.
Sourcepub fn capabilities(&self) -> Capabilities
pub fn capabilities(&self) -> Capabilities
What the driver can and cannot do.
Sourcepub fn set_autosave(&self, on: bool)
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.
Sourcepub fn set_cache_limit(&self, rows: usize)
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.
Sourcepub fn set_blob_cache_limit(&self, bytes: usize)
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.
Sourcepub fn blob_cache_bytes(&self) -> usize
pub fn blob_cache_bytes(&self) -> usize
Bytes the blob memo currently holds.
Sourcepub fn blob_cache_len(&self) -> usize
pub fn blob_cache_len(&self) -> usize
Values the blob memo currently holds.
Sourcepub fn install_transaction_participant(
&self,
participant: impl TransactionParticipant,
) -> Result<(), DbError>
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.
Sourcepub fn last_error(&self) -> Signal<Option<String>>
pub fn last_error(&self) -> Signal<Option<String>>
The last autosave failure, if any, as a tracked signal the UI can watch.
Sourcepub fn save(&self) -> Result<(), DbError>
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.
Sourcepub fn record_sql(&self, f: impl FnOnce()) -> Result<Vec<String>, DbError>
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.
Sourcepub fn get<M: Model>(&self, id: impl Into<ModelId<M>>) -> Option<Elem<M>>
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).
Sourcepub fn try_get<M: Model>(
&self,
id: impl Into<ModelId<M>>,
) -> Result<Option<Elem<M>>, DbError>
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.
Sourcepub fn ensure_resident<M: Model>(&self, keys: &[u64]) -> Result<(), DbError>
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.
Sourcepub fn ensure<M: Model>(
&self,
ids: impl IntoIterator<Item = impl Into<ModelId<M>>>,
) -> Result<(), DbError>
pub fn ensure<M: Model>( &self, ids: impl IntoIterator<Item = impl Into<ModelId<M>>>, ) -> Result<(), DbError>
ModelContainer::ensure_resident, typed ids in.
Sourcepub fn warm<M: Model>(&self) -> Result<usize, DbError>
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.
Sourcepub fn insert<M: Model>(&self, row: M)
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.
Sourcepub fn table_count<M: Model>(&self) -> Result<u64, DbError>
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.
Sourcepub fn backup_to(&self, path: &Path) -> Result<(), DbError>
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.
Sourcepub fn integrity_check(&self) -> Result<Vec<String>, DbError>
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.
Sourcepub fn foreign_key_check(&self) -> Result<Vec<ForeignKeyViolation>, DbError>
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.
Sourcepub fn checkpoint(&self) -> Result<Checkpoint, DbError>
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.
pub fn vacuum(&self) -> Result<(), DbError>
Sourcepub fn size_bytes(&self) -> Result<u64, DbError>
pub fn size_bytes(&self) -> Result<u64, DbError>
Total size in bytes (page_count × page_size).
Source§impl ModelContainer
impl ModelContainer
Sourcepub fn query<M: Model>(&self) -> QueryBuilder<'_, M>
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.
Sourcepub fn query_fn<M: Model>(&self, f: impl Fn() -> Fetch + 'static) -> Query<M>
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.
Sourcepub fn count_fn<M: Model>(
&self,
f: impl Fn() -> Fetch + 'static,
) -> CountQuery<M>
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.
Sourcepub fn query_raw<M: Model>(
&self,
sql: impl Into<String>,
params: Vec<Value>,
tables: &[&str],
) -> Query<M>
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.
Sourcepub fn undo(&self, levels: usize) -> UndoStack
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.
Sourcepub fn with_connection<R>(
&self,
f: impl FnOnce(&mut dyn SqliteConnection) -> R,
) -> R
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.
Sourcepub fn try_with_connection<R>(
&self,
f: impl FnOnce(&mut dyn SqliteConnection) -> Result<R, DbError>,
) -> Result<R, DbError>
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.
Sourcepub fn rescan(&self) -> Result<(), DbError>
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).
Sourcepub fn attach_database(
&self,
alias: &str,
path: &str,
schema: Schema,
) -> Result<(), DbError>
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.
Sourcepub fn detach_database(&self, alias: &str) -> Result<(), DbError>
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.
Sourcepub fn check_external(&self) -> Result<bool, DbError>
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§
Auto Trait Implementations§
impl !RefUnwindSafe for ModelContainer
impl !Send for ModelContainer
impl !Sync for ModelContainer
impl !UnwindSafe for ModelContainer
impl Forget for ModelContainer
impl Freeze for ModelContainer
impl Unpin for ModelContainer
impl UnsafeUnpin for ModelContainer
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> ErasedDestructor for Twhere
T: 'static,
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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