Function select_all

Source
pub async fn select_all<T: SqlQuery + SqlParams, R, F>(
    pool: &Pool,
    entity: T,
    to_model: F,
) -> Result<Vec<R>, Error>
where F: Fn(&Row) -> R,
Expand description

§select_all

Deadpool bağlantı havuzunu kullanarak özel bir model dönüştürücü fonksiyon ile veritabanından birden fazla kayıt seçer.

§Parametreler

  • pool: Deadpool bağlantı havuzu
  • entity: Sorgu parametrelerini içeren veri nesnesi (SqlQuery ve SqlParams trait’lerini uygulamalıdır)
  • to_model: Satırı modele dönüştüren fonksiyon

§Dönüş Değeri

  • Result<Vec<R>, Error>: Başarılı olursa, dönüştürülen modelleri içeren bir vektör döndürür; başarısız olursa, Error döndürür

§Kullanım Örneği

use deadpool_postgres::{Config, Runtime, Pool};
use tokio_postgres::{NoTls, Error, Row};
use parsql::tokio_postgres::pool_crud_ops::select_all;
 
#[derive(Queryable, SqlParams)]
#[table("users")]
#[where_clause("state = $")]
pub struct UsersQuery {
    pub state: i16,
}

pub struct UserModel {
    pub id: i32,
    pub name: String,
    pub email: String,
    pub is_active: bool,
}

impl UsersQuery {
    pub fn new(state: i16) -> Self {
        Self { state }
    }
}

fn row_to_user(row: &Row) -> UserModel {
    UserModel {
        id: row.get("id"),
        name: row.get("name"),
        email: row.get("email"),
        is_active: row.get::<_, i16>("state") == 1,
    }
}
 
#[tokio::main]
async fn main() -> Result<(), Error> {
    let mut cfg = Config::new();
    cfg.host = Some("localhost".to_string());
    cfg.dbname = Some("test".to_string());
     
    let pool = cfg.create_pool(Some(Runtime::Tokio1), NoTls).unwrap();

    let query = UsersQuery::new(1);
    let users = select_all(&pool, query, row_to_user).await?;
     
    println!("Users: {:?}", users);
    Ok(())
}