Struct kuzu::Connection

source ·
pub struct Connection<'a> { /* private fields */ }
Expand description

Connections are used to interact with a Database instance.

Concurrency

Each connection is thread-safe, and multiple connections can connect to the same Database instance in a multithreaded environment.

Note that since connections require a reference to the Database, creating or using connections in multiple threads cannot be done from a regular std::thread since the threads (and connections) could outlive the database. This can be worked around by using a scoped thread (Note: Introduced in rust 1.63. For compatibility with older versions of rust, crosssbeam_utils::thread::scope can be used instead).

Also note that write queries can only be done one at a time; the query command will return an error if another write query is in progress.

let conn = Connection::new(&db)?;
conn.query("CREATE NODE TABLE Person(name STRING, age INT32, PRIMARY KEY(name));")?;
// Write queries must be done sequentially
conn.query("CREATE (:Person {name: 'Alice', age: 25});")?;
conn.query("CREATE (:Person {name: 'Bob', age: 30});")?;
let (alice, bob) = std::thread::scope(|s| -> Result<(Vec<Value>, Vec<Value>), Error> {
    let alice_thread = s.spawn(|| -> Result<Vec<Value>, Error> {
        let conn = Connection::new(&db)?;
        let mut result = conn.query("MATCH (a:Person) WHERE a.name = \"Alice\" RETURN a.name AS NAME, a.age AS AGE;")?;
        Ok(result.next().unwrap())
    });
    let bob_thread = s.spawn(|| -> Result<Vec<Value>, Error> {
        let conn = Connection::new(&db)?;
        let mut result = conn.query(
            "MATCH (a:Person) WHERE a.name = \"Bob\" RETURN a.name AS NAME, a.age AS AGE;",
        )?;
        Ok(result.next().unwrap())
    });
    Ok((alice_thread.join().unwrap()?, bob_thread.join().unwrap()?))
 })?;

 assert_eq!(alice, vec!["Alice".into(), 25.into()]);
 assert_eq!(bob, vec!["Bob".into(), 30.into()]);
 temp_dir.close()?;
 Ok(())

Committing

If the connection is in AUTO_COMMIT mode any query over the connection will be wrapped around a transaction and committed (even if the query is READ_ONLY). If the connection is in MANUAL transaction mode, which happens only if an application manually begins a transaction (see below), then an application has to manually commit or rollback the transaction by calling commit() or rollback().

AUTO_COMMIT is the default mode when a Connection is created. If an application calls begin[ReadOnly/Write]Transaction at any point, the mode switches to MANUAL. This creates an “active transaction” in the connection. When a connection is in MANUAL mode and the active transaction is rolled back or committed, then the active transaction is removed (so the connection no longer has an active transaction) and the mode automatically switches back to AUTO_COMMIT. Note: When a Connection object is deconstructed, if the connection has an active (manual) transaction, then the active transaction is rolled back.

use kuzu::{Database, SystemConfig, Connection};
let db = Database::new(path, SystemConfig::default())?;
let conn = Connection::new(&db)?;
// AUTO_COMMIT mode
conn.query("CREATE NODE TABLE Person(name STRING, age INT64, PRIMARY KEY(name));")?;
conn.begin_write_transaction()?;
// MANUAL mode (write)
conn.query("CREATE (:Person {name: 'Alice', age: 25});")?;
conn.query("CREATE (:Person {name: 'Bob', age: 30});")?;
// Queries committed and mode goes back to AUTO_COMMIT
conn.commit()?;
let result = conn.query("MATCH (a:Person) RETURN a.name AS NAME, a.age AS AGE;")?;
assert!(result.count() == 2);
use kuzu::{Database, SystemConfig, Connection};
let db = Database::new(path, SystemConfig::default())?;
let conn = Connection::new(&db)?;
// AUTO_COMMIT mode
conn.query("CREATE NODE TABLE Person(name STRING, age INT64, PRIMARY KEY(name));")?;
conn.begin_write_transaction()?;
// MANUAL mode (write)
conn.query("CREATE (:Person {name: 'Alice', age: 25});")?;
conn.query("CREATE (:Person {name: 'Bob', age: 30});")?;
// Queries rolled back and mode goes back to AUTO_COMMIT
conn.rollback()?;
let result = conn.query("MATCH (a:Person) RETURN a.name AS NAME, a.age AS AGE;")?;
assert!(result.count() == 0);

Implementations§

source§

impl<'a> Connection<'a>

source

pub fn new(database: &'a Database) -> Result<Self, Error>

Creates a connection to the database.

Arguments
  • database: A reference to the database instance to which this connection will be connected.
source

pub fn set_max_num_threads_for_exec(&mut self, num_threads: u64)

Sets the maximum number of threads to use for execution in the current connection

Arguments
  • num_threads: The maximum number of threads to use for execution in the current connection
source

pub fn get_max_num_threads_for_exec(&self) -> u64

Returns the maximum number of threads used for execution in the current connection

source

pub fn prepare(&self, query: &str) -> Result<PreparedStatement, Error>

Prepares the given query and returns the prepared statement.

Arguments
source

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

Executes the given query and returns the result.

Arguments
source

pub fn execute( &self, prepared_statement: &mut PreparedStatement, params: Vec<(&str, Value)> ) -> Result<QueryResult, Error>

Executes the given prepared statement with args and returns the result.

Arguments
  • prepared_statement: The prepared statement to execute
source

pub fn begin_read_only_transaction(&self) -> Result<(), Error>

Manually starts a new read-only transaction in the current connection

source

pub fn begin_write_transaction(&self) -> Result<(), Error>

Manually starts a new write transaction in the current connection

source

pub fn commit(&self) -> Result<(), Error>

Manually commits the current transaction

source

pub fn rollback(&self) -> Result<(), Error>

Manually rolls back the current transaction

source

pub fn interrupt(&self) -> Result<(), Error>

Interrupts all queries currently executing within this connection

source

pub fn set_query_timeout(&self, timeout_ms: u64)

Sets the query timeout value of the current connection

A value of zero (the default) disables the timeout.

Trait Implementations§

source§

impl<'a> Send for Connection<'a>

source§

impl<'a> Sync for Connection<'a>

Auto Trait Implementations§

§

impl<'a> !RefUnwindSafe for Connection<'a>

§

impl<'a> Unpin for Connection<'a>

§

impl<'a> UnwindSafe for Connection<'a>

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

§

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

§

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.