Skip to main content

rex_db/models/
tx_methods.rs

1use diesel::prelude::*;
2use diesel::result::Error;
3
4use crate::ConnCache;
5use crate::schema::tx_methods;
6
7#[derive(Clone, Debug, Queryable, Insertable, Selectable)]
8pub struct TxMethod {
9    pub id: i32,
10    pub name: String,
11    pub position: i32,
12}
13
14#[derive(Insertable)]
15#[diesel(table_name = tx_methods)]
16pub struct NewTxMethod<'a> {
17    name: &'a str,
18    position: i32,
19}
20
21impl NewTxMethod<'_> {
22    #[must_use]
23    pub fn new(name: &str, position: i32) -> NewTxMethod<'_> {
24        NewTxMethod { name, position }
25    }
26
27    pub fn insert(self, db_conn: &mut impl ConnCache) -> Result<TxMethod, Error> {
28        use crate::schema::tx_methods::dsl::tx_methods;
29
30        diesel::insert_into(tx_methods)
31            .values(self)
32            .returning(TxMethod::as_returning())
33            .get_result(db_conn.conn())
34    }
35}
36
37impl TxMethod {
38    pub fn get_all(db_conn: &mut impl ConnCache) -> Result<Vec<TxMethod>, Error> {
39        use crate::schema::tx_methods::dsl::tx_methods;
40
41        tx_methods
42            .select(TxMethod::as_select())
43            .load(db_conn.conn())
44    }
45
46    pub fn get_last_position(db_conn: &mut impl ConnCache) -> Result<i32, Error> {
47        use crate::schema::tx_methods::dsl::{position, tx_methods};
48
49        tx_methods
50            .select(position)
51            .order(position.desc())
52            .first(db_conn.conn())
53            .optional()
54            .map(|opt| opt.unwrap_or(0))
55    }
56
57    pub fn get_by_name(db_conn: &mut impl ConnCache, name: &str) -> Result<TxMethod, Error> {
58        use crate::schema::tx_methods::dsl::{name as tx_method_name, tx_methods};
59
60        tx_methods
61            .filter(tx_method_name.eq(name))
62            .first(db_conn.conn())
63    }
64
65    pub fn rename(
66        t_id: i32,
67        new_name: &str,
68        db_conn: &mut impl ConnCache,
69    ) -> Result<TxMethod, Error> {
70        use crate::schema::tx_methods::dsl::{id, name, tx_methods};
71
72        diesel::update(tx_methods.filter(id.eq(t_id)))
73            .set(name.eq(new_name))
74            .returning(TxMethod::as_returning())
75            .get_result(db_conn.conn())
76    }
77
78    pub fn set_new_position(&self, db_conn: &mut impl ConnCache) -> Result<TxMethod, Error> {
79        use crate::schema::tx_methods::dsl::{id, position, tx_methods};
80
81        diesel::update(tx_methods.filter(id.eq(self.id)))
82            .set(position.eq(self.position))
83            .returning(TxMethod::as_returning())
84            .get_result(db_conn.conn())
85    }
86}