pub struct Connection { /* private fields */ }Expand description
An active connection to a Geode database server.
A Connection represents a single QUIC connection with an open bidirectional
stream for communication. It provides methods for executing queries, managing
transactions, and controlling the connection lifecycle.
§Connection Lifecycle
- Create via
Client::connect - Execute queries with
queryorquery_with_params - Optionally use transactions with
begin,commit,rollback - Close with
close
§Example
let client = Client::new("localhost", 3141).skip_verify(true);
let mut conn = client.connect().await?;
// Execute queries
let (page, _) = conn.query("RETURN 42 AS answer").await?;
println!("Answer: {}", page.rows[0].get("answer").unwrap().as_int()?);
// Use transactions
conn.begin().await?;
conn.query("CREATE (n:Node {id: 1})").await?;
conn.commit().await?;
conn.close()?;§Thread Safety
Connection is !Sync because the underlying QUIC stream is not thread-safe.
For concurrent access, use ConnectionPool.
Implementations§
Source§impl Connection
impl Connection
Sourcepub async fn query(&mut self, gql: &str) -> Result<(Page, Option<String>)>
pub async fn query(&mut self, gql: &str) -> Result<(Page, Option<String>)>
Execute a GQL query without parameters.
§Arguments
gql- The GQL query string
§Returns
A tuple of (Page, Option<String>) where the page contains the results
and the optional string contains any query warnings.
§Errors
Returns Error::Query if the query fails to execute.
§Example
let (page, _) = conn.query("MATCH (n:Person) RETURN n.name LIMIT 10").await?;
for row in &page.rows {
println!("Name: {}", row.get("name").unwrap().as_string()?);
}Sourcepub async fn query_with_params(
&mut self,
gql: &str,
params: &HashMap<String, Value>,
) -> Result<(Page, Option<String>)>
pub async fn query_with_params( &mut self, gql: &str, params: &HashMap<String, Value>, ) -> Result<(Page, Option<String>)>
Execute a GQL query with parameters.
Parameters are substituted for $param_name placeholders in the query.
This is the recommended way to include dynamic values in queries, as it
prevents injection attacks and allows query plan caching.
§Arguments
gql- The GQL query string with parameter placeholdersparams- A map of parameter names to values
§Returns
A tuple of (Page, Option<String>) where the page contains the results
and the optional string contains any query warnings.
§Errors
Returns Error::Query if the query fails to execute.
§Example
let mut params = HashMap::new();
params.insert("name".to_string(), Value::string("Alice"));
params.insert("min_age".to_string(), Value::int(25));
let (page, _) = conn.query_with_params(
"MATCH (p:Person {name: $name}) WHERE p.age >= $min_age RETURN p",
¶ms
).await?;Sourcepub fn query_sync(
&mut self,
gql: &str,
params: Option<HashMap<String, Value>>,
) -> Result<Page>
pub fn query_sync( &mut self, gql: &str, params: Option<HashMap<String, Value>>, ) -> Result<Page>
Execute a query without parameters (synchronous-style blocking version for test runner)
Sourcepub async fn begin(&mut self) -> Result<()>
pub async fn begin(&mut self) -> Result<()>
Begin a new transaction.
After calling begin, all queries will be part of the transaction until
commit or rollback is called.
§Errors
Returns an error if a transaction is already in progress or if the server rejects the request.
§Example
conn.begin().await?;
conn.query("CREATE (n:Node {id: 1})").await?;
conn.query("CREATE (n:Node {id: 2})").await?;
conn.commit().await?; // Both nodes are now persistedSourcepub async fn rollback(&mut self) -> Result<()>
pub async fn rollback(&mut self) -> Result<()>
Rollback the current transaction.
Discards all changes made since begin was called.
§Errors
Returns an error if no transaction is in progress.
§Example
conn.begin().await?;
match conn.query("CREATE (n:InvalidNode)").await {
Ok(_) => conn.commit().await?,
Err(_) => conn.rollback().await?, // Undo everything
}Sourcepub fn prepare(&self, query: &str) -> Result<PreparedStatement>
pub fn prepare(&self, query: &str) -> Result<PreparedStatement>
Create a prepared statement for efficient repeated execution.
Prepared statements allow you to define a query once and execute it
multiple times with different parameters. The query text is parsed
to extract parameter names (tokens starting with $).
§Arguments
query- The GQL query string with parameter placeholders
§Returns
A PreparedStatement that can be executed multiple times.
§Example
let stmt = conn.prepare("MATCH (p:Person {id: $id}) RETURN p.name")?;
for id in 1..=100 {
let mut params = HashMap::new();
params.insert("id".to_string(), Value::int(id));
let (page, _) = stmt.execute(&mut conn, ¶ms).await?;
// Process results...
}Sourcepub async fn explain(&mut self, gql: &str) -> Result<QueryPlan>
pub async fn explain(&mut self, gql: &str) -> Result<QueryPlan>
Get the execution plan for a query without running it.
This is useful for understanding how the database will execute a query and for identifying potential performance issues.
§Arguments
gql- The GQL query string to explain
§Returns
A QueryPlan containing the execution plan details.
§Errors
Returns an error if the query is invalid or cannot be planned.
§Example
let plan = conn.explain("MATCH (p:Person)-[:KNOWS]->(f) RETURN f").await?;
println!("Estimated rows: {}", plan.estimated_rows);
for op in &plan.operations {
println!(" {} - {}", op.op_type, op.description);
}Sourcepub async fn profile(&mut self, gql: &str) -> Result<QueryProfile>
pub async fn profile(&mut self, gql: &str) -> Result<QueryProfile>
Execute a query and return the execution profile with timing information.
This runs the query and collects detailed execution statistics including actual row counts and timing for each operation.
§Arguments
gql- The GQL query string to profile
§Returns
A QueryProfile containing the execution plan and runtime statistics.
§Errors
Returns an error if the query fails to execute.
§Example
let profile = conn.profile("MATCH (p:Person) RETURN p LIMIT 100").await?;
println!("Execution time: {:.2}ms", profile.execution_time_ms);
println!("Actual rows: {}", profile.actual_rows);Sourcepub async fn batch(
&mut self,
queries: &[(&str, Option<&HashMap<String, Value>>)],
) -> Result<Vec<Page>>
pub async fn batch( &mut self, queries: &[(&str, Option<&HashMap<String, Value>>)], ) -> Result<Vec<Page>>
Execute multiple queries in a batch.
This is more efficient than executing queries one at a time when you have multiple independent queries to run.
§Arguments
queries- A slice of (query, optional params) tuples
§Returns
A Vec<Page> with results for each query, in the same order as input.
§Errors
Returns an error if any query fails. Queries are executed in order, so earlier queries may have completed before the error.
§Example
let results = conn.batch(&[
("MATCH (n:Person) RETURN count(n)", None),
("MATCH (n:Company) RETURN count(n)", None),
("MATCH ()-[r:WORKS_AT]->() RETURN count(r)", None),
]).await?;
for (i, page) in results.iter().enumerate() {
println!("Query {}: {} rows", i + 1, page.rows.len());
}Sourcepub fn close(&mut self) -> Result<()>
pub fn close(&mut self) -> Result<()>
Close the connection.
Gracefully closes the QUIC connection. After calling this method, the connection can no longer be used.
§Note
It’s good practice to explicitly close connections, but they will also be closed when dropped.
§Example
let mut conn = client.connect().await?;
// ... use connection ...
conn.close()?;