Function delete

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

§delete

Deletes a record from the database.

§Parameters

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

§Return Value

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

§Struct Definition

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

#[derive(Deletable, SqlParams)]   // Required macros
#[table("table_name")]             // Table name to delete from
#[where_clause("id = $")]          // Delete condition
pub struct MyEntity {
    pub id: i32,                   // Fields used in the condition
    // Other fields can be added, but typically only condition fields are necessary
}
  • Deletable: Automatically generates SQL DELETE statements
  • SqlParams: Automatically generates SQL parameters
  • #[table("table_name")]: Specifies the table name for the deletion
  • #[where_clause("id = $")]: Specifies the delete condition ($ will be replaced with parameter value)

§Example Usage

use postgres::{Client, NoTls, Error};
use parsql::postgres::delete;
 
#[derive(Deletable, SqlParams)]
#[table("users")]
#[where_clause("id = $")]
pub struct DeleteUser {
    pub id: i32,
}
 
fn main() -> Result<(), Error> {
    let mut client = Client::connect(
        "host=localhost user=postgres dbname=test",
        NoTls,
    )?;

    let delete_user = DeleteUser { id: 6 };
    let delete_result = delete(&mut client, delete_user)?;
     
    println!("Delete result: {:?}", delete_result);
    Ok(())
}