CodeGraph

Struct CodeGraph 

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

The main code graph database.

CodeGraph provides the primary interface for storing and querying code relationships. All operations are explicit with no hidden behavior.

Implementations§

Source§

impl CodeGraph

Source

pub fn with_backend(backend: Box<dyn StorageBackend>) -> Result<Self>

Open or create a code graph with the given storage backend.

This is the explicit way to create a graph. No automatic scanning or parsing.

§Errors

Returns GraphError::Storage if the backend cannot be initialized.

Source

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

Open a persistent code graph at the given path.

Uses RocksDB for production-grade persistent storage.

§Example
use codegraph::CodeGraph;
use std::path::Path;

let graph = CodeGraph::open(Path::new("./my_project.graph")).unwrap();
§Errors

Returns GraphError::Storage if the database cannot be opened.

Source

pub fn in_memory() -> Result<Self>

Create an in-memory code graph for testing.

Warning: All data is lost when the graph is dropped. Only use for testing.

Source

pub fn add_node( &mut self, node_type: NodeType, properties: PropertyMap, ) -> Result<NodeId>

Add a node to the graph.

§Parameters
  • node_type: Type of code entity
  • properties: Metadata for the node
§Returns

The unique ID assigned to the created node.

§Errors

Returns GraphError::Storage if persistence fails.

Source

pub fn get_node(&self, id: NodeId) -> Result<&Node>

Get a node by ID (immutable).

§Errors

Returns GraphError::NodeNotFound if the node doesn’t exist.

Source

pub fn get_node_mut(&mut self, id: NodeId) -> Result<&mut Node>

Get a mutable reference to a node by ID.

§Errors

Returns GraphError::NodeNotFound if the node doesn’t exist.

Source

pub fn update_node_properties( &mut self, id: NodeId, properties: PropertyMap, ) -> Result<()>

Update properties of an existing node.

Merges new properties with existing ones (overwrites duplicates).

§Errors

Returns error if node not found or persistence fails.

Source

pub fn delete_node(&mut self, id: NodeId) -> Result<()>

Delete a node and all its connected edges.

§Errors

Returns error if node not found or deletion fails.

Source

pub fn add_edge( &mut self, source_id: NodeId, target_id: NodeId, edge_type: EdgeType, properties: PropertyMap, ) -> Result<EdgeId>

Add an edge to the graph.

§Parameters
  • source_id: Source node ID
  • target_id: Target node ID
  • edge_type: Type of relationship
  • properties: Metadata for the edge (e.g., line number)
§Returns

The unique ID assigned to the created edge.

§Errors

Returns error if source or target node doesn’t exist or storage fails.

Source

pub fn get_edge(&self, id: EdgeId) -> Result<&Edge>

Get an edge by ID.

§Errors

Returns GraphError::EdgeNotFound if the edge doesn’t exist.

Source

pub fn delete_edge(&mut self, id: EdgeId) -> Result<()>

Delete an edge.

§Errors

Returns error if edge not found or deletion fails.

Source

pub fn get_neighbors( &self, node_id: NodeId, direction: Direction, ) -> Result<Vec<NodeId>>

Get all neighbor nodes connected by edges in the specified direction.

§Parameters
  • node_id: The node to find neighbors for
  • direction: Which edges to follow (Outgoing, Incoming, or Both)
§Returns

Vector of neighbor node IDs.

§Errors

Returns error if node not found.

Source

pub fn get_edges_between( &self, source_id: NodeId, target_id: NodeId, ) -> Result<Vec<EdgeId>>

Get all edges between two nodes.

Returns all edges from source to target.

Source

pub fn add_nodes_batch( &mut self, nodes: Vec<(NodeType, PropertyMap)>, ) -> Result<Vec<NodeId>>

Add multiple nodes in an atomic batch operation.

Either all nodes are added or none are.

§Returns

Vector of assigned node IDs in the same order as input.

Source

pub fn add_edges_batch( &mut self, edges: Vec<(NodeId, NodeId, EdgeType, PropertyMap)>, ) -> Result<Vec<EdgeId>>

Add multiple edges in an atomic batch operation.

Either all edges are added or none are.

§Returns

Vector of assigned edge IDs in the same order as input.

Source

pub fn node_count(&self) -> usize

Get the total number of nodes in the graph.

Source

pub fn edge_count(&self) -> usize

Get the total number of edges in the graph.

Source

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

Clear all nodes and edges from the graph.

This is a destructive operation that cannot be undone.

Source

pub fn query<'a>(&'a self) -> QueryBuilder<'a>

Create a new query builder for this graph.

Returns a QueryBuilder that allows fluent chaining of filters to find specific nodes in the graph.

§Examples
use codegraph::{CodeGraph, NodeType};

let mut graph = CodeGraph::in_memory()?;
// ... populate graph ...

// Find all public functions
let results = graph.query()
    .node_type(NodeType::Function)
    .property("visibility", "public")
    .execute()?;
Source

pub fn flush(&mut self) -> Result<()>

Explicitly flush any buffered writes to disk.

Most operations are durable immediately, but this ensures WAL is synced.

Source

pub fn close(self) -> Result<()>

Close the graph and ensure all data is persisted.

Source

pub fn bfs( &self, start: NodeId, direction: Direction, max_depth: Option<usize>, ) -> Result<Vec<NodeId>>

Perform Breadth-First Search traversal from a starting node.

Returns all reachable nodes within the specified depth limit.

§Parameters
  • start: Starting node ID
  • direction: Follow outgoing or incoming edges
  • max_depth: Optional maximum depth (None for unlimited)
§Returns

Vec of reachable node IDs (excluding the start node)

Source

pub fn dfs( &self, start: NodeId, direction: Direction, max_depth: Option<usize>, ) -> Result<Vec<NodeId>>

Perform Depth-First Search traversal from a starting node.

Uses an iterative approach to avoid stack overflow.

§Parameters
  • start: Starting node ID
  • direction: Follow outgoing or incoming edges
  • max_depth: Optional maximum depth (None for unlimited)
§Returns

Vec of reachable node IDs (excluding the start node)

Source

pub fn find_strongly_connected_components(&self) -> Result<Vec<Vec<NodeId>>>

Find all strongly connected components (SCCs) using Tarjan’s algorithm.

Returns groups of nodes that form circular dependencies.

§Returns

Vec of SCCs, where each SCC is a Vec of node IDs

Source

pub fn find_all_paths( &self, start: NodeId, end: NodeId, max_depth: Option<usize>, ) -> Result<Vec<Vec<NodeId>>>

Find all paths between two nodes up to a maximum depth.

§Parameters
  • start: Starting node ID
  • end: Target node ID
  • max_depth: Maximum path length (recommended: use Some value to prevent infinite loops)
§Returns

Vec of paths, where each path is a Vec of node IDs from start to end

Source

pub fn export_dot(&self) -> Result<String>

Export graph to Graphviz DOT format for visualization.

Warning: Large graphs (>10K nodes) will produce warnings. Graphs over 100K nodes will fail.

Source

pub fn export_dot_styled(&self, options: DotOptions) -> Result<String>

Export graph to Graphviz DOT format with custom styling options.

Source

pub fn export_json(&self) -> Result<String>

Export graph to D3.js-compatible JSON format.

Warning: Large graphs (>10K nodes) will produce warnings. Graphs over 100K nodes will fail.

Source

pub fn export_json_filtered( &self, node_filter: impl Fn(&Node) -> bool, include_edges: bool, ) -> Result<String>

Export filtered subset of graph to JSON.

Source

pub fn export_csv_nodes(&self, path: &Path) -> Result<()>

Export nodes to CSV file.

Warning: Large graphs (>10K nodes) will produce warnings. Graphs over 100K nodes will fail.

Source

pub fn export_csv_edges(&self, path: &Path) -> Result<()>

Export edges to CSV file.

Warning: Large graphs (>10K nodes) will produce warnings. Graphs over 100K nodes will fail.

Source

pub fn export_csv(&self, nodes_path: &Path, edges_path: &Path) -> Result<()>

Export both nodes and edges to separate CSV files (convenience method).

Source

pub fn export_triples(&self) -> Result<String>

Export graph as RDF triples in N-Triples format.

Warning: Large graphs (>10K nodes) will produce warnings. Graphs over 100K nodes will fail.

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