pub struct Transaction<'conn> { /* private fields */ }
Expand description

Represents a transaction on a database connection.

Note

Transactions will roll back by default. Use commit method to explicitly commit the transaction, or use set_drop_behavior to change what happens when the transaction is dropped.

Example

fn perform_queries(conn: &mut Connection) -> Result<()> {
    let tx = conn.transaction()?;

    do_queries_part_1(&tx)?; // tx causes rollback if this fails
    do_queries_part_2(&tx)?; // tx causes rollback if this fails

    tx.commit()
}

Implementations

Begin a new transaction. Cannot be nested; see savepoint for nested transactions.

Even though we don’t mutate the connection, we take a &mut Connection so as to prevent nested transactions on the same connection. For cases where this is unacceptable, Transaction::new_unchecked is available.

Starts a new savepoint, allowing nested transactions.

Note

Just like outer level transactions, savepoint transactions rollback by default.

Example
fn perform_queries(conn: &mut Connection) -> Result<()> {
    let mut tx = conn.transaction()?;

    {
        let sp = tx.savepoint()?;
        if perform_queries_part_1_succeeds(&sp) {
            sp.commit()?;
        }
        // otherwise, sp will rollback
    }

    tx.commit()
}

Create a new savepoint with a custom savepoint name. See savepoint().

Get the current setting for what happens to the transaction when it is dropped.

Configure the transaction to perform the specified action when it is dropped.

A convenience method which consumes and commits a transaction.

A convenience method which consumes and rolls back a transaction.

Consumes the transaction, committing or rolling back according to the current setting (see drop_behavior).

Functionally equivalent to the Drop implementation, but allows callers to see any errors that occur.

Methods from Deref<Target = Connection>

Prepare a SQL statement for execution, returning a previously prepared (but not currently in-use) statement if one is available. The returned statement will be cached for reuse by future calls to prepare_cached once it is dropped.

fn insert_new_people(conn: &Connection) -> Result<()> {
    {
        let mut stmt = conn.prepare_cached("INSERT INTO People (name) VALUES (?)")?;
        stmt.execute(["Joe Smith"])?;
    }
    {
        // This will return the same underlying SQLite statement handle without
        // having to prepare it again.
        let mut stmt = conn.prepare_cached("INSERT INTO People (name) VALUES (?)")?;
        stmt.execute(["Bob Jones"])?;
    }
    Ok(())
}
Failure

Will return Err if sql cannot be converted to a C-compatible string or if the underlying SQLite call fails.

Set the maximum number of cached prepared statements this connection will hold. By default, a connection will hold a relatively small number of cached statements. If you need more, or know that you will not use cached statements, you can set the capacity manually using this method.

Remove/finalize all prepared statements currently in the cache.

Query the current value of pragma_name.

Some pragmas will return multiple rows/values which cannot be retrieved with this method.

Prefer PRAGMA function introduced in DuckDB 3.20: SELECT user_version FROM pragma_user_version;

Query the current rows/values of pragma_name.

Prefer PRAGMA function introduced in DuckDB 3.20: SELECT * FROM pragma_collation_list;

Query the current value(s) of pragma_name associated to pragma_value.

This method can be used with query-only pragmas which need an argument (e.g. table_info('one_tbl')) or pragmas which returns value(s) (e.g. integrity_check).

Prefer PRAGMA function introduced in DuckDB 3.20: SELECT * FROM pragma_table_info(?);

Set a new value to pragma_name.

Some pragmas will return the updated value which cannot be retrieved with this method.

Set a new value to pragma_name and return the updated value.

Only few pragmas automatically return the updated value.

Begin a new transaction with the default behavior (DEFERRED).

Attempt to open a nested transaction will result in a DuckDB error. Connection::transaction prevents this at compile time by taking &mut self, but Connection::unchecked_transaction() may be used to defer the checking until runtime.

See Connection::transaction and Transaction::new_unchecked (which can be used if the default transaction behavior is undesirable).

Example
fn perform_queries(conn: Rc<Connection>) -> Result<()> {
    let tx = conn.unchecked_transaction()?;

    do_queries_part_1(&tx)?; // tx causes rollback if this fails
    do_queries_part_2(&tx)?; // tx causes rollback if this fails

    tx.commit()
}
Failure

Will return Err if the underlying DuckDB call fails. The specific error returned if transactions are nested is currently unspecified.

Convenience method to run multiple SQL statements (that cannot take any parameters).

Example
fn create_tables(conn: &Connection) -> Result<()> {
    conn.execute_batch("BEGIN;
                        CREATE TABLE foo(x INTEGER);
                        CREATE TABLE bar(y TEXT);
                        COMMIT;",
    )
}
Failure

Will return Err if sql cannot be converted to a C-compatible string or if the underlying DuckDB call fails.

Convenience method to prepare and execute a single SQL statement.

On success, returns the number of rows that were changed or inserted or deleted.

Example
With params
fn update_rows(conn: &Connection) {
    match conn.execute("UPDATE foo SET bar = 'baz' WHERE qux = ?", [1i32]) {
        Ok(updated) => println!("{} rows were updated", updated),
        Err(err) => println!("update failed: {}", err),
    }
}
With params of varying types
fn update_rows(conn: &Connection) {
    match conn.execute("UPDATE foo SET bar = ? WHERE qux = ?", params![&"baz", 1i32]) {
        Ok(updated) => println!("{} rows were updated", updated),
        Err(err) => println!("update failed: {}", err),
    }
}
Failure

Will return Err if sql cannot be converted to a C-compatible string or if the underlying DuckDB call fails.

Returns the path to the database file, if one exists and is known.

Convenience method to execute a query that is expected to return a single row.

Example
fn preferred_locale(conn: &Connection) -> Result<String> {
    conn.query_row(
        "SELECT value FROM preferences WHERE name='locale'",
        [],
        |row| row.get(0),
    )
}

If the query returns more than one row, all rows except the first are ignored.

Returns Err(QueryReturnedNoRows) if no results are returned. If the query truly is optional, you can call .optional() on the result of this to get a Result<Option<T>>.

Failure

Will return Err if sql cannot be converted to a C-compatible string or if the underlying DuckDB call fails.

Convenience method to execute a query that is expected to return a single row, and execute a mapping via f on that returned row with the possibility of failure. The Result type of f must implement std::convert::From<Error>.

Example
fn preferred_locale(conn: &Connection) -> Result<String> {
    conn.query_row_and_then(
        "SELECT value FROM preferences WHERE name='locale'",
        [],
        |row| row.get(0),
    )
}

If the query returns more than one row, all rows except the first are ignored.

Failure

Will return Err if sql cannot be converted to a C-compatible string or if the underlying DuckDB call fails.

Prepare a SQL statement for execution.

Example
fn insert_new_people(conn: &Connection) -> Result<()> {
    let mut stmt = conn.prepare("INSERT INTO People (name) VALUES (?)")?;
    stmt.execute(["Joe Smith"])?;
    stmt.execute(["Bob Jones"])?;
    Ok(())
}
Failure

Will return Err if sql cannot be converted to a C-compatible string or if the underlying DuckDB call fails.

Create an Appender for fast import data default to use DatabaseName::Main

Example
fn insert_rows(conn: &Connection) -> Result<()> {
    let mut app = conn.appender("foo")?;
    app.append_rows([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]])?;
    Ok(())
}
Failure

Will return Err if table not exists

Create an Appender for fast import data

Example
fn insert_rows(conn: &Connection) -> Result<()> {
    let mut app = conn.appender_to_db("foo", &DatabaseName::Main.to_string())?;
    app.append_rows([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]])?;
    Ok(())
}
Failure

Will return Err if table not exists

Test for auto-commit mode. Autocommit mode is on by default.

Creates a new connection to the already-opened database.

Trait Implementations

Formats the value using the given formatter. Read more
The resulting type after dereferencing.
Dereferences the value.
Executes the destructor for this type. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.