Function get_all

Source
pub fn get_all<T: SqlQuery + FromRow + SqlParams>(
    client: &mut Client,
    params: &T,
) -> Result<Vec<T>, Error>
Expand description

§get_all

Retrieves multiple records from the database.

§Parameters

  • client: Database connection client
  • params: Query parameter object (must implement SqlQuery, FromRow, and SqlParams traits)

§Return Value

  • Result<Vec<T>, Error>: On success, returns the list of found records; on failure, returns Error

§Struct Definition

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

#[derive(Queryable, SqlParams, FromRow, Debug)]  // Required macros
#[table("table_name")]                           // Table name to query
#[select("field1, field2, COUNT(*) as count")]   // Custom SELECT statement (optional)
#[join("INNER JOIN other_table ON ...")]         // JOIN statements (optional)
#[where_clause("status > $")]                    // Query condition
#[group_by("field1, field2")]                    // GROUP BY statement (optional)
#[having("COUNT(*) > 0")]                        // HAVING statement (optional)
#[order_by("count DESC")]                        // ORDER BY statement (optional)
pub struct MyEntity {
    pub status: i32,                             // Field used in the query condition
    pub field1: String,                          // Fields to be populated from the result set
    pub field2: i32,
    pub count: i64,                              // Calculated value
    // ...
}
 
impl MyEntity {
    pub fn new(status: i32) -> Self {
        Self {
            status,
            field1: String::default(),
            field2: 0,
            count: 0,
            // ...
        }
    }
}
  • Queryable: Automatically generates SQL SELECT statements
  • SqlParams: Automatically generates SQL parameters
  • FromRow: Enables conversion from database row to struct object
  • #[table("table_name")]: Specifies the table name for the query
  • #[select("...")]: Creates a custom SELECT statement (if omitted, all fields will be selected)
  • #[join("...")]: Specifies JOIN statements (can be used multiple times)
  • #[where_clause("...")]: Specifies the query condition ($ will be replaced with parameter value)
  • #[group_by("...")]: Specifies the GROUP BY statement
  • #[having("...")]: Specifies the HAVING statement
  • #[order_by("...")]: Specifies the ORDER BY statement

§Example Usage

use postgres::{Client, NoTls, Error};
use parsql::postgres::get_all;
 
// Simple query example
#[derive(Queryable, SqlParams, FromRow, Debug)]
#[table("users")]
#[where_clause("email = $")]
pub struct GetAllUsers {
    pub id: i32,
    pub name: String,
    pub email: String,
    pub state: i16,
}

// Complex JOIN example
#[derive(Queryable, SqlParams, FromRow, Debug)]
#[table("users")]
#[select("users.id, users.name, users.email, users.state as user_state, posts.id as post_id, posts.content, posts.state as post_state, comments.content as comment")]
#[join("INNER JOIN posts ON users.id = posts.user_id")]
#[join("LEFT JOIN comments ON posts.id = comments.post_id")]
#[where_clause("users.id = $")]
pub struct SelectUserWithPosts {
    pub id: i32,
    pub name: String,
    pub email: String,
    pub user_state: i16,
    pub post_id: i32,
    pub content: String,
    pub post_state: i16,
    pub comment: Option<String>,
}

// GROUP BY and ORDER BY example
#[derive(Queryable, SqlParams, FromRow, Debug)]
#[table("users")]
#[select("users.state, COUNT(*) as user_count")]
#[where_clause("state > $")]
#[group_by("users.state")]
#[order_by("user_count DESC")]
pub struct UserStateStats {
    pub state: i16,
    pub user_count: i64,
}

// HAVING filter example
#[derive(Queryable, SqlParams, FromRow, Debug)]
#[table("users")]
#[select("users.state, COUNT(*) as user_count")]
#[where_clause("state > $")]
#[group_by("users.state")]
#[having("COUNT(*) > 1")]
#[order_by("user_count DESC")]
pub struct UserStateStatsFiltered {
    pub state: i16,
    pub user_count: i64,
}

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

    // Example usage
    let select_user_with_posts = SelectUserWithPosts::new(1);
    let get_user_with_posts = get_all(&mut client, &select_user_with_posts)?;
     
    println!("Get user with posts: {:?}", get_user_with_posts);
     
    // Other examples
    let user_state_stats = get_all(&mut client, &UserStateStats::new(0))?;
    println!("User state stats: {:?}", user_state_stats);
     
    let user_state_stats_filtered = get_all(&mut client, &UserStateStatsFiltered::new(0))?;
    println!("User state stats (filtered with HAVING): {:?}", user_state_stats_filtered);
    Ok(())
}