Function get

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

§get

Retrieves a single record from the database.

§Parameters

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

§Return Value

  • Result<T, Error>: On success, returns the found record; 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
#[where_clause("id = $")]                        // Query condition
pub struct MyEntity {
    pub id: i32,                                 // Field used in the query condition
    pub field1: String,                          // Fields to be populated from the result set
    pub field2: i32,
    // ...
}
 
// A factory method is also useful
impl MyEntity {
    pub fn new(id: i32) -> Self {
        Self {
            id,
            field1: String::default(),
            field2: 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
  • #[where_clause("id = $")]: Specifies the query condition ($ will be replaced with parameter value)

§Example Usage

use postgres::{Client, NoTls, Error};
use parsql::postgres::get;
 
#[derive(Queryable, SqlParams, FromRow, Debug)]
#[table("users")]
#[where_clause("id = $")]
pub struct GetUser {
    pub id: i32,
    pub name: String,
    pub email: String,
    pub state: i16,
}
 
impl GetUser {
    pub fn new(id: i32) -> Self {
        Self {
            id,
            name: String::default(),
            email: String::default(),
            state: 0,
        }
    }
}

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

    let get_user = GetUser::new(1);
    let get_result = get(&mut client, &get_user)?;
     
    println!("Get result: {:?}", get_result);
    Ok(())
}