summaryrefslogtreecommitdiff
path: root/schist_core/schist_queries/src/accounts.rs
blob: 7b9b834a048796d2b6df32a9992c6a9ce4bd33d9 (plain)
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
use anyhow::{Context, Result};
use diesel::{QueryDsl, RunQueryDsl, SelectableHelper, SqliteConnection};
use schist_models::Account;
use schist_schema::schema::accounts::dsl::accounts as accounts_table;

pub fn delete_all_accounts(connection: &mut SqliteConnection) -> Result<usize> {
    let num_rows_deleted = diesel::delete(accounts_table)
        .execute(connection)
        .with_context(|| "failed to delete all accounts")?;
    Ok(num_rows_deleted)
}

pub fn get_all_accounts(connection: &mut SqliteConnection) -> Result<Vec<Account>> {
    let all_accounts = accounts_table
        .select(Account::as_select())
        .load(connection)
        .with_context(|| "failed to get all accounts")?;
    Ok(all_accounts)
}

pub fn insert_accounts(accounts: &[Account], connection: &mut SqliteConnection) -> Result<usize> {
    let num_accounts_inserted = diesel::insert_into(accounts_table)
        .values(accounts)
        .execute(connection)
        .with_context(|| insert_err_msg(accounts))?;
    Ok(num_accounts_inserted)
}

fn insert_err_msg(accounts: &[Account]) -> String {
    format!(
        "failed to insert accounts: [{}]",
        accounts
            .iter()
            .map(|a| format!("\"{}\": \"{}\"", a.id, a.name))
            .collect::<Vec<String>>()
            .join(", ")
    )
}