sqlx_ledger/journal/
repo.rs

1use sqlx::{Pool, Postgres, Transaction};
2use tracing::instrument;
3
4use super::entity::*;
5use crate::{error::*, primitives::*};
6
7/// Repository for working with `Journal` entities.
8#[derive(Debug, Clone)]
9pub struct Journals {
10    pool: Pool<Postgres>,
11}
12
13impl Journals {
14    pub fn new(pool: &Pool<Postgres>) -> Self {
15        Self { pool: pool.clone() }
16    }
17
18    pub async fn create(&self, new_journal: NewJournal) -> Result<JournalId, SqlxLedgerError> {
19        let mut tx = self.pool.begin().await?;
20        let res = self.create_in_tx(&mut tx, new_journal).await?;
21        tx.commit().await?;
22        Ok(res)
23    }
24
25    #[instrument(name = "sqlx_ledger.journals.create", skip(self, tx))]
26    pub async fn create_in_tx<'a>(
27        &self,
28        tx: &mut Transaction<'a, Postgres>,
29        new_journal: NewJournal,
30    ) -> Result<JournalId, SqlxLedgerError> {
31        let NewJournal {
32            id,
33            name,
34            description,
35            status,
36        } = new_journal;
37        let record = sqlx::query!(
38            r#"INSERT INTO sqlx_ledger_journals (id, name, description, status)
39            VALUES ($1, $2, $3, $4)
40            RETURNING id, version, created_at"#,
41            id as JournalId,
42            name,
43            description,
44            status as Status,
45        )
46        .fetch_one(&mut **tx)
47        .await?;
48        Ok(JournalId::from(record.id))
49    }
50}