Function update

Source
pub fn update<T: SqlQuery + UpdateParams>(
    client: &mut Client,
    entity: T,
) -> Result<u64, Error>
Expand description

§update

Updates an existing record in the database.

§Parameters

  • client: Database connection client
  • entity: Data object containing the update information (must implement SqlQuery and UpdateParams traits)

§Return Value

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

§Struct Definition

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

#[derive(Updateable, UpdateParams)]  // Required macros
#[table("table_name")]               // Table name to update
#[update("field1, field2")]          // Fields to update (optional)
#[where_clause("id = $")]            // Update condition
pub struct MyEntity {
    pub id: i32,                     // Fields used in the condition
    pub field1: String,              // Fields to be updated
    pub field2: i32,                 // Fields to be updated
    // ...
}
  • Updateable: Automatically generates SQL UPDATE statements
  • UpdateParams: Automatically generates update parameters
  • #[table("table_name")]: Specifies the table name for the update
  • #[update("field1, field2")]: Specifies which fields should be updated (if omitted, all fields will be updated)
  • #[where_clause("id = $")]: Specifies the update condition ($ will be replaced with parameter value)

§Example Usage

use postgres::{Client, NoTls, Error};
use parsql::postgres::update;
 
#[derive(Updateable, UpdateParams)]
#[table("users")]
#[update("name, email")]
#[where_clause("id = $")]
pub struct UpdateUser {
    pub id: i32,
    pub name: String,
    pub email: String,
    pub state: i16,  // This field won't be updated as it's not specified in the update attribute
}

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

    let update_user = UpdateUser {
        id: 1,
        name: String::from("John"),
        email: String::from("[email protected]"),
        state: 2,
    };

    let update_result = update(&mut client, update_user)?;
    println!("Update result: {:?}", update_result);
    Ok(())
}