Database

Struct Database 

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

SQLite database connection wrapper.

Provides methods for storing and querying sessions, messages, and session-to-commit links. Handles schema migrations automatically when opening the database.

Implementations§

Source§

impl Database

Source

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

Opens or creates a database at the specified path.

Runs schema migrations automatically to ensure tables exist.

Source

pub fn open_default() -> Result<Self>

Opens the default database at ~/.lore/lore.db.

Creates the database file and directory if they do not exist.

Source

pub fn insert_session(&self, session: &Session) -> Result<()>

Inserts a new session or updates an existing one.

If a session with the same ID already exists, updates the ended_at and message_count fields. Also updates the sessions_fts index for full-text search on session metadata.

Source

pub fn get_session(&self, id: &Uuid) -> Result<Option<Session>>

Retrieves a session by its unique ID.

Returns None if no session with the given ID exists.

Source

pub fn list_sessions( &self, limit: usize, working_dir: Option<&str>, ) -> Result<Vec<Session>>

Lists sessions ordered by start time (most recent first).

Optionally filters by working directory prefix. Returns at most limit sessions.

Source

pub fn session_exists_by_source(&self, source_path: &str) -> Result<bool>

Checks if a session with the given source path already exists.

Used to detect already-imported sessions during import operations.

Source

pub fn find_session_by_id_prefix(&self, prefix: &str) -> Result<Option<Session>>

Finds a session by ID prefix, searching all sessions in the database.

This method uses SQL LIKE to efficiently search by prefix without loading all sessions into memory. Returns an error if the prefix is ambiguous (matches multiple sessions).

§Arguments
  • prefix - The UUID prefix to search for (can be any length)
§Returns
  • Ok(Some(session)) - If exactly one session matches the prefix
  • Ok(None) - If no sessions match the prefix
  • Err - If multiple sessions match (ambiguous prefix) or database error
Source

pub fn update_session_branch( &self, session_id: Uuid, new_branch: &str, ) -> Result<usize>

Updates the git branch for a session.

Used by the daemon when a message is processed with a different branch than the session’s current branch, indicating a branch switch mid-session. Also updates the sessions_fts index to keep search in sync.

Returns the number of rows affected (0 or 1).

Source

pub fn insert_message(&self, message: &Message) -> Result<()>

Inserts a message into the database.

If a message with the same ID already exists, the insert is ignored. Message content is serialized to JSON for storage. Also inserts extracted text content into the FTS index for full-text search.

Source

pub fn get_messages(&self, session_id: &Uuid) -> Result<Vec<Message>>

Retrieves all messages for a session, ordered by index.

Messages are returned in conversation order (by their index field).

Source

pub fn get_session_branch_history( &self, session_id: Uuid, ) -> Result<Vec<String>>

Returns the ordered list of distinct branches for a session.

Branches are returned in the order they first appeared in messages, with consecutive duplicates removed. This shows the branch transitions during a session (e.g., “main -> feat/auth -> main”).

Returns an empty vector if the session has no messages or all messages have None branches.

Inserts a link between a session and a git commit.

Links can be created manually by users or automatically by the auto-linking system based on time and file overlap heuristics.

Retrieves all session links for a commit.

Supports prefix matching on the commit SHA, allowing short SHAs (e.g., first 8 characters) to be used for lookup.

Retrieves all links associated with a session.

A session can be linked to multiple commits if it spans several git operations.

Deletes a specific session link by its ID.

Returns true if a link was deleted, false if no link with that ID existed.

Note: This method is part of the public API for programmatic use, though the CLI currently uses session/commit-based deletion.

Deletes all links for a session.

Returns the number of links deleted.

Deletes a link between a specific session and commit.

The commit_sha is matched as a prefix, so short SHAs work. Returns true if a link was deleted, false if no matching link existed.

Source

pub fn search_messages( &self, query: &str, limit: usize, working_dir: Option<&str>, since: Option<DateTime<Utc>>, role: Option<&str>, ) -> Result<Vec<SearchResult>>

Searches message content using full-text search.

Uses SQLite FTS5 to search for messages matching the query. Returns results ordered by FTS5 relevance ranking.

Optional filters:

  • working_dir: Filter by working directory prefix
  • since: Filter by minimum timestamp
  • role: Filter by message role

Note: This is the legacy search API. For new code, use search_with_options.

Source

pub fn search_with_options( &self, options: &SearchOptions, ) -> Result<Vec<SearchResult>>

Searches messages and session metadata using full-text search with filters.

Uses SQLite FTS5 to search for messages matching the query. Also searches session metadata (tool, project, branch) via sessions_fts. Returns results ordered by FTS5 relevance ranking.

Supports extensive filtering via SearchOptions:

  • tool: Filter by AI tool name
  • since/until: Filter by date range
  • project: Filter by project name (partial match)
  • branch: Filter by git branch (partial match)
  • role: Filter by message role
  • repo: Filter by working directory prefix
Source

pub fn get_context_messages( &self, session_id: &Uuid, message_index: i32, context_count: usize, ) -> Result<(Vec<Message>, Vec<Message>)>

Gets messages around a specific message for context.

Returns N messages before and N messages after the specified message, useful for displaying search results with surrounding context.

Source

pub fn get_message_by_index( &self, session_id: &Uuid, index: i32, ) -> Result<Option<Message>>

Gets a single message by its index within a session.

Source

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

Rebuilds the full-text search index from existing messages and sessions.

This should be called when:

  • Upgrading from a database without FTS support
  • The FTS index becomes corrupted or out of sync

Returns the number of messages indexed.

Source

pub fn search_index_needs_rebuild(&self) -> Result<bool>

Checks if the search index needs rebuilding.

Returns true if there are messages or sessions in the database but the FTS indexes are empty, indicating data was imported before FTS was added.

Source

pub fn session_count(&self) -> Result<i32>

Returns the total number of sessions in the database.

Source

pub fn message_count(&self) -> Result<i32>

Returns the total number of messages across all sessions.

Returns the total number of session links in the database.

Source

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

Returns the path to the database file, if available.

Returns None for in-memory databases.

Source

pub fn find_sessions_near_commit_time( &self, commit_time: DateTime<Utc>, window_minutes: i64, working_dir: Option<&str>, ) -> Result<Vec<Session>>

Finds sessions that were active around a commit time.

A session is considered active if the commit time falls within the window before and after the session’s time range (started_at to ended_at).

§Arguments
  • commit_time - The timestamp of the commit
  • window_minutes - The window in minutes before/after the session
  • working_dir - Optional working directory filter (prefix match)
§Returns

Sessions that were active near the commit time, ordered by proximity.

Checks if a link already exists between a session and commit.

Used to avoid creating duplicate links during auto-linking.

Source

pub fn delete_session(&self, session_id: &Uuid) -> Result<(usize, usize)>

Deletes a session and all its associated data.

Removes the session, all its messages, all FTS index entries, and all session links. Returns the counts of deleted items.

§Returns

A tuple of (messages_deleted, links_deleted) counts.

Source

pub fn insert_annotation(&self, annotation: &Annotation) -> Result<()>

Inserts a new annotation for a session.

Annotations are user-created bookmarks or notes attached to sessions.

Source

pub fn get_annotations(&self, session_id: &Uuid) -> Result<Vec<Annotation>>

Retrieves all annotations for a session.

Annotations are returned in order of creation (oldest first).

Source

pub fn delete_annotation(&self, annotation_id: &Uuid) -> Result<bool>

Deletes an annotation by its ID.

Returns true if an annotation was deleted, false if not found.

Source

pub fn delete_annotations_by_session(&self, session_id: &Uuid) -> Result<usize>

Deletes all annotations for a session.

Returns the number of annotations deleted.

Source

pub fn insert_tag(&self, tag: &Tag) -> Result<()>

Inserts a new tag for a session.

Tags are unique per session, so attempting to add a duplicate tag label to the same session will fail with a constraint error.

Source

pub fn get_tags(&self, session_id: &Uuid) -> Result<Vec<Tag>>

Retrieves all tags for a session.

Tags are returned in alphabetical order by label.

Source

pub fn tag_exists(&self, session_id: &Uuid, label: &str) -> Result<bool>

Checks if a tag with the given label exists for a session.

Source

pub fn delete_tag(&self, session_id: &Uuid, label: &str) -> Result<bool>

Deletes a tag by session ID and label.

Returns true if a tag was deleted, false if not found.

Source

pub fn delete_tags_by_session(&self, session_id: &Uuid) -> Result<usize>

Deletes all tags for a session.

Returns the number of tags deleted.

Source

pub fn list_sessions_with_tag( &self, label: &str, limit: usize, ) -> Result<Vec<Session>>

Lists sessions with a specific tag label.

Returns sessions ordered by start time (most recent first).

Source

pub fn insert_summary(&self, summary: &Summary) -> Result<()>

Inserts a new summary for a session.

Each session can have at most one summary. If a summary already exists for the session, this will fail due to the unique constraint.

Source

pub fn get_summary(&self, session_id: &Uuid) -> Result<Option<Summary>>

Retrieves the summary for a session, if one exists.

Source

pub fn update_summary(&self, session_id: &Uuid, content: &str) -> Result<bool>

Updates the summary for a session.

Updates the content and generated_at timestamp for an existing summary. Returns true if a summary was updated, false if no summary exists.

Source

pub fn delete_summary(&self, session_id: &Uuid) -> Result<bool>

Deletes the summary for a session.

Returns true if a summary was deleted, false if no summary existed.

Source

pub fn upsert_machine(&self, machine: &Machine) -> Result<()>

Registers a machine or updates its name if it already exists.

Used to store machine identity information for cloud sync. If a machine with the given ID already exists, updates the name.

Source

pub fn get_machine(&self, id: &str) -> Result<Option<Machine>>

Gets a machine by ID.

Returns None if no machine with the given ID exists.

Source

pub fn get_machine_name(&self, id: &str) -> Result<String>

Gets the display name for a machine ID.

Returns the machine name if found, otherwise returns a truncated UUID (first 8 characters) for readability.

Source

pub fn list_machines(&self) -> Result<Vec<Machine>>

Lists all registered machines.

Returns machines ordered by creation date (oldest first).

Source

pub fn get_most_recent_session_for_directory( &self, working_dir: &str, ) -> Result<Option<Session>>

Gets the most recent session for a given working directory.

Returns the session with the most recent started_at timestamp where the working directory matches or is a subdirectory of the given path.

Source

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

Runs SQLite VACUUM to reclaim unused space and defragment the database.

This operation can take some time on large databases and temporarily doubles the disk space used while rebuilding.

Source

pub fn file_size(&self) -> Result<Option<u64>>

Returns the file size of the database in bytes.

Returns None for in-memory databases.

Source

pub fn delete_sessions_older_than(&self, before: DateTime<Utc>) -> Result<usize>

Deletes sessions older than the specified date.

Also deletes all associated messages, links, and FTS entries.

§Arguments
  • before - Delete sessions that started before this date
§Returns

The number of sessions deleted.

Source

pub fn count_sessions_older_than(&self, before: DateTime<Utc>) -> Result<i32>

Counts sessions older than the specified date (for dry-run preview).

§Arguments
  • before - Count sessions that started before this date
§Returns

The number of sessions that would be deleted.

Source

pub fn get_sessions_older_than( &self, before: DateTime<Utc>, ) -> Result<Vec<Session>>

Returns sessions older than the specified date (for dry-run preview).

§Arguments
  • before - Return sessions that started before this date
§Returns

A vector of sessions that would be deleted, ordered by start date.

Source

pub fn stats(&self) -> Result<DatabaseStats>

Returns database statistics including counts and date ranges.

§Returns

A DatabaseStats struct with session, message, and link counts, plus the date range of sessions and a breakdown by tool.

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

Source§

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

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

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

impl<T> WithSubscriber for T

Source§

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

fn with_current_subscriber(self) -> WithDispatch<Self>

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