Module transaction_ops

Source
Expand description

Transaction support module

This module provides support for database transactions, including:

  • Transaction management functions
  • Implementation of CrudOps trait for Transaction objects
  • Helper functions for working with transactions

There are two ways to use transactions:

  1. Using the CrudOps trait methods directly on a Transaction object
  2. Using the transaction helper functions from the transactional module
use tokio_postgres::{NoTls, Error};
use parsql::tokio_postgres::{CrudOps, transactional};
use parsql::macros::{Insertable, SqlParams};
 
#[derive(Insertable, SqlParams)]
#[table("users")]
struct InsertUser {
    name: String,
    email: String,
}
 
#[tokio::main]
async fn main() -> Result<(), Error> {
    let (mut client, connection) = tokio_postgres::connect("", NoTls).await?;
    tokio::spawn(async move { connection.await; });
     
    // Approach 1: CrudOps trait on Transaction
    let tx = client.transaction().await?;
    let rows = tx.insert(InsertUser {
        name: "John".to_string(),
        email: "john@example.com".to_string(),
    }).await?;
    tx.commit().await?;
     
    // Approach 2: Helper functions
    let tx = transactional::begin(&mut client).await?;
    let (tx, rows) = transactional::tx_insert(tx, InsertUser {
        name: "Jane".to_string(),
        email: "jane@example.com".to_string(),
    }).await?;
    tx.commit().await?;
     
    Ok(())
}

Functions§

begin
Creates and begins a new transaction.
tx_delete
Deletes a record within a transaction.
tx_fetch
Retrieves a single record within a transaction.
tx_fetch_all
Retrieves multiple records within a transaction.
tx_getDeprecated
Retrieves a single record within a transaction.
tx_get_allDeprecated
Retrieves multiple records within a transaction.
tx_insert
Inserts a record within a transaction.
tx_update
Updates a record within a transaction.