Skip to main content

SqliteBackend

Struct SqliteBackend 

Source
pub struct SqliteBackend {
    conn: Mutex<Connection>,
    db_path: Option<PathBuf>,
}
Expand description

SQLite-based index backend with FTS5.

§Concurrency Model

Uses a Mutex<Connection> for thread-safe access. While this serializes database operations, SQLite’s WAL mode and busy_timeout pragma mitigate contention:

  • WAL mode: Allows concurrent readers with a single writer
  • busy_timeout: Waits up to 5 seconds for locks instead of failing immediately
  • NORMAL synchronous: Balances durability with performance

For high-throughput scenarios requiring true connection pooling, consider using r2d2-rusqlite or deadpool-sqlite. This would require refactoring to use Pool<SqliteConnectionManager> instead of Mutex<Connection>.

Fields§

§conn: Mutex<Connection>

Connection to the SQLite database.

Protected by Mutex because rusqlite::Connection is not Sync. WAL mode and busy_timeout handle concurrent access gracefully.

§db_path: Option<PathBuf>

Path to the SQLite database (None for in-memory).

Implementations§

Source§

impl SqliteBackend

Source

pub fn new(db_path: impl Into<PathBuf>) -> Result<Self>

Creates a new SQLite backend.

§Errors

Returns an error if the database cannot be opened or initialized.

Source

pub fn in_memory() -> Result<Self>

Creates an in-memory SQLite backend (useful for testing).

§Errors

Returns an error if the database cannot be initialized.

Source

pub fn db_path(&self) -> Option<&Path>

Returns the database path.

Source

fn initialize(&self) -> Result<()>

Initializes the database schema.

Source

fn create_indexes(conn: &Connection)

Creates indexes for optimized queries.

Source

fn build_filter_clause_numbered( &self, filter: &SearchFilter, start_param: usize, ) -> (String, Vec<String>, usize)

Builds a WHERE clause from a search filter with numbered parameters. Returns the clause string, the parameters, and the next parameter index.

Source

fn record_operation_metrics( &self, operation: &'static str, start: Instant, status: &'static str, )

Source

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

Performs a WAL checkpoint to merge WAL file into main database (RES-M3).

This is useful for:

  • Graceful shutdown (ensure WAL is flushed)
  • Periodic maintenance (prevent WAL file growth)
  • Before backup operations

Uses TRUNCATE mode which blocks briefly but ensures WAL is fully merged and then truncated to zero bytes.

§Returns

Returns a tuple of (pages_written, pages_remaining) on success. pages_remaining should be 0 if checkpoint completed fully.

§Errors

Returns an error if the checkpoint operation fails.

Source

pub fn wal_size(&self) -> Option<u32>

Returns the current WAL file size in pages.

Useful for monitoring and deciding when to trigger a checkpoint.

§Errors

Returns an error if the query fails.

Source

pub fn checkpoint_if_needed( &self, threshold_pages: u32, ) -> Result<Option<(u32, u32)>>

Checkpoints the WAL if it exceeds the given threshold in pages.

Default SQLite auto-checkpoint threshold is 1000 pages (~4MB with 4KB pages). This method allows explicit control over checkpointing.

§Arguments
  • threshold_pages - Checkpoint if WAL size exceeds this number of pages.
§Returns

Returns Some((pages_written, pages_remaining)) if checkpoint was performed, None if WAL was below threshold.

§Errors

Returns an error if the checkpoint operation fails.

Source

pub fn store_edge( &self, from_id: &MemoryId, to_id: &MemoryId, edge_type: EdgeType, ) -> Result<()>

Stores a memory edge relationship in the database.

Creates a directed edge from one memory to another with the specified edge type. Used by the consolidation service to link original memories to their summaries.

§Arguments
  • from_id - The source memory ID
  • to_id - The target memory ID
  • edge_type - The type of relationship
§Errors

Returns an error if the database operation fails or if the memory IDs don’t exist.

§Examples
use subcog::storage::index::SqliteBackend;
use subcog::models::{MemoryId, EdgeType};

let backend = SqliteBackend::new("./index.db")?;
let from_id = MemoryId::new("original_memory");
let to_id = MemoryId::new("summary_memory");

backend.store_edge(&from_id, &to_id, EdgeType::SummarizedBy)?;
Source

pub fn query_edges( &self, from_id: &MemoryId, edge_type: EdgeType, ) -> Result<Vec<MemoryId>>

Queries edges for a given memory ID and edge type.

Returns a list of target memory IDs that have the specified edge type relationship with the source memory ID.

§Arguments
  • from_id - The source memory ID
  • edge_type - The type of relationship to query
§Errors

Returns an error if the database query fails.

§Examples
use subcog::storage::index::SqliteBackend;
use subcog::models::{MemoryId, EdgeType};

let backend = SqliteBackend::new("./index.db")?;
let from_id = MemoryId::new("original_memory");

let targets = backend.query_edges(&from_id, EdgeType::SummarizedBy)?;

Trait Implementations§

Source§

impl IndexBackend for SqliteBackend

Source§

fn get_memories_batch(&self, ids: &[MemoryId]) -> Result<Vec<Option<Memory>>>

Retrieves multiple memories in a single batch query (PERF-C1 fix).

Uses a single SQL query with IN clause instead of N individual queries.

Source§

fn reindex(&self, memories: &[Memory]) -> Result<()>

Re-indexes all memories in a single transaction (DB-H2).

This is more efficient than the default implementation which creates a transaction per memory.

Source§

fn index(&self, memory: &Memory) -> Result<()>

Indexes a memory for full-text search. Read more
Source§

fn remove(&self, id: &MemoryId) -> Result<bool>

Removes a memory from the index. Read more
Source§

fn search( &self, query: &str, filter: &SearchFilter, limit: usize, ) -> Result<Vec<(MemoryId, f32)>>

Searches for memories matching a text query. Read more
Source§

fn clear(&self) -> Result<()>

Clears the entire index. Read more
Source§

fn list_all( &self, filter: &SearchFilter, limit: usize, ) -> Result<Vec<(MemoryId, f32)>>

Lists all indexed memories, optionally filtered. Read more
Source§

fn get_memory(&self, id: &MemoryId) -> Result<Option<Memory>>

Retrieves a memory by ID. Read more
Source§

impl PersistenceBackend for SqliteBackend

Source§

fn store(&self, memory: &Memory) -> Result<()>

Stores a memory. Read more
Source§

fn get(&self, id: &MemoryId) -> Result<Option<Memory>>

Retrieves a memory by ID. Read more
Source§

fn delete(&self, id: &MemoryId) -> Result<bool>

Deletes a memory by ID. Read more
Source§

fn list_ids(&self) -> Result<Vec<MemoryId>>

Lists all memory IDs. Read more
Source§

fn get_batch(&self, ids: &[MemoryId]) -> Result<Vec<Memory>>

Retrieves multiple memories by their IDs in a single batch operation. Read more
Source§

fn exists(&self, id: &MemoryId) -> Result<bool>

Checks if a memory exists. Read more
Source§

fn count(&self) -> Result<usize>

Returns the total count of memories. 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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FutureExt for T

§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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
§

impl<T> IntoRequest<T> for T

§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
§

impl<L> LayerExt<L> for L

§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in [Layered].
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

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

Initializes a with the given initializer. Read more
§

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

Dereferences the given pointer. Read more
§

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

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

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

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

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. 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.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

impl<T> Allocation for T
where T: RefUnwindSafe + Send + Sync,