Skip to main content

GrafeoDB

Struct GrafeoDB 

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

Your handle to a Grafeo database.

Start here. Create one with new_in_memory() for quick experiments, or open() for persistent storage. Then grab a session() to start querying.

§Examples

use grafeo_engine::GrafeoDB;

// Quick in-memory database
let db = GrafeoDB::new_in_memory();

// Add some data
db.create_node(&["Person"]);

// Query it
let session = db.session();
let result = session.execute("MATCH (p:Person) RETURN p")?;

Implementations§

Source§

impl GrafeoDB

Source

pub fn node_count(&self) -> usize

Returns the number of nodes in the database.

Source

pub fn edge_count(&self) -> usize

Returns the number of edges in the database.

Source

pub fn label_count(&self) -> usize

Returns the number of distinct labels in the database.

Source

pub fn property_key_count(&self) -> usize

Returns the number of distinct property keys in the database.

Source

pub fn edge_type_count(&self) -> usize

Returns the number of distinct edge types in the database.

Source

pub fn is_persistent(&self) -> bool

Returns true if this database is backed by a file (persistent).

In-memory databases return false.

Source

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

Returns the database file path, if persistent.

In-memory databases return None.

Source

pub fn info(&self) -> DatabaseInfo

Returns high-level database information.

Includes node/edge counts, persistence status, and mode (LPG/RDF).

Source

pub fn memory_usage(&self) -> MemoryUsage

Returns a hierarchical memory usage breakdown.

Walks all internal structures (store, indexes, MVCC chains, caches, string pools, buffer manager) and returns estimated heap bytes for each. Safe to call concurrently with queries.

Source

pub fn detailed_stats(&self) -> DatabaseStats

Returns detailed database statistics.

Includes counts, memory usage, and index information.

Source

pub fn schema(&self) -> SchemaInfo

Returns schema information (labels, edge types, property keys).

For LPG mode, returns label and edge type information. For RDF mode, returns predicate and named graph information.

Source

pub fn list_indexes(&self) -> Vec<IndexInfo>

Returns detailed information about all indexes.

Source

pub fn validate(&self) -> ValidationResult

Validates database integrity.

Checks for:

  • Dangling edge references (edges pointing to non-existent nodes)
  • Internal index consistency

Returns a list of errors and warnings. Empty errors = valid.

Source

pub fn wal_status(&self) -> WalStatus

Returns WAL (Write-Ahead Log) status.

Returns None if WAL is not enabled.

Source

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

Forces a WAL checkpoint.

Flushes all pending WAL records to the main storage.

§Errors

Returns an error if the checkpoint fails.

Source§

impl GrafeoDB

Source

pub fn create_node(&self, labels: &[&str]) -> NodeId

Creates a node with the given labels and returns its ID.

Labels categorize nodes - think of them like tags. A node can have multiple labels (e.g., ["Person", "Employee"]).

§Examples
use grafeo_engine::GrafeoDB;

let db = GrafeoDB::new_in_memory();
let alix = db.create_node(&["Person"]);
let company = db.create_node(&["Company", "Startup"]);
Source

pub fn create_node_with_props( &self, labels: &[&str], properties: impl IntoIterator<Item = (impl Into<PropertyKey>, impl Into<Value>)>, ) -> NodeId

Creates a new node with labels and properties.

If WAL is enabled, the operation is logged for durability.

Source

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

Gets a node by ID.

Source

pub fn get_node_at_epoch(&self, id: NodeId, epoch: EpochId) -> Option<Node>

Gets a node as it existed at a specific epoch.

Uses pure epoch-based visibility (not transaction-aware), so the node is visible if and only if created_epoch <= epoch and it was not deleted at or before epoch.

Source

pub fn get_edge_at_epoch(&self, id: EdgeId, epoch: EpochId) -> Option<Edge>

Gets an edge as it existed at a specific epoch.

Uses pure epoch-based visibility (not transaction-aware).

Source

pub fn get_node_history( &self, id: NodeId, ) -> Vec<(EpochId, Option<EpochId>, Node)>

Returns all versions of a node with their creation/deletion epochs.

Properties and labels reflect the current state (not versioned per-epoch).

Source

pub fn get_edge_history( &self, id: EdgeId, ) -> Vec<(EpochId, Option<EpochId>, Edge)>

Returns all versions of an edge with their creation/deletion epochs.

Properties reflect the current state (not versioned per-epoch).

Source

pub fn current_epoch(&self) -> EpochId

Returns the current epoch of the database.

Source

pub fn delete_node(&self, id: NodeId) -> bool

Deletes a node and all its edges.

If WAL is enabled, the operation is logged for durability.

Source

pub fn set_node_property(&self, id: NodeId, key: &str, value: Value)

Sets a property on a node.

If WAL is enabled, the operation is logged for durability.

Source

pub fn add_node_label(&self, id: NodeId, label: &str) -> bool

Adds a label to an existing node.

Returns true if the label was added, false if the node doesn’t exist or already has the label.

§Examples
use grafeo_engine::GrafeoDB;

let db = GrafeoDB::new_in_memory();
let alix = db.create_node(&["Person"]);

// Promote Alix to Employee
let added = db.add_node_label(alix, "Employee");
assert!(added);
Source

pub fn remove_node_label(&self, id: NodeId, label: &str) -> bool

Removes a label from a node.

Returns true if the label was removed, false if the node doesn’t exist or doesn’t have the label.

§Examples
use grafeo_engine::GrafeoDB;

let db = GrafeoDB::new_in_memory();
let alix = db.create_node(&["Person", "Employee"]);

// Remove Employee status
let removed = db.remove_node_label(alix, "Employee");
assert!(removed);
Source

pub fn get_node_labels(&self, id: NodeId) -> Option<Vec<String>>

Gets all labels for a node.

Returns None if the node doesn’t exist.

§Examples
use grafeo_engine::GrafeoDB;

let db = GrafeoDB::new_in_memory();
let alix = db.create_node(&["Person", "Employee"]);

let labels = db.get_node_labels(alix).unwrap();
assert!(labels.contains(&"Person".to_string()));
assert!(labels.contains(&"Employee".to_string()));
Source

pub fn create_edge(&self, src: NodeId, dst: NodeId, edge_type: &str) -> EdgeId

Creates an edge (relationship) between two nodes.

Edges connect nodes and have a type that describes the relationship. They’re directed - the order of src and dst matters.

§Examples
use grafeo_engine::GrafeoDB;

let db = GrafeoDB::new_in_memory();
let alix = db.create_node(&["Person"]);
let gus = db.create_node(&["Person"]);

// Alix knows Gus (directed: Alix -> Gus)
let edge = db.create_edge(alix, gus, "KNOWS");
Source

pub fn create_edge_with_props( &self, src: NodeId, dst: NodeId, edge_type: &str, properties: impl IntoIterator<Item = (impl Into<PropertyKey>, impl Into<Value>)>, ) -> EdgeId

Creates a new edge with properties.

If WAL is enabled, the operation is logged for durability.

Source

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

Gets an edge by ID.

Source

pub fn delete_edge(&self, id: EdgeId) -> bool

Deletes an edge.

If WAL is enabled, the operation is logged for durability.

Source

pub fn set_edge_property(&self, id: EdgeId, key: &str, value: Value)

Sets a property on an edge.

If WAL is enabled, the operation is logged for durability.

Source

pub fn remove_node_property(&self, id: NodeId, key: &str) -> bool

Removes a property from a node.

Returns true if the property existed and was removed, false otherwise.

Source

pub fn remove_edge_property(&self, id: EdgeId, key: &str) -> bool

Removes a property from an edge.

Returns true if the property existed and was removed, false otherwise.

Source

pub fn batch_create_nodes( &self, label: &str, property: &str, vectors: Vec<Vec<f32>>, ) -> Vec<NodeId>

Creates multiple nodes in bulk, each with a single vector property.

Much faster than individual create_node_with_props calls because it acquires internal locks once and loops in Rust rather than crossing the FFI boundary per vector.

§Arguments
  • label - Label applied to all created nodes
  • property - Property name for the vector data
  • vectors - Vector data for each node
§Returns

Vector of created NodeIds in the same order as the input vectors.

Source§

impl GrafeoDB

Source

pub fn create_property_index(&self, property: &str)

Creates an index on a node property for O(1) lookups by value.

After creating an index, calls to Self::find_nodes_by_property will be O(1) instead of O(n) for this property. The index is automatically maintained when properties are set or removed.

§Example
// Create an index on the 'email' property
db.create_property_index("email");

// Now lookups by email are O(1)
let nodes = db.find_nodes_by_property("email", &Value::from("alix@example.com"));
Source

pub fn drop_property_index(&self, property: &str) -> bool

Drops an index on a node property.

Returns true if the index existed and was removed.

Source

pub fn has_property_index(&self, property: &str) -> bool

Returns true if the property has an index.

Source

pub fn find_nodes_by_property( &self, property: &str, value: &Value, ) -> Vec<NodeId>

Finds all nodes that have a specific property value.

If the property is indexed, this is O(1). Otherwise, it scans all nodes which is O(n). Use Self::create_property_index for frequently queried properties.

§Example
// Create index for fast lookups (optional but recommended)
db.create_property_index("city");

// Find all nodes where city = "NYC"
let nyc_nodes = db.find_nodes_by_property("city", &Value::from("NYC"));
Source

pub fn create_vector_index( &self, label: &str, property: &str, dimensions: Option<usize>, metric: Option<&str>, m: Option<usize>, ef_construction: Option<usize>, ) -> Result<()>

Creates a vector similarity index on a node property.

This enables efficient approximate nearest-neighbor search on vector properties. Currently validates the index parameters and scans existing nodes to verify the property contains vectors of the expected dimensions.

§Arguments
  • label - Node label to index (e.g., "Doc")
  • property - Property containing vector embeddings (e.g., "embedding")
  • dimensions - Expected vector dimensions (inferred from data if None)
  • metric - Distance metric: "cosine" (default), "euclidean", "dot_product", "manhattan"
  • m - HNSW links per node (default: 16). Higher = better recall, more memory.
  • ef_construction - Construction beam width (default: 128). Higher = better index quality, slower build.
§Errors

Returns an error if the metric is invalid, no vectors are found, or dimensions don’t match.

Source§

impl GrafeoDB

Source

pub fn save(&self, path: impl AsRef<Path>) -> Result<()>

Saves the database to a file path.

  • If in-memory: creates a new persistent database at path
  • If file-backed: creates a copy at the new path

The original database remains unchanged.

§Errors

Returns an error if the save operation fails.

Requires the wal feature for persistence support.

Source

pub fn to_memory(&self) -> Result<Self>

Creates an in-memory copy of this database.

Returns a new database that is completely independent, including all named graph data. Useful for:

  • Testing modifications without affecting the original
  • Faster operations when persistence isn’t needed
§Errors

Returns an error if the copy operation fails.

Source

pub fn open_in_memory(path: impl AsRef<Path>) -> Result<Self>

Opens a database file and loads it entirely into memory.

The returned database has no connection to the original file. Changes will NOT be written back to the file.

§Errors

Returns an error if the file can’t be opened or loaded.

Source

pub fn export_snapshot(&self) -> Result<Vec<u8>>

Exports the entire database to a binary snapshot (v2 format).

The returned bytes can be stored (e.g. in IndexedDB) and later restored with import_snapshot(). Includes all named graph data.

§Errors

Returns an error if serialization fails.

Source

pub fn import_snapshot(data: &[u8]) -> Result<Self>

Creates a new in-memory database from a binary snapshot.

Accepts both v1 (no named graphs) and v2 (with named graphs) formats. The data must have been produced by export_snapshot().

All edge references are validated before any data is inserted: every edge’s source and destination must reference a node present in the snapshot, and duplicate node/edge IDs are rejected. If validation fails, no database is created.

§Errors

Returns an error if the snapshot is invalid, contains dangling edge references, has duplicate IDs, or deserialization fails.

Source

pub fn restore_snapshot(&self, data: &[u8]) -> Result<()>

Replaces the current database contents with data from a binary snapshot.

Accepts both v1 and v2 snapshot formats. The data must have been produced by export_snapshot().

All validation (duplicate IDs, dangling edge references) is performed before any data is modified. If validation fails, the current database is left unchanged. If validation passes, the store is cleared and rebuilt from the snapshot atomically (from the perspective of subsequent queries).

§Errors

Returns an error if the snapshot is invalid, contains dangling edge references, has duplicate IDs, or deserialization fails.

Source

pub fn iter_nodes(&self) -> impl Iterator<Item = Node> + '_

Returns an iterator over all nodes in the database.

Useful for dump/export operations.

Source

pub fn iter_edges(&self) -> impl Iterator<Item = Edge> + '_

Returns an iterator over all edges in the database.

Useful for dump/export operations.

Source§

impl GrafeoDB

Source

pub fn execute(&self, query: &str) -> Result<QueryResult>

Runs a query directly on the database.

A convenience method that creates a temporary session behind the scenes. If you’re running multiple queries, grab a session() instead to avoid the overhead.

Graph context commands (USE GRAPH, SESSION SET GRAPH, SESSION RESET) persist across calls: running execute("USE GRAPH analytics") followed by execute("MATCH (n) RETURN n") routes the second query to the analytics graph.

§Errors

Returns an error if parsing or execution fails.

Source

pub fn execute_at_epoch( &self, query: &str, epoch: EpochId, ) -> Result<QueryResult>

Executes a GQL query with visibility at the specified epoch.

This enables time-travel queries: the query sees the database as it existed at the given epoch.

§Errors

Returns an error if parsing or execution fails.

Source

pub fn execute_with_params( &self, query: &str, params: HashMap<String, Value>, ) -> Result<QueryResult>

Executes a query with parameters and returns the result.

§Errors

Returns an error if the query fails.

Source

pub fn execute_language( &self, query: &str, language: &str, params: Option<HashMap<String, Value>>, ) -> Result<QueryResult>

Executes a query in the specified language by name.

Supported language names: "gql", "cypher", "gremlin", "graphql", "sparql", "sql". Each requires the corresponding feature flag.

§Errors

Returns an error if the language is unknown/disabled, or if the query fails.

Source

pub fn query_scalar<T: FromValue>(&self, query: &str) -> Result<T>

Executes a query and returns a single scalar value.

§Errors

Returns an error if the query fails or doesn’t return exactly one row.

Source§

impl GrafeoDB

Source

pub fn new_in_memory() -> Self

Creates an in-memory database, fast to create, gone when dropped.

Use this for tests, experiments, or when you don’t need persistence. For data that survives restarts, use open() instead.

§Panics

Panics if the internal arena allocator cannot be initialized (out of memory). Use with_config() for a fallible alternative.

§Examples
use grafeo_engine::GrafeoDB;

let db = GrafeoDB::new_in_memory();
let session = db.session();
session.execute("INSERT (:Person {name: 'Alix'})")?;
Source

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

Opens a database at the given path, creating it if it doesn’t exist.

If you’ve used this path before, Grafeo recovers your data from the write-ahead log automatically. First open on a new path creates an empty database.

§Errors

Returns an error if the path isn’t writable or recovery fails.

§Examples
use grafeo_engine::GrafeoDB;

let db = GrafeoDB::open("./my_social_network")?;
Source

pub fn with_config(config: Config) -> Result<Self>

Creates a database with custom configuration.

Use this when you need fine-grained control over memory limits, thread counts, or persistence settings. For most cases, new_in_memory() or open() are simpler.

§Errors

Returns an error if the database can’t be created or recovery fails.

§Examples
use grafeo_engine::{GrafeoDB, Config};

// In-memory with a 512MB limit
let config = Config::in_memory()
    .with_memory_limit(512 * 1024 * 1024);

let db = GrafeoDB::with_config(config)?;
Source

pub fn with_store(store: Arc<dyn GraphStoreMut>, config: Config) -> Result<Self>

Creates a database backed by a custom GraphStoreMut implementation.

The external store handles all data persistence. WAL, CDC, and index management are the responsibility of the store implementation.

Query execution (all 6 languages, optimizer, planner) works through the provided store. Admin operations (schema introspection, persistence, vector/text indexes) are not available on external stores.

§Examples
use std::sync::Arc;
use grafeo_engine::{GrafeoDB, Config};
use grafeo_core::graph::GraphStoreMut;

fn example(store: Arc<dyn GraphStoreMut>) -> grafeo_common::utils::error::Result<()> {
    let db = GrafeoDB::with_store(store, Config::in_memory())?;
    let result = db.execute("MATCH (n) RETURN count(n)")?;
    Ok(())
}
Source

pub fn session(&self) -> Session

Opens a new session for running queries.

Sessions are cheap to create: spin up as many as you need. Each gets its own transaction context, so concurrent sessions won’t block each other on reads.

§Panics

Panics if the database was configured with an external graph store and the internal arena allocator cannot be initialized (out of memory).

§Examples
use grafeo_engine::GrafeoDB;

let db = GrafeoDB::new_in_memory();
let session = db.session();

// Run queries through the session
let result = session.execute("MATCH (n) RETURN count(n)")?;
Source

pub fn current_graph(&self) -> Option<String>

Returns the current graph name, if any.

This is the persistent graph context used by one-shot execute() calls. It is updated whenever execute() encounters USE GRAPH, SESSION SET GRAPH, or SESSION RESET.

Source

pub fn set_current_graph(&self, name: Option<&str>)

Sets the current graph context for subsequent one-shot execute() calls.

This is equivalent to running USE GRAPH <name> but without creating a session. Pass None to reset to the default graph.

Source

pub fn adaptive_config(&self) -> &AdaptiveConfig

Returns the adaptive execution configuration.

Source

pub fn config(&self) -> &Config

Returns the configuration.

Source

pub fn graph_model(&self) -> GraphModel

Returns the graph data model of this database.

Source

pub fn memory_limit(&self) -> Option<usize>

Returns the configured memory limit in bytes, if any.

Source

pub fn store(&self) -> &Arc<LpgStore>

Returns the underlying (default) store.

This provides direct access to the LPG store for algorithm implementations and admin operations (index management, schema introspection, MVCC internals).

For code that only needs read/write graph operations, prefer graph_store() which returns the trait interface.

Source

pub fn create_graph(&self, name: &str) -> Result<bool>

Creates a named graph. Returns true if created, false if it already exists.

§Errors

Returns an error if arena allocation fails.

Source

pub fn drop_graph(&self, name: &str) -> bool

Drops a named graph. Returns true if dropped, false if it did not exist.

Source

pub fn list_graphs(&self) -> Vec<String>

Returns all named graph names.

Source

pub fn graph_store(&self) -> Arc<dyn GraphStoreMut>

Returns the graph store as a trait object.

This provides the GraphStoreMut interface for code that should work with any storage backend. Use this when you only need graph read/write operations and don’t need admin methods like index management.

Source

pub fn gc(&self)

Garbage collects old MVCC versions that are no longer visible.

Determines the minimum epoch required by active transactions and prunes version chains older than that threshold. Also cleans up completed transaction metadata in the transaction manager.

Source

pub fn buffer_manager(&self) -> &Arc<BufferManager>

Returns the buffer manager for memory-aware operations.

Source

pub fn query_cache(&self) -> &Arc<QueryCache>

Returns the query cache.

Source

pub fn clear_plan_cache(&self)

Clears all cached query plans.

This is called automatically after DDL operations, but can also be invoked manually after external schema changes (e.g., WAL replay, import) or when you want to force re-optimization of all queries.

Source

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

Closes the database, flushing all pending writes.

For persistent databases, this ensures everything is safely on disk. Called automatically when the database is dropped, but you can call it explicitly if you need to guarantee durability at a specific point.

§Errors

Returns an error if the WAL can’t be flushed (check disk space/permissions).

Source

pub fn wal(&self) -> Option<&Arc<LpgWal>>

Returns the typed WAL if available.

Trait Implementations§

Source§

impl AdminService for GrafeoDB

Source§

fn info(&self) -> DatabaseInfo

Returns high-level database information (counts, mode, persistence).
Source§

fn detailed_stats(&self) -> DatabaseStats

Returns detailed database statistics (memory, disk, indexes).
Source§

fn schema(&self) -> SchemaInfo

Returns schema information (labels, edge types, property keys).
Source§

fn validate(&self) -> ValidationResult

Validates database integrity, returning errors and warnings.
Source§

fn wal_status(&self) -> WalStatus

Returns WAL (Write-Ahead Log) status.
Source§

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

Forces a WAL checkpoint, flushing pending records to storage. Read more
Source§

impl Drop for GrafeoDB

Source§

fn drop(&mut self)

Executes the destructor for this type. 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.

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