Function select_all

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

§select_all

Retrieves multiple records 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<Vec<T>, Error>: On success, returns the list of transformed objects; 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
#[select("id, name, COUNT(*) as count")] // Custom SELECT statement (optional)
#[where_clause("active = $")]            // Query condition
pub struct MyQueryEntity {
    pub active: bool,                    // 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
  • #[select("...")]: Creates a custom SELECT statement (if omitted, all fields will be selected)
  • #[where_clause("active = $")]: Specifies the query condition ($ will be replaced with parameter value)

§Example Usage

use postgres::{Client, NoTls, Error};
use parsql::postgres::select_all;
 
#[derive(Queryable, SqlParams)]
#[table("users")]
#[select("id, name, email")]
pub struct UsersQuery {
    // Can be empty for a parameterless query
}
 
impl UsersQuery {
    pub fn new() -> Self {
        Self {}
    }
}
 
// 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 users_query = UsersQuery::new();
    let users = select_all(&mut client, users_query, |row| {
        let id: i32 = row.get("id");
        let name: String = row.get("name");
        User { id, name }
    })?;
     
    println!("Users: {:?}", users);
    Ok(())
}