Skip to main content

Database

Struct Database 

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

SQLite database for code intelligence.

Implementations§

Source§

impl Database

Source

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

Open or create a database at the given path.

Verifies the schema version stored in PRAGMA user_version:

Source

pub fn open_in_memory() -> Result<Self>

Create an in-memory database (for testing).

Check if vector search is available (sqlite-vec extension loaded and table exists).

Source

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

Begin a transaction.

Source

pub fn get_file_hash(&self, path: &str) -> Result<Option<String>>

Get the content hash for a file.

Source

pub fn needs_update(&self, path: &str, new_hash: &str) -> Result<bool>

Check if a file needs reindexing based on hash.

Source

pub fn upsert_file( &self, file: &FileRecord, source: Option<&[u8]>, ) -> Result<()>

Insert or update a file record.

Source

pub fn delete_file(&self, path: &str) -> Result<()>

Delete a file and all associated data.

Source

pub fn delete_symbols_for_file(&self, file_path: &str) -> Result<()>

Delete all symbols for a file.

Source

pub fn insert_symbol(&self, symbol: &Symbol) -> Result<()>

Insert a symbol.

Source

pub fn insert_edge(&self, edge: &Edge) -> Result<()>

Insert an edge.

Source

pub fn upsert_module(&self, module: &ModuleInfo) -> Result<()>

Insert module information.

Source

pub fn insert_symbols_batch(&self, symbols: &[Symbol]) -> Result<usize>

Insert multiple symbols in a transaction (batch insert for parallel indexing).

Source

pub fn insert_edges_batch(&self, edges: &[Edge]) -> Result<usize>

Insert multiple edges in a transaction (batch insert for parallel indexing).

Source

pub fn get_symbol(&self, id: &str) -> Result<Option<Symbol>>

Find a symbol by ID.

Source

pub fn find_symbols(&self, pattern: &str, limit: i32) -> Result<Vec<Symbol>>

Find symbols by name (exact or pattern).

Source

pub fn find_symbols_filtered( &self, pattern: &str, limit: i32, file_pattern: Option<&str>, kind_filter: Option<&str>, ) -> Result<Vec<Symbol>>

Find symbols by name with optional file path and kind filters.

  • pattern: Name pattern to search for
  • limit: Maximum number of results
  • file_pattern: Optional file path filter (supports glob syntax: *, **)
  • kind_filter: Optional symbol kind filter (function, method, struct, etc.)

Results are ordered by match quality: exact name match first, then prefix match, then substring match.

Source

pub fn get_source(&self, symbol_id: &str) -> Result<Option<String>>

Get the source code for a symbol.

Source

pub fn get_file_symbols(&self, file_path: &str) -> Result<Vec<Symbol>>

Get all symbols in a file.

Source

pub fn find_symbols_in_file(&self, file_path: &str) -> Result<Vec<Symbol>>

Find symbols in a specific file (alias for get_file_symbols).

Source

pub fn get_outgoing_edges(&self, symbol_id: &str) -> Result<Vec<Edge>>

Get edges from a symbol.

Source

pub fn get_incoming_edges(&self, target_name: &str) -> Result<Vec<Edge>>

Get edges to a symbol (callers).

Source

pub fn get_stats(&self) -> Result<CodebaseStats>

Get codebase statistics.

Source

pub fn symbol_metrics(&self) -> Result<Vec<SymbolMetrics>>

Per-symbol fan-in/fan-out/complexity metrics for functions and methods.

Results are ordered by complexity (highest first).

Source

pub fn file_complexity(&self) -> Result<Vec<FileComplexity>>

Per-file aggregated complexity (same formula as Self::symbol_metrics, summed over all symbols in the file).

symbol_count counts all symbols in the file, not only functions. Results are ordered by complexity (highest first).

Source

pub fn file_call_edges(&self, file_path: &str) -> Result<Vec<(String, String)>>

All calls edges sourced from symbols in file_path, as (source_symbol_id, target_name) pairs.

Used by ctx score to compute per-file complexity restricted to changed files (per-changed-file queries keep scoring fast on large indexes).

Source

pub fn fan_in_counts(&self, ids: &[String]) -> Result<HashMap<String, i64>>

Count resolved incoming ‘calls’ edges for the given symbol IDs.

Symbols with no incoming calls are absent from the returned map.

Source

pub fn get_indexed_files(&self) -> Result<Vec<String>>

Get all indexed file paths.

Source

pub fn get_all_symbol_ids(&self) -> Result<Vec<String>>

Get all symbol IDs, sorted ascending (stable order for rank computation).

Source

pub fn get_rank_edges(&self) -> Result<Vec<(String, String)>>

Get deduplicated resolved edges of the kinds used for ranking (calls, imports, extends, implements), ordered for determinism.

Source

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

Delete all cached PageRank scores (called when the index changes).

Source

pub fn store_symbol_ranks(&self, ranks: &[(String, f64)]) -> Result<()>

Bulk-store PageRank scores in a single transaction, replacing any existing cache.

Source

pub fn load_symbol_ranks(&self) -> Result<Vec<(String, f64)>>

Load all cached PageRank scores.

Source

pub fn count_symbols(&self) -> Result<i64>

Count rows in the symbols table.

Source

pub fn count_symbol_ranks(&self) -> Result<i64>

Count rows in the symbol_rank cache.

Source

pub fn get_files_with_sizes(&self) -> Result<Vec<(String, i64)>>

Get all indexed files with their sizes, ordered by path.

Source

pub fn get_symbol_ids_in_file(&self, file_path: &str) -> Result<Vec<String>>

Get the IDs of all symbols defined in a file.

Source

pub fn get_symbol_ids_by_name(&self, name: &str) -> Result<Vec<String>>

Get the IDs of all symbols whose name or qualified name matches exactly.

Source

pub fn get_map_symbols(&self) -> Result<Vec<MapSymbolRow>>

Get the lightweight symbol rows shown by ctx map (declaration-level kinds only), in a stable base order.

Source

pub fn get_cross_file_edges(&self) -> Result<Vec<CrossFileEdge>>

All resolved relationship edges whose endpoints live in different files.

Used by ctx check to build the file-level dependency graph. Only calls/implements/extends/uses edges are included (imports edges are file-level and handled separately; contains and friends are structural, not dependencies).

Source

pub fn get_file_imports(&self) -> Result<Vec<(String, Vec<ImportInfo>)>>

Per-file imports recorded in the modules table.

The imports column stores a JSON array of ImportInfo; rows whose JSON fails to parse are skipped.

Source

pub fn get_import_edges(&self) -> Result<Vec<(String, String, Option<i64>)>>

File-level imports edges from the edges table.

Some parsers (Go) record imports as edges whose source_id is the importing file path and whose target_name is the import path. Returns (source, target_name, line) tuples.

Semantic search using FTS5 full-text search. Searches across name, signature, brief, and docstring fields.

Hybrid search combining exact match with semantic search.

Source

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

Rebuild the FTS index (useful after schema changes).

Source

pub fn store_embedding( &self, symbol_id: &str, provider: &str, model: &str, vector: &[f32], ) -> Result<()>

Store an embedding for a symbol.

This stores the embedding in two places:

  1. The embeddings table (JSON format, for compatibility)
  2. The symbol_vectors table (binary format, for fast KNN search via sqlite-vec)
Source

pub fn get_embedding(&self, symbol_id: &str) -> Result<Option<Vec<f32>>>

Get the embedding for a symbol.

Source

pub fn get_all_embeddings( &self, ) -> Result<Vec<(String, String, String, String, u32, Vec<f32>)>>

Get all embeddings with their symbol metadata.

Source

pub fn count_embeddings(&self) -> Result<i64>

Count symbols that have embeddings.

Source

pub fn get_embedding_metadata(&self) -> Result<Vec<(String, String, i64, i64)>>

Get metadata about stored embeddings (provider, model, dimension, count).

Returns a list of (provider, model, dimension, count) tuples for each unique combination in the embeddings table. This is useful for detecting dimension mismatches when querying with a different embedding provider.

Source

pub fn get_symbols_without_embeddings(&self, limit: i64) -> Result<Vec<Symbol>>

Get symbols that don’t have embeddings yet.

Source

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

Migrate existing embeddings from JSON table to vector table for fast KNN search.

This copies all embeddings with the correct dimension to the symbol_vectors table. Returns the number of embeddings migrated.

Source

pub fn count_vector_embeddings(&self) -> Result<i64>

Get the count of embeddings in the vector table.

Fast vector similarity search using sqlite-vec.

Returns the top-k most similar symbols to the query embedding. This uses indexed KNN search which is O(log n) instead of O(n).

Returns (symbol_id, name, kind, file_path, line, distance) tuples. Distance is L2 distance (lower is more similar).

Source

pub fn has_vector_embeddings(&self) -> bool

Check if the vector table has any embeddings.

Source

pub fn delete_embeddings( &self, provider: &str, model: Option<&str>, ) -> Result<usize>

Delete embeddings for a specific provider/model.

Source

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

Resolve target_id for edges that only have target_name.

This performs cross-file symbol resolution by matching target_name to symbols in the database. Resolution priority: 0. Qualified match: the edge context equals a symbol’s qualified_name exactly (e.g., “ChessPureLib.isKingInCheck”), disambiguating a bare name shared across files/languages.

  1. Context match: the call context contains the type name (e.g., “TypeScriptParser::new()”)
  2. Unique: only one symbol with that name exists in the codebase
  3. Same file unique: only one symbol with that name exists in the same file

We intentionally avoid aggressive same-file matching because calls like Vec::new() would incorrectly match a local new function.

Returns the number of edges that were resolved.

Source

pub fn insert_fingerprints_batch( &self, fingerprints: &[Fingerprint], ) -> Result<usize>

Insert (or replace) a batch of MinHash fingerprints in one transaction.

Source

pub fn get_fingerprints(&self, min_tokens: i64) -> Result<Vec<Fingerprint>>

Load all fingerprints with at least min_tokens tokens, ordered by symbol id (so callers get a stable, canonical order).

Trait Implementations§

Source§

impl Debug for Database

Source§

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

Formats the value using the given formatter. 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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> 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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + 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
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + 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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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

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

Source§

fn vzip(self) -> V

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