pub async fn tx_insert<T: SqlQuery + SqlParams>(
transaction: Transaction<'_>,
entity: T,
) -> Result<(Transaction<'_>, u64), Error>
Expand description
§tx_insert
Inserts a record within a transaction.
§Parameters
transaction
: Active transaction objectentity
: Data object to be inserted (must implement Insertable and SqlParams traits)
§Return Value
Result<(Transaction<'_>, u64), Error>
: On success, returns the transaction and number of inserted records
§Example Usage
use tokio_postgres::{NoTls, Error};
use deadpool_postgres::{Config, Runtime};
use parsql::deadpool_postgres::transactional::tx_insert;
#[derive(Insertable, SqlParams)]
#[table("users")]
pub struct InsertUser {
pub name: String,
pub email: String,
pub state: i16,
}
#[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 insert_user = InsertUser {
name: "John".to_string(),
email: "john@example.com".to_string(),
state: 1,
};
let (tx, rows_affected) = tx_insert(tx, insert_user).await?;
tx.commit().await?;
println!("Inserted {} rows", rows_affected);
Ok(())
}