Function insert

Source
pub fn insert<T: SqlQuery + SqlParams, P: for<'a> FromSql<'a> + Send + Sync>(
    client: &mut Client,
    entity: T,
) -> Result<P, Error>
Expand description

§insert

Inserts a new record into the database.

§Parameters

  • client: Database connection client
  • entity: Data object to be inserted (must implement SqlQuery and SqlParams traits)

§Return Value

  • Result<u64, Error>: On success, returns the number of inserted records; on failure, returns Error

§Struct Definition

Structs used with this function should be annotated with the following derive macros:

#[derive(Insertable, SqlParams)]  // Required macros
#[table("table_name")]            // Table name to insert into
pub struct MyEntity {
    pub field1: String,
    pub field2: i32,
    // ...
}
  • Insertable: Automatically generates SQL INSERT statements
  • SqlParams: Automatically generates SQL parameters
  • #[table("table_name")]: Specifies the table name for the insertion

§Example Usage

use postgres::{Client, NoTls, Error};
use parsql::postgres::insert;
 
#[derive(Insertable, SqlParams)]
#[table("users")]
pub struct InsertUser {
    pub name: String,
    pub email: String,
    pub state: i16,
}

fn main() -> Result<(), Error> {
    let mut client = Client::connect(
        "host=localhost user=postgres dbname=test",
        NoTls,
    )?;

    let insert_user = InsertUser {
        name: "John".to_string(),
        email: "[email protected]".to_string(),
        state: 1_i16,
    };

    let insert_result = insert(&mut client, insert_user)?;
    println!("Insert result: {:?}", insert_result);
    Ok(())
}