Function fetch

Source
pub fn fetch<P, R>(conn: &Connection, params: &P) -> Result<R, Error>
where P: SqlQuery<R> + SqlParams, R: FromRow,
Expand description

§fetch

Retrieves a single record from the database based on a specific condition.

§Parameters

  • conn: SQLite database connection
  • entity: Query parameter object (must implement SqlQuery, FromRow, and SqlParams traits)

§Return Value

  • Result<T, Error>: On success, returns the queried record; on failure, returns Error

§Struct Definition

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

#[derive(Queryable, FromRow, SqlParams)]  // Required macros
#[table("table_name")]                    // Table name to query
#[where_clause("id = ?")]                 // Query condition
pub struct MyEntity {
    pub id: i64,                          // Field used in the condition
    pub field1: String,                   // Fields to retrieve
    pub field2: i32,
}

§Example Usage

use rusqlite::{Connection, Result};
use parsql_macros::{Queryable, FromRow, SqlParams};
use parsql_sqlite::fetch;

fn main() -> Result<()> {
    // Create database connection
    let conn = Connection::open("test.db")?;
    conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)", [])?;
    conn.execute("INSERT INTO users (id, name, email) VALUES (1, 'John', 'john@example.com')", [])?;

    // Define a query
    #[derive(Queryable, FromRow, SqlParams)]
    #[table("users")]
    #[where_clause("id = ?")]
    pub struct GetUser {
        pub id: i64,
        pub name: String,
        pub email: String,
    }

    // Create query parameters (get user with ID 1)
    let get_query = GetUser {
        id: 1,
        name: String::new(),
        email: String::new(),
    };

    // Execute query
    let user = fetch(&conn, &get_query)?;
    println!("User: {:?}", user);
    Ok(())
}