Skip to main content

Db

Struct Db 

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

An embedded, in-memory database with Git semantics.

Db is a handle: cloning it is cheap and every clone refers to the same database. It is Send + Sync, and readers never block writers.

use memfork_core::{Db, MergePolicy, Value};

let db = Db::new();
db.put("main", "plan:1", Value::new("draft"))?;

// Fork before a risky step; the parent cannot see the attempt.
db.fork("main", "try")?;
db.put("try", "plan:1", Value::new("rewritten"))?;
assert_eq!(db.get("main", "plan:1")?.map(|e| e.value.clone()), Some("draft".into()));

// It worked: fold it back in.
db.merge("try", "main", MergePolicy::Fail)?;
assert_eq!(db.get("main", "plan:1")?.map(|e| e.value.clone()), Some("rewritten".into()));

Implementations§

Source§

impl Db

Source

pub fn new() -> Self

Create a database with a single empty branch, main.

Source

pub fn with_default_branch(name: &str) -> Result<Self>

Create a database whose default branch has a name other than main.

Source

pub fn default_branch(&self) -> &str

The name of the branch that cannot be discarded.

Source

pub fn set_journal(&self, journal: Option<Arc<dyn Journal>>)

Record every change to a journal before it becomes visible.

The engine does no I/O of its own: the journal decides where the bytes go and how durable they are. Attached after recovery rather than at construction, because replay must not re-record what it is replaying.

A library caller gets no journal unless they ask. The memfork binary attaches one by default, because an agent’s memory that forgets everything on restart is not what anyone means by memory.

Source

pub fn is_journalled(&self) -> bool

Whether changes are being recorded.

Source

pub fn set_eviction(&self, config: Option<EvictionConfig>)

Set a memory budget, or remove one.

With no budget nothing is ever evicted and reads record nothing, so they stay lock-free. Setting one turns on the reading history that scoring needs, which costs a brief per-branch lock per read.

Source

pub fn eviction(&self) -> Option<EvictionConfig>

The memory budget, if one is set.

Source

pub fn on_evict(&self, hook: Option<OnEvict>)

Be told about entries before they are evicted, so they can be kept somewhere else.

Source

pub fn enforce_budget(&self, branch: &str) -> Result<Option<CommitId>>

Evict from a branch until it is under budget, as its own commit.

Called after a commit lands. Does nothing without a budget, and nothing when the branch is already under it, so the common path costs one lock-free read of the configuration.

Source

pub fn embedding_dim(&self) -> Option<usize>

The embedding dimension this database is pinned to, if any entry has carried an embedding yet (DESIGN §4.1).

Source

pub fn head(&self, branch: &str) -> Result<CommitId>

The commit a branch currently points at.

Source

pub fn commit(&self, id: CommitId) -> Result<Arc<Commit>>

Look up a commit by id.

Source

pub fn has_branch(&self, branch: &str) -> bool

Whether a branch exists.

Source

pub fn branches(&self) -> Vec<BranchInfo>

Every branch, in ascending name order.

Source

pub fn read(&self, branch: &str) -> Result<ReadView>

A consistent view of a branch as it is right now (DESIGN §4.3).

Source

pub fn at(&self, branch: &str, seq: u64) -> Result<ReadView>

A view of a branch as it was after commit number seq (DESIGN §4.2).

Sequence numbers are monotonic along a branch’s first-parent chain, so seq names exactly one commit: 0 is the empty genesis state and head.seq is the present.

Source

pub fn get(&self, branch: &str, key: &str) -> Result<Option<Arc<Entry>>>

Read one key from a branch head.

Source

pub fn list( &self, branch: &str, prefix: &str, limit: Option<usize>, ) -> Result<Vec<(String, Arc<Entry>)>>

List the keys of a branch that start with prefix, in ascending order.

Source

pub fn search( &self, branch: &str, query: &[f32], k: usize, prefix: Option<&str>, ) -> Result<Vec<SearchHit>>

Exact brute-force cosine similarity search (DESIGN §4.2).

Source

pub fn log(&self, branch: &str, limit: Option<usize>) -> Result<Vec<LogEntry>>

The first-parent history of a branch, newest first.

Source

pub fn resolve(&self, reference: &str) -> Result<Arc<Commit>>

Resolve a branch name or a full hex commit id to a commit.

Source

pub fn diff(&self, a: &str, b: &str) -> Result<Vec<Change>>

Key-level differences between two branches or commits, sorted by key.

Source

pub fn begin(&self, branch: &str) -> Result<Txn>

Open a transaction on a branch (DESIGN §4.2).

The transaction records the branch head it was based on. Dropping it without committing is a rollback that leaves no trace.

Source

pub fn put(&self, branch: &str, key: &str, value: Value) -> Result<CommitId>

Write one key as a single-operation transaction.

Source

pub fn delete(&self, branch: &str, key: &str) -> Result<CommitId>

Remove one key as a single-operation transaction.

Source

pub fn apply_record(&self, record: &Record) -> Result<()>

Rebuild state from journal records, in the order they were written.

Commit ids are recomputed, never read from the record, so a replay that produces the original ids is evidence the engine is deterministic rather than evidence that bytes were copied faithfully.

Source

pub fn fork(&self, from: &str, new_branch: &str) -> Result<CommitId>

Point a new branch at another branch’s head (DESIGN §4.2).

Constant time and constant space whatever the database holds: the new branch is one pointer into the same immutable commit, and the two branches go on sharing every node until one of them is written to.

Source

pub fn fork_at( &self, from: &str, seq: u64, new_branch: &str, ) -> Result<CommitId>

Point a new branch at a past commit of another branch (DESIGN §4.2).

Source

pub fn branch_from_commit( &self, new_branch: &str, at: CommitId, ) -> Result<CommitId>

Point a new branch at an arbitrary commit.

Source

pub fn discard(&self, branch: &str) -> Result<()>

Delete a branch and free every commit only it could reach (DESIGN §4.2).

The default branch cannot be discarded. Any ReadView already handed out stays valid: it holds its commit alive by reference count.

Source

pub fn discarded(&self) -> Vec<Discarded>

The most recently discarded branches, oldest first, at most DISCARDS_REMEMBERED of them.

Source

pub fn all_commits(&self) -> Vec<Arc<Commit>>

Every commit the graph holds, in id order: what a history view draws.

Source

pub fn commit_count(&self) -> usize

How many commits the graph currently holds. Tests use this to show that a rolled-back transaction and a discarded branch leave nothing behind.

Source§

impl Db

Source

pub fn merge( &self, source: &str, target: &str, policy: MergePolicy, ) -> Result<MergeOutcome>

Merge source into target against their common ancestor (DESIGN §4.2).

A key is in conflict only when both sides changed it to different content. Under MergePolicy::Fail a conflict returns Error::MergeConflict with every conflicting key and changes nothing at all.

Trait Implementations§

Source§

impl Clone for Db

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
Source§

impl Debug for Db

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Db

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Db

§

impl !UnwindSafe for Db

§

impl Freeze for Db

§

impl Send for Db

§

impl Sync for Db

§

impl Unpin for Db

§

impl UnsafeUnpin for Db

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