1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
mod employee {
    #[derive(Debug, elephantry::Entity)]
    #[elephantry(model = "Model", structure = "Structure", relation = "employee")]
    pub struct Entity {
        #[elephantry(pk)]
        pub employee_id: Option<i32>,
        pub first_name: String,
        pub last_name: String,
        pub birth_date: chrono::NaiveDate,
        pub is_manager: bool,
        pub day_salary: bigdecimal::BigDecimal,
        pub department_id: i32,
    }

    impl Model {
        pub fn new_employee(
            &self,
            employee: &Entity,
            department: &str,
        ) -> elephantry::Result<Entity> {
            let transaction = self.connection.transaction();

            transaction.start()?;
            transaction.set_deferrable(
                Some(vec!["employee_department_id_fkey"]),
                elephantry::transaction::Constraints::Deferred,
            )?;

            let mut employee = self.connection.insert_one::<Self>(employee)?;
            let department = self
                .connection
                .find_where::<super::department::Model>("name = $*", &[&department], None)?
                .nth(0)
                .unwrap();
            employee.department_id = department.department_id;

            let employee = self
                .connection
                .update_one::<Self>(
                    &elephantry::pk! { employee_id => employee.employee_id },
                    &employee,
                )?
                .unwrap();

            transaction.commit()?;

            Ok(employee)
        }
    }
}

mod department {
    #[derive(Debug, elephantry::Entity)]
    #[elephantry(model = "Model", structure = "Structure", relation = "department")]
    pub struct Entity {
        #[elephantry(pk)]
        pub department_id: i32,
        pub name: String,
        pub parent_id: Option<i32>,
    }
}

fn main() -> elephantry::Result {
    env_logger::init();

    let database_url =
        std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://localhost".to_string());
    let elephantry = elephantry::Pool::new(&database_url)?;
    elephantry.execute(include_str!("structure.sql"))?;

    let employee = elephantry.model::<employee::Model>().new_employee(
        &employee::Entity {
            employee_id: None,
            first_name: "First name".to_string(),
            last_name: "Last name".to_string(),
            birth_date: chrono::NaiveDate::from_ymd_opt(1990, 1, 1).unwrap(),
            is_manager: true,
            day_salary: 1_000.into(),
            department_id: -1,
        },
        "Direction",
    )?;

    dbg!(employee);

    Ok(())
}