Skip to main content

PooledConnection

Struct PooledConnection 

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

A pooled connection that returns to the pool when dropped

Implementations§

Source§

impl PooledConnection

Source

pub fn inner(&self) -> &Connection

Get a reference to the underlying connection.

§Panics

Panics if called after the connection has been dropped or taken. This should never happen in normal usage as the connection is only taken during Drop.

Methods from Deref<Target = Connection>§

Source

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()?);
}
Source

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 placeholders
  • params - 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",
    &params
).await?;
Source

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)

Source

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 persisted
Source

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

Commit the current transaction.

Persists all changes made since begin was called.

§Errors

Returns an error if no transaction is in progress or if the server rejects the commit.

§Example
conn.begin().await?;
conn.query("CREATE (n:Node)").await?;
conn.commit().await?;  // Changes are now permanent
Source

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
}
Source

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, &params).await?;
    // Process results...
}
Source

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);
}
Source

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);
Source

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());
}
Source

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

Close the connection.

Gracefully closes the 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()?;
Source

pub fn is_healthy(&self) -> bool

Check if the connection is still healthy.

Returns true if the underlying QUIC connection is still open and usable. This is used by connection pools to verify connections before reuse.

§Example
let mut conn = client.connect().await?;
if conn.is_healthy() {
    // Connection is still usable
    let (page, _) = conn.query("RETURN 1").await?;
}

Trait Implementations§

Source§

impl Deref for PooledConnection

Source§

type Target = Connection

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl DerefMut for PooledConnection

Source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
Source§

impl Drop for PooledConnection

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> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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