Function select

Source
pub fn select<T: SqlQuery + SqlParams, F>(
    client: &mut Client,
    entity: T,
    to_model: F,
) -> Result<T, Error>
where F: Fn(&Row) -> Result<T, Error>,
Expand description

§select

Retrieves a single record from the database using a custom transformation function. This is useful when you want to use a custom transformation function instead of the FromRow trait.

§Parameters

  • client: Database connection client
  • entity: Query parameter object (must implement SqlQuery and SqlParams traits)
  • to_model: Function to convert a Row object to the target object type

§Return Value

  • Result<T, Error>: On success, returns the transformed object; on failure, returns Error

§Struct Definition

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

#[derive(Queryable, SqlParams)]          // Required macros (FromRow is not needed)
#[table("table_name")]                   // Table name to query
#[where_clause("id = $")]                // Query condition
pub struct MyQueryEntity {
    pub id: i32,                         // Field used in the query condition
    // Other fields can be added if necessary for the query condition
}
 
// A separate struct can be used for the return value
pub struct MyResultEntity {
    pub id: i32,
    pub name: String,
    pub count: i64,
}
  • Queryable: Automatically generates SQL SELECT statements
  • SqlParams: Automatically generates SQL parameters
  • #[table("table_name")]: Specifies the table name for the query
  • #[where_clause("id = $")]: Specifies the query condition ($ will be replaced with parameter value)

§Example Usage

use postgres::{Client, NoTls, Error};
use parsql::postgres::select;
 
#[derive(Queryable, SqlParams)]
#[table("users")]
#[where_clause("id = $")]
pub struct UserQuery {
    pub id: i32,
}
 
impl UserQuery {
    pub fn new(id: i32) -> Self {
        Self { id }
    }
}
 
// Different return structure
pub struct User {
    pub id: i32,
    pub name: String,
}

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

    // A custom model transformation function is required
    let user_query = UserQuery::new(1);
    let user = select(&mut client, user_query, |row| {
        let id: i32 = row.get("id");
        let name: String = row.get("name");
        Ok(User { id, name })
    })?;
     
    println!("User: {:?}", user);
    Ok(())
}