Skip to main content

06_complex/
06-complex.rs

1mod employee {
2    #[derive(Debug, elephantry::Entity)]
3    #[elephantry(model = "Model", structure = "Structure", relation = "employee")]
4    pub struct Entity {
5        #[elephantry(pk)]
6        pub employee_id: i32,
7        pub first_name: String,
8        pub last_name: String,
9        pub birth_date: chrono::NaiveDate,
10        pub is_manager: bool,
11        pub day_salary: bigdecimal::BigDecimal,
12        pub department_id: i32,
13    }
14
15    impl Model {
16        pub fn managers_salary(&self) -> elephantry::Result<f32> {
17            let query = "select sum(day_salary) from employee where is_manager";
18
19            let result = self.connection.execute(query)?.get(0).get("sum");
20
21            Ok(result)
22        }
23    }
24}
25
26fn main() -> elephantry::Result {
27    env_logger::init();
28
29    let database_url =
30        std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://localhost".to_string());
31    let elephantry = elephantry::Pool::new(&database_url)?;
32    elephantry.execute(include_str!("structure.sql"))?;
33
34    let model = elephantry.model::<employee::Model>();
35    let managers_salary = model.managers_salary()?;
36
37    dbg!(managers_salary);
38
39    Ok(())
40}