Skip to main content

Session

Struct Session 

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

Your handle to the database - execute queries and manage transactions.

Get one from GrafeoDB::session(). Each session tracks its own transaction state, so you can have multiple concurrent sessions without them interfering.

Implementations§

Source§

impl Session

Source

pub fn graph_model(&self) -> GraphModel

Returns the graph model this session operates on.

Source

pub fn use_graph(&self, name: &str)

Sets the current graph for this session (USE GRAPH).

Source

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

Returns the current graph name, if any.

Source

pub fn set_time_zone(&self, tz: &str)

Sets the session time zone.

Source

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

Returns the session time zone, if set.

Source

pub fn set_parameter(&self, key: &str, value: Value)

Sets a session parameter.

Source

pub fn get_parameter(&self, key: &str) -> Option<Value>

Gets a session parameter by cloning it.

Source

pub fn reset_session(&self)

Resets all session state to defaults.

Source

pub fn set_viewing_epoch(&self, epoch: EpochId)

Sets a viewing epoch override for time-travel queries.

While set, all queries on this session see the database as it existed at the given epoch. Use clear_viewing_epoch to return to normal behavior.

Source

pub fn clear_viewing_epoch(&self)

Clears the viewing epoch override, returning to normal behavior.

Source

pub fn viewing_epoch(&self) -> Option<EpochId>

Returns the current viewing epoch override, if any.

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 execute(&self, query: &str) -> Result<QueryResult>

Executes a GQL query.

§Errors

Returns an error if the query fails to parse or execute.

§Examples
use grafeo_engine::GrafeoDB;

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

// Create a node
session.execute("INSERT (:Person {name: 'Alix', age: 30})")?;

// Query nodes
let result = session.execute("MATCH (n:Person) RETURN n.name, n.age")?;
for row in &result.rows {
    println!("{:?}", row);
}
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 GQL query with parameters.

§Errors

Returns an error if the query fails to parse or execute.

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 the query fails.

Source

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

Begins a new transaction.

§Errors

Returns an error if a transaction is already active.

§Examples
use grafeo_engine::GrafeoDB;

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

session.begin_transaction()?;
session.execute("INSERT (:Person {name: 'Alix'})")?;
session.execute("INSERT (:Person {name: 'Gus'})")?;
session.commit()?; // Both inserts committed atomically
Source

pub fn begin_transaction_with_isolation( &mut self, isolation_level: IsolationLevel, ) -> Result<()>

Begins a transaction with a specific isolation level.

See begin_transaction for the default (SnapshotIsolation).

§Errors

Returns an error if a transaction is already active.

Source

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

Commits the current transaction.

Makes all changes since begin_transaction permanent.

§Errors

Returns an error if no transaction is active.

Source

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

Aborts the current transaction.

Discards all changes since begin_transaction.

§Errors

Returns an error if no transaction is active.

§Examples
use grafeo_engine::GrafeoDB;

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

session.begin_transaction()?;
session.execute("INSERT (:Person {name: 'Alix'})")?;
session.rollback()?; // Insert is discarded
Source

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

Creates a named savepoint within the current transaction.

The savepoint captures the current node/edge ID counters so that rollback_to_savepoint can discard entities created after this point.

§Errors

Returns an error if no transaction is active.

Source

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

Rolls back to a named savepoint, undoing all writes made after it.

The savepoint and any savepoints created after it are removed. Entities with IDs >= the savepoint snapshot are discarded.

§Errors

Returns an error if no transaction is active or the savepoint does not exist.

Source

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

Releases (removes) a named savepoint without rolling back.

§Errors

Returns an error if no transaction is active or the savepoint does not exist.

Source

pub fn in_transaction(&self) -> bool

Returns whether a transaction is active.

Source

pub fn prepare_commit(&mut self) -> Result<PreparedCommit<'_>>

Prepares the current transaction for a two-phase commit.

Returns a PreparedCommit that lets you inspect pending changes and attach metadata before finalizing. The mutable borrow prevents concurrent operations while the commit is pending.

If the PreparedCommit is dropped without calling commit() or abort(), the transaction is automatically rolled back.

§Errors

Returns an error if no transaction is active.

§Examples
use grafeo_engine::GrafeoDB;

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

session.begin_transaction()?;
session.execute("INSERT (:Person {name: 'Alix'})")?;

let mut prepared = session.prepare_commit()?;
println!("Nodes written: {}", prepared.info().nodes_written);
prepared.set_metadata("audit_user", "admin");
prepared.commit()?;
Source

pub fn set_auto_commit(&mut self, auto_commit: bool)

Sets auto-commit mode.

Source

pub fn auto_commit(&self) -> bool

Returns whether auto-commit is enabled.

Source

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

Creates a node directly (bypassing query execution).

This is a low-level API for testing and direct manipulation. If a transaction is active, the node will be versioned with the transaction ID.

Source

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

Creates a node with properties.

If a transaction is active, the node will be versioned with the transaction ID.

Source

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

Creates an edge between two nodes.

This is a low-level API for testing and direct manipulation. If a transaction is active, the edge will be versioned with the transaction ID.

Source

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

Gets a node by ID directly, bypassing query planning.

This is the fastest way to retrieve a single node when you know its ID. Skips parsing, binding, optimization, and physical planning entirely.

§Performance
  • Time complexity: O(1) average case
  • No lock contention (uses DashMap internally)
  • ~20-30x faster than equivalent MATCH query
§Example
let session = db.session();
let node_id = session.create_node(&["Person"]);

// Direct lookup - O(1), no query planning
let node = session.get_node(node_id);
assert!(node.is_some());
Source

pub fn get_node_property(&self, id: NodeId, key: &str) -> Option<Value>

Gets a single property from a node by ID, bypassing query planning.

More efficient than get_node() when you only need one property, as it avoids loading the full node with all properties.

§Performance
  • Time complexity: O(1) average case
  • No query planning overhead
§Example
let session = db.session();
let id = session.create_node_with_props(&["Person"], [("name", "Alix".into())]);

// Direct property access - O(1)
let name = session.get_node_property(id, "name");
assert_eq!(name, Some(Value::String("Alix".into())));
Source

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

Gets an edge by ID directly, bypassing query planning.

§Performance
  • Time complexity: O(1) average case
  • No lock contention
Source

pub fn get_neighbors_outgoing(&self, node: NodeId) -> Vec<(NodeId, EdgeId)>

Gets outgoing neighbors of a node directly, bypassing query planning.

Returns (neighbor_id, edge_id) pairs for all outgoing edges.

§Performance
  • Time complexity: O(degree) where degree is the number of outgoing edges
  • Uses adjacency index for direct access
  • ~10-20x faster than equivalent MATCH query
§Example
let session = db.session();
let alix = session.create_node(&["Person"]);
let gus = session.create_node(&["Person"]);
session.create_edge(alix, gus, "KNOWS");

// Direct neighbor lookup - O(degree)
let neighbors = session.get_neighbors_outgoing(alix);
assert_eq!(neighbors.len(), 1);
assert_eq!(neighbors[0].0, gus);
Source

pub fn get_neighbors_incoming(&self, node: NodeId) -> Vec<(NodeId, EdgeId)>

Gets incoming neighbors of a node directly, bypassing query planning.

Returns (neighbor_id, edge_id) pairs for all incoming edges.

§Performance
  • Time complexity: O(degree) where degree is the number of incoming edges
  • Uses backward adjacency index for direct access
Source

pub fn get_neighbors_outgoing_by_type( &self, node: NodeId, edge_type: &str, ) -> Vec<(NodeId, EdgeId)>

Gets outgoing neighbors filtered by edge type, bypassing query planning.

§Example
let neighbors = session.get_neighbors_outgoing_by_type(alix, "KNOWS");
Source

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

Checks if a node exists, bypassing query planning.

§Performance
  • Time complexity: O(1)
  • Fastest existence check available
Source

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

Checks if an edge exists, bypassing query planning.

Source

pub fn get_degree(&self, node: NodeId) -> (usize, usize)

Gets the degree (number of edges) of a node.

Returns (outgoing_degree, incoming_degree).

Source

pub fn get_nodes_batch(&self, ids: &[NodeId]) -> Vec<Option<Node>>

Batch lookup of multiple nodes by ID.

More efficient than calling get_node() in a loop because it amortizes overhead.

§Performance
  • Time complexity: O(n) where n is the number of IDs
  • Better cache utilization than individual lookups

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