Skip to main content

haste_repository/pg/
mod.rs

1use haste_fhir_model::r4::generated::resources::Resource;
2use haste_fhir_operation_error::derive::OperationOutcomeError;
3use haste_jwt::VersionId;
4use moka::future::Cache;
5use sqlx::Postgres;
6use std::sync::Arc;
7use tokio::sync::Mutex;
8
9use crate::Repository;
10
11pub use pending::PendingRows;
12
13mod failed_indexing;
14mod migrate;
15mod models;
16mod pending;
17mod rate_limit;
18mod sequence;
19mod transaction;
20
21#[derive(OperationOutcomeError, Debug)]
22pub enum StoreError {
23    #[error(code = "duplicate", diagnostic = "Resource already exists.")]
24    Duplicate,
25    #[error(code = "not-found", diagnostic = "Resource not found.")]
26    NotFound,
27    #[error(code = "invalid", diagnostic = "SQL Error occured.")]
28    SQLXError(#[from] sqlx::Error),
29    #[error(code = "exception", diagnostic = "Failed to create transaction.")]
30    TransactionError,
31    #[error(code = "invalid", diagnostic = "Cannot commit non transaction.")]
32    NotTransaction,
33    #[error(code = "invalid", diagnostic = "Failed to commit the transaction.")]
34    FailedCommitTransaction,
35    #[error(code = "exception", diagnostic = "Failed to hash password.")]
36    PasswordHashError(argon2::password_hash::Error),
37    #[error(
38        code = "exception",
39        diagnostic = "Failed to deserialize resource: '{arg0}'"
40    )]
41    DeserializeError(String),
42}
43
44/// Connection types supported by the repository traits.
45#[derive(Debug, Clone)]
46pub enum PGConnection {
47    Pool(sqlx::Pool<Postgres>, Cache<VersionId, Resource>),
48    Transaction(
49        Arc<Mutex<sqlx::Transaction<'static, Postgres>>>,
50        Cache<VersionId, Resource>,
51        PendingRows,
52    ),
53}
54
55static TOTAL_CACHE_SIZE: u64 = 1000 * 10;
56
57impl PGConnection {
58    #[must_use]
59    pub fn pool(pool: sqlx::Pool<Postgres>) -> Self {
60        PGConnection::Pool(pool, Cache::new(TOTAL_CACHE_SIZE))
61    }
62
63    #[must_use]
64    pub fn cache(&self) -> &Cache<VersionId, Resource> {
65        match self {
66            PGConnection::Pool(_, cache) | PGConnection::Transaction(_, cache, _) => cache,
67        }
68    }
69}
70
71impl Repository for PGConnection {}