Function tx_update

Source
pub async fn tx_update<T: SqlQuery + SqlParams>(
    transaction: Transaction<'_>,
    entity: T,
) -> Result<(Transaction<'_>, u64), Error>
Expand description

§begin_from_pool

Starts a new database transaction directly from a connection pool.

§Parameters

  • pool: Connection pool to start the transaction from

§Return Value

  • Result<(Client, Transaction<'_>), Error>: On success, returns the client and transaction

§Example Usage

use tokio_postgres::{NoTls, Error};
use deadpool_postgres::{Config, Runtime};
use parsql::deadpool_postgres::transactional::begin_from_pool;
 
#[tokio::main]
async fn main() -> Result<(), Error> {
    let mut cfg = Config::new();
    cfg.host = Some("localhost".to_string());
    cfg.dbname = Some("test".to_string());
     
    let pool = cfg.create_pool(Some(Runtime::Tokio1), NoTls)?;
     
    // Instead of using begin_from_pool, we'll get a client and start a transaction
    let client = pool.get().await.unwrap();
    let tx = client.transaction().await?;
     
    // Now you can use the transaction
     
    // Commit the transaction
    tx.commit().await?;
    // Client will be dropped and returned to the pool automatically
     
    Ok(())
}

§tx_update

Updates a record within a transaction.

§Parameters

  • transaction: Active transaction object
  • entity: Data object containing the update information (must implement Updateable and SqlParams traits)

§Return Value

  • Result<(Transaction<'_>, u64), Error>: On success, returns the transaction and number of updated records

§Example Usage

use tokio_postgres::{NoTls, Error};
use deadpool_postgres::{Config, Runtime};
use parsql::deadpool_postgres::transactional::tx_update;
 
#[derive(Updateable, UpdateParams)]
#[table("users")]
#[update("name, email")]
#[where_clause("id = $")]
pub struct UpdateUser {
    pub id: i32,
    pub name: String,
    pub email: String,
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    let mut cfg = Config::new();
    cfg.host = Some("localhost".to_string());
    cfg.dbname = Some("test".to_string());
     
    let pool = cfg.create_pool(Some(Runtime::Tokio1), NoTls)?;
    let client = pool.get().await?;
     
    let mut tx = client.transaction().await?;
     
    let update_user = UpdateUser {
        id: 1,
        name: String::from("John"),
        email: String::from("john@example.com"),
    };
     
    let (tx, rows_affected) = tx_update(tx, update_user).await?;
    tx.commit().await?;
     
    println!("Updated {} rows", rows_affected);
    Ok(())
}