Skip to main content

Database

Struct Database 

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

A kit database handle.

Wraps a MongrelDB core database and a kit schema, providing table metadata and transaction creation.

Implementations§

Source§

impl Database

Source

pub fn open(path: &Path) -> Result<Self>

Open an existing kit database.

Source

pub fn open_encrypted(path: &Path, passphrase: &str) -> Result<Self>

Open an existing page-encrypted kit database with its passphrase.

Source

pub fn create_encrypted( path: &Path, schema: KitSchema, passphrase: &str, ) -> Result<Self>

Create a fresh page-encrypted kit database (AES-256-GCM; the passphrase derives the key hierarchy). Columns flagged encrypted / encrypted_indexable are encrypted at rest.

Source

pub fn create(path: &Path, schema: KitSchema) -> Result<Self>

Create a fresh kit database with the given schema.

Source

pub fn register_default( &mut self, name: impl Into<String>, provider: impl Fn() -> Value + Send + Sync + 'static, )

Register a named default provider used by DefaultKind::CustomName columns. Returns the database for chaining.

Source

pub fn raw(&self) -> &CoreDatabase

The raw, unguarded MongrelDB core database. This is the Rust analogue of the TypeScript kit’s nativeDb escape hatch: writes made directly against it bypass all kit constraints.

Source

pub fn table_names(&self) -> Vec<String>

Application table names, excluding the reserved __kit_* tables.

Source

pub fn create_procedure(&self, spec: &ProcedureSpec) -> Result<StoredProcedure>

Source

pub fn replace_procedure(&self, spec: &ProcedureSpec) -> Result<StoredProcedure>

Source

pub fn drop_procedure(&self, name: &str) -> Result<()>

Source

pub fn call_procedure( &self, name: &str, args: Map<String, Value>, ) -> Result<ProcedureCallResult>

Source

pub fn create_trigger(&self, spec: &TriggerSpec) -> Result<StoredTrigger>

Source

pub fn replace_trigger(&self, spec: &TriggerSpec) -> Result<StoredTrigger>

Source

pub fn drop_trigger(&self, name: &str) -> Result<()>

Source

pub fn triggers(&self) -> Vec<StoredTrigger>

Source

pub fn trigger(&self, name: &str) -> Option<StoredTrigger>

Source

pub fn allocate_sequence(&self, name: &str, count: i64) -> Result<i64>

Allocate count values from the named sequence, returning the first allocated value. A fresh sequence starts at 1 (SQL AUTO_INCREMENT semantics). The allocation runs in its own committed transaction and retries on write-write conflicts.

Source

pub fn transaction<T, F>(&self, max_retries: usize, f: F) -> Result<T>
where F: FnMut(&mut Transaction<'_>) -> Result<T>,

Run f inside a kit transaction, committing on success and retrying on retryable write-write conflicts up to max_retries times.

Source

pub fn table(&self, name: &str) -> Option<&KitTable>

Look up a table definition by name.

Source

pub fn schema(&self) -> &KitSchema

Return the currently loaded schema.

Source

pub fn begin(&self) -> Result<Transaction<'_>>

Begin a new kit transaction.

Source

pub fn set_schema(&mut self, schema: KitSchema)

Replace the in-memory schema, usually after a migration.

Source

pub fn check_internal_tables(&self) -> Result<()>

Verify that the sidecar schema file and all reserved __kit_* tables are present.

Source

pub fn gc(&self) -> Result<usize>

Reclaim orphaned runs and stale WAL/shadow files; returns the count removed. Safe to run on a live database.

Source

pub fn check(&self) -> Vec<Value>

Verify run footer checksums; returns any integrity issues as JSON objects (table_id, table_name, severity, description). Empty ⇒ healthy.

Source

pub fn doctor(&self) -> Result<Vec<u64>>

Drop corrupt runs; returns the ids of the runs that were dropped.

Source

pub fn snapshot_epoch(&self) -> u64

The current visible commit epoch — a monotonically increasing version stamp. A committed write bumps it; a snapshot at this epoch sees all currently-committed data.

Source

pub fn export_tsv(&self, table: &str) -> Result<String>

Export every visible row of table as a TSV document (header row of column names, tab-separated cells, NULL = empty field). See crate::tsv for the escaping rules.

Source

pub fn import_tsv(&self, table: &str, text: &str) -> Result<usize>

Import a TSV document into table (one committed transaction). Each row passes through defaults, validation, and constraint checks like a normal insert. Returns the number of rows inserted.

Source

pub fn explain(&self, table: &str, predicate: &Expr) -> Result<ExplainPlan>

Describe how predicate would be executed against table: which native index conditions push down, whether the push-down is exact (no residual re-filtering), and whether any index acceleration applies at all. A pure diagnostic — it plans but does not run the query.

Source

pub fn rows_at_epoch(&self, table: &str, epoch: u64) -> Result<Vec<Row>>

Read every row of table visible at commit epoch — a point-in-time (MVCC time-travel) read. epoch must not exceed the current snapshot epoch. Rows reclaimed by GC/compaction for retired snapshots may no longer be reconstructable; this reads whatever the engine still retains at that epoch.

Source

pub fn approx_aggregate( &self, table: &str, column: Option<&str>, agg: ApproxAggKind, z: f64, ) -> Result<Option<ApproxAggregate>>

Estimate an aggregate over table from the engine’s reservoir sample, returning a point estimate and a z-score confidence interval (e.g. z = 1.96 for ~95%). column is required for Sum/Avg and ignored for Count. Returns None when the reservoir is empty (no sampled rows yet). Fast and O(sample) — trades exactness for speed on large tables.

Source

pub fn scan_batched<F>( &self, table: &str, batch_size: usize, f: F, ) -> Result<()>
where F: FnMut(&[Map<String, Value>]) -> Result<()>,

Stream table in row batches without materializing the whole table at once. f receives successive chunks of at most batch_size value-maps, all from one snapshot. Backed by the engine’s native scan cursor when the table has a sorted run; for an overlay-only table (no run yet) it falls back to a single in-memory pass, still chunked to batch_size.

Source

pub fn set_similarity( &self, table: &str, column: &str, query: &[String], k: usize, ) -> Result<Vec<SimilarRow>>

Rank rows of table by Jaccard set-similarity between query and the string set stored (as a JSON array) in column, returning the top k with similarity > 0, highest first — the dedup/join primitive.

When column has a MinHash index, candidate rows come from the engine’s LSH index (sub-linear) and are then re-verified with exact Jaccard, so the top-k is exact for the recalled candidates (LSH recall is high but < 100%). Without an index it is an exact linear scan.

Source

pub fn flush(&self) -> Result<()>

Flush every table’s in-memory writes to durable sorted runs. Besides durability, this empties the memtable, which is what enables the engine’s incremental-aggregate fast path (see Self::incremental_aggregate).

Source

pub fn incremental_aggregate( &self, table: &str, column: Option<&str>, agg: IncrementalAggKind, filter: Option<&Expr>, ) -> Result<IncrementalAggregate>

Maintain and read an aggregate over table that updates by merging only newly-committed rows instead of rescanning. column is required for Sum/Min/Max/Avg and ignored for Count. An optional filter restricts the aggregate; it must translate exactly to index conditions (no residual), otherwise this errors — an inexact filter would silently aggregate the wrong rows.

The engine keeps a per-(table, column, agg, filter) cached state and, on a warm cache with an advanced epoch and no deletes/pending writes, folds in just the delta. The returned value is always exact; the incremental flag reports whether the fast path was taken.

Source

pub fn applied_migrations(&self) -> Result<Vec<Migration>>

Return the migrations already recorded in __kit_schema_migrations.

Source

pub fn close(&self) -> Result<()>

Best-effort flush-on-close (§4.4): force-flush pending writes on every table to .sr sorted runs so WAL segments stay bounded across repeated short-lived process invocations (e.g. the CLI). Call as the last action before exit. The daemon does not need this (auto-compactor handles it).

Source

pub fn compact_all(&self) -> Result<(usize, usize)>

Compact all tables: merge sorted runs into one clean run each so query latency stays flat. Returns (compacted, skipped). Safe to run at any time — honors snapshot retention. The daemon’s background auto-compactor already does this periodically; this is for manual/cron use.

Source

pub fn compact_table(&self, name: &str) -> Result<bool>

Compact a single table by name. Returns true if compacted, false if skipped (< 2 runs).

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> 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> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.