pub struct Database { /* private fields */ }Expand description
SQLite database for code intelligence.
Implementations§
Source§impl Database
impl Database
Sourcepub fn open(path: &Path) -> Result<Self>
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:
0(fresh or pre-versioning database): the schema is initialized and the version is stamped toSCHEMA_VERSION.SCHEMA_VERSION: opened normally.- anything else: returns
crate::error::CtxError::SchemaVersionMismatch.
Sourcepub fn open_in_memory() -> Result<Self>
pub fn open_in_memory() -> Result<Self>
Create an in-memory database (for testing).
Sourcepub fn has_vector_search(&self) -> bool
pub fn has_vector_search(&self) -> bool
Check if vector search is available (sqlite-vec extension loaded and table exists).
Sourcepub fn transaction(&mut self) -> Result<Transaction<'_>>
pub fn transaction(&mut self) -> Result<Transaction<'_>>
Begin a transaction.
Sourcepub fn get_file_hash(&self, path: &str) -> Result<Option<String>>
pub fn get_file_hash(&self, path: &str) -> Result<Option<String>>
Get the content hash for a file.
Sourcepub fn needs_update(&self, path: &str, new_hash: &str) -> Result<bool>
pub fn needs_update(&self, path: &str, new_hash: &str) -> Result<bool>
Check if a file needs reindexing based on hash.
Sourcepub fn upsert_file(
&self,
file: &FileRecord,
source: Option<&[u8]>,
) -> Result<()>
pub fn upsert_file( &self, file: &FileRecord, source: Option<&[u8]>, ) -> Result<()>
Insert or update a file record.
Sourcepub fn delete_file(&self, path: &str) -> Result<()>
pub fn delete_file(&self, path: &str) -> Result<()>
Delete a file and all associated data.
Sourcepub fn delete_symbols_for_file(&self, file_path: &str) -> Result<()>
pub fn delete_symbols_for_file(&self, file_path: &str) -> Result<()>
Delete all symbols for a file.
Sourcepub fn insert_symbol(&self, symbol: &Symbol) -> Result<()>
pub fn insert_symbol(&self, symbol: &Symbol) -> Result<()>
Insert a symbol.
Sourcepub fn insert_edge(&self, edge: &Edge) -> Result<()>
pub fn insert_edge(&self, edge: &Edge) -> Result<()>
Insert an edge.
Sourcepub fn upsert_module(&self, module: &ModuleInfo) -> Result<()>
pub fn upsert_module(&self, module: &ModuleInfo) -> Result<()>
Insert module information.
Sourcepub fn insert_symbols_batch(&self, symbols: &[Symbol]) -> Result<usize>
pub fn insert_symbols_batch(&self, symbols: &[Symbol]) -> Result<usize>
Insert multiple symbols in a transaction (batch insert for parallel indexing).
Sourcepub fn insert_edges_batch(&self, edges: &[Edge]) -> Result<usize>
pub fn insert_edges_batch(&self, edges: &[Edge]) -> Result<usize>
Insert multiple edges in a transaction (batch insert for parallel indexing).
Sourcepub fn find_symbols(&self, pattern: &str, limit: i32) -> Result<Vec<Symbol>>
pub fn find_symbols(&self, pattern: &str, limit: i32) -> Result<Vec<Symbol>>
Find symbols by name (exact or pattern).
Sourcepub fn find_symbols_filtered(
&self,
pattern: &str,
limit: i32,
file_pattern: Option<&str>,
kind_filter: Option<&str>,
) -> Result<Vec<Symbol>>
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 forlimit: Maximum number of resultsfile_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.
Sourcepub fn get_source(&self, symbol_id: &str) -> Result<Option<String>>
pub fn get_source(&self, symbol_id: &str) -> Result<Option<String>>
Get the source code for a symbol.
Sourcepub fn get_file_symbols(&self, file_path: &str) -> Result<Vec<Symbol>>
pub fn get_file_symbols(&self, file_path: &str) -> Result<Vec<Symbol>>
Get all symbols in a file.
Sourcepub fn find_symbols_in_file(&self, file_path: &str) -> Result<Vec<Symbol>>
pub fn find_symbols_in_file(&self, file_path: &str) -> Result<Vec<Symbol>>
Find symbols in a specific file (alias for get_file_symbols).
Sourcepub fn get_outgoing_edges(&self, symbol_id: &str) -> Result<Vec<Edge>>
pub fn get_outgoing_edges(&self, symbol_id: &str) -> Result<Vec<Edge>>
Get edges from a symbol.
Sourcepub fn get_incoming_edges(&self, target_name: &str) -> Result<Vec<Edge>>
pub fn get_incoming_edges(&self, target_name: &str) -> Result<Vec<Edge>>
Get edges to a symbol (callers).
Sourcepub fn get_stats(&self) -> Result<CodebaseStats>
pub fn get_stats(&self) -> Result<CodebaseStats>
Get codebase statistics.
Sourcepub fn symbol_metrics(&self) -> Result<Vec<SymbolMetrics>>
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).
Sourcepub fn file_complexity(&self) -> Result<Vec<FileComplexity>>
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).
Sourcepub fn file_call_edges(&self, file_path: &str) -> Result<Vec<(String, String)>>
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).
Sourcepub fn fan_in_counts(&self, ids: &[String]) -> Result<HashMap<String, i64>>
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.
Sourcepub fn get_indexed_files(&self) -> Result<Vec<String>>
pub fn get_indexed_files(&self) -> Result<Vec<String>>
Get all indexed file paths.
Sourcepub fn get_all_symbol_ids(&self) -> Result<Vec<String>>
pub fn get_all_symbol_ids(&self) -> Result<Vec<String>>
Get all symbol IDs, sorted ascending (stable order for rank computation).
Sourcepub fn get_rank_edges(&self) -> Result<Vec<(String, String)>>
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.
Sourcepub fn clear_symbol_rank(&self) -> Result<()>
pub fn clear_symbol_rank(&self) -> Result<()>
Delete all cached PageRank scores (called when the index changes).
Sourcepub fn store_symbol_ranks(&self, ranks: &[(String, f64)]) -> Result<()>
pub fn store_symbol_ranks(&self, ranks: &[(String, f64)]) -> Result<()>
Bulk-store PageRank scores in a single transaction, replacing any existing cache.
Sourcepub fn count_symbols(&self) -> Result<i64>
pub fn count_symbols(&self) -> Result<i64>
Count rows in the symbols table.
Sourcepub fn count_symbol_ranks(&self) -> Result<i64>
pub fn count_symbol_ranks(&self) -> Result<i64>
Count rows in the symbol_rank cache.
Sourcepub fn get_files_with_sizes(&self) -> Result<Vec<(String, i64)>>
pub fn get_files_with_sizes(&self) -> Result<Vec<(String, i64)>>
Get all indexed files with their sizes, ordered by path.
Sourcepub fn get_symbol_ids_in_file(&self, file_path: &str) -> Result<Vec<String>>
pub fn get_symbol_ids_in_file(&self, file_path: &str) -> Result<Vec<String>>
Get the IDs of all symbols defined in a file.
Sourcepub fn get_symbol_ids_by_name(&self, name: &str) -> Result<Vec<String>>
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.
Sourcepub fn get_map_symbols(&self) -> Result<Vec<MapSymbolRow>>
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.
Sourcepub fn get_cross_file_edges(&self) -> Result<Vec<CrossFileEdge>>
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).
Sourcepub fn get_file_imports(&self) -> Result<Vec<(String, Vec<ImportInfo>)>>
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.
Sourcepub fn get_import_edges(&self) -> Result<Vec<(String, String, Option<i64>)>>
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.
Sourcepub fn semantic_search(
&self,
query: &str,
limit: i32,
) -> Result<Vec<(Symbol, f64)>>
pub fn semantic_search( &self, query: &str, limit: i32, ) -> Result<Vec<(Symbol, f64)>>
Semantic search using FTS5 full-text search. Searches across name, signature, brief, and docstring fields.
Sourcepub fn hybrid_search(
&self,
query: &str,
limit: i32,
) -> Result<Vec<(Symbol, f64, String)>>
pub fn hybrid_search( &self, query: &str, limit: i32, ) -> Result<Vec<(Symbol, f64, String)>>
Hybrid search combining exact match with semantic search.
Sourcepub fn rebuild_fts_index(&self) -> Result<()>
pub fn rebuild_fts_index(&self) -> Result<()>
Rebuild the FTS index (useful after schema changes).
Sourcepub fn store_embedding(
&self,
symbol_id: &str,
provider: &str,
model: &str,
vector: &[f32],
) -> Result<()>
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:
- The
embeddingstable (JSON format, for compatibility) - The
symbol_vectorstable (binary format, for fast KNN search via sqlite-vec)
Sourcepub fn get_embedding(&self, symbol_id: &str) -> Result<Option<Vec<f32>>>
pub fn get_embedding(&self, symbol_id: &str) -> Result<Option<Vec<f32>>>
Get the embedding for a symbol.
Sourcepub fn get_all_embeddings(
&self,
) -> Result<Vec<(String, String, String, String, u32, Vec<f32>)>>
pub fn get_all_embeddings( &self, ) -> Result<Vec<(String, String, String, String, u32, Vec<f32>)>>
Get all embeddings with their symbol metadata.
Sourcepub fn count_embeddings(&self) -> Result<i64>
pub fn count_embeddings(&self) -> Result<i64>
Count symbols that have embeddings.
Sourcepub fn get_embedding_metadata(&self) -> Result<Vec<(String, String, i64, i64)>>
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.
Sourcepub fn get_symbols_without_embeddings(&self, limit: i64) -> Result<Vec<Symbol>>
pub fn get_symbols_without_embeddings(&self, limit: i64) -> Result<Vec<Symbol>>
Get symbols that don’t have embeddings yet.
Sourcepub fn migrate_embeddings_to_vec(&self) -> Result<usize>
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.
Sourcepub fn count_vector_embeddings(&self) -> Result<i64>
pub fn count_vector_embeddings(&self) -> Result<i64>
Get the count of embeddings in the vector table.
Sourcepub fn vector_search(
&self,
query_embedding: &[f32],
limit: usize,
) -> Result<Vec<(String, String, String, String, u32, f32)>>
pub fn vector_search( &self, query_embedding: &[f32], limit: usize, ) -> Result<Vec<(String, String, String, String, u32, f32)>>
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).
Sourcepub fn has_vector_embeddings(&self) -> bool
pub fn has_vector_embeddings(&self) -> bool
Check if the vector table has any embeddings.
Sourcepub fn delete_embeddings(
&self,
provider: &str,
model: Option<&str>,
) -> Result<usize>
pub fn delete_embeddings( &self, provider: &str, model: Option<&str>, ) -> Result<usize>
Delete embeddings for a specific provider/model.
Sourcepub fn resolve_edge_targets(&self) -> Result<usize>
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.
- Context match: the call context contains the type name (e.g., “TypeScriptParser::new()”)
- Unique: only one symbol with that name exists in the codebase
- 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.
Sourcepub fn insert_fingerprints_batch(
&self,
fingerprints: &[Fingerprint],
) -> Result<usize>
pub fn insert_fingerprints_batch( &self, fingerprints: &[Fingerprint], ) -> Result<usize>
Insert (or replace) a batch of MinHash fingerprints in one transaction.
Sourcepub fn get_fingerprints(&self, min_tokens: i64) -> Result<Vec<Fingerprint>>
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§
Auto Trait Implementations§
impl !Freeze for Database
impl !RefUnwindSafe for Database
impl !Sync for Database
impl !UnwindSafe for Database
impl Send for Database
impl Unpin for Database
impl UnsafeUnpin for Database
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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