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
use sqlx::SqliteConnection;

/// Account that transactions are related to.
pub struct Account {
    id: i64,
    name: String,
}

impl Account {
    /// Create a new [Account] and add it to the database.
    pub async fn new(name: &str, conn: &mut SqliteConnection) -> Self {
        let account: Self = sqlx::query_as!(
            Self,
            "
            INSERT INTO accounts ( name )
            VALUES ( ?1 )
            RETURNING *
            ",
            name
        )
        .fetch_one(conn)
        .await
        .unwrap();

        account
    }

    /// Get the [Account]'s id.
    pub fn id(&self) -> i64 {
        self.id
    }

    /// Get the [Account]'s name.
    pub fn name(&self) -> &str {
        self.name.as_ref()
    }

    pub async fn get_all(conn: &mut SqliteConnection) -> Vec<Self> {
        let accounts: Vec<Self> = sqlx::query_as!(
            Self,
            "
            SELECT * FROM accounts
            ",
        )
        .fetch_all(conn)
        .await
        .unwrap();

        accounts
    }
}

#[cfg(test)]
mod tests {
    use crate::test_utilities::test_database;

    use super::*;

    #[tokio::test]
    async fn test_new_account() {
        let mut conn = test_database().await;

        let account = Account::new("Expenses", &mut conn).await;

        assert_eq!(account.name(), "Expenses");
        assert_eq!(account.id(), 1);
    }

    #[tokio::test]
    async fn test_get_all_accounts() {
        let mut conn = test_database().await;

        Account::new("Expenses", &mut conn).await;
        Account::new("Assets", &mut conn).await;

        let accounts = Account::get_all(&mut conn).await;

        assert_eq!(accounts.len(), 2);
        assert_eq!(accounts[0].name(), "Expenses");
        assert_eq!(accounts[0].id(), 1);
        assert_eq!(accounts[1].name(), "Assets");
        assert_eq!(accounts[1].id(), 2);
    }
}