Trait Statement

Source
pub trait Statement {
    // Required method
    fn execute_statement(
        &self,
        connection: &mut impl GenericClient,
    ) -> Result<u64, Error>;
}
Expand description

A Statement is a SQL statement that, unlike a Query, does not return rows. Instead, it returns the number of rows that have been affected by the statement.

§Example

Statement can be derived like so:

#[derive(Statement)]
#[statement(sql = "DELETE FROM Person WHERE id = @id")]
struct DeletePerson {
    // Define the statement's parameters
    id: i32
}

It then can be used like so:

fn main() -> Result<(), postgres::Error> {
    let connection_string = std::env::var("POSTGRES_CONNECTION_STRING")
        .unwrap_or("host=localhost user=postgres".to_owned());
    let mut db = postgres::Client::connect(&connection_string, postgres::NoTls)?;

    let delete_count = DeletePerson {
        id: 123
    }.execute_statement(&mut db)?;

    println!("Deleted {} people", delete_count);
    Ok(())
}

For a more thorough example (including bulk queries), see the example project folder in the GitHub repository.

§Notes

  • In order to use #[derive(Statement), you must also provide the helper attribute #[statement(sql = "...")
    • The sql parameter is required and must be a string literal
    • Unlike Query, there is no row parameter because Statement does not return rows (but rather a count of the number of rows affected)
  • At compile time, the derive macro will check that the parameter names you used in your query match the field names defined in the struct. A mismatch (e.g. using “@idd” instead of “@id” when the field name is id) will cause a compiler error.
  • If you want to include a single literal @ in your SQL, you must escape it by doubling it (@@)

Required Methods§

Source

fn execute_statement( &self, connection: &mut impl GenericClient, ) -> Result<u64, Error>

Execute a given statement on a given database connection or transaction, and return the number of rows that were affected.

For the sole argument you can pass either a database connection (i.e. postgres::Client) or a transaction (i.e. postgres::Transaction).

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§