Expand description
Transaction support module
This module provides support for database transactions, including:
- Transaction management functions
- Implementation of
CrudOps
trait forTransaction
objects - Helper functions for working with transactions
There are two ways to use transactions:
- Using the
CrudOps
trait methods directly on aTransaction
object - 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_get
Deprecated - Retrieves a single record within a transaction.
- tx_
get_ all Deprecated - Retrieves multiple records within a transaction.
- tx_
insert - Inserts a record within a transaction.
- tx_
update - Updates a record within a transaction.