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
11mod authorization_code;
12mod fhir;
13mod membership;
14mod migrate;
15mod project;
16mod rate_limit;
17mod scope;
18mod system;
19mod tenant;
20mod user;
21mod utilities;
22
23#[derive(OperationOutcomeError, Debug)]
24pub enum StoreError {
25    #[error(code = "duplicate", diagnostic = "Resource already exists.")]
26    Duplicate,
27    #[error(code = "not-found", diagnostic = "Resource not found.")]
28    NotFound,
29    #[error(code = "invalid", diagnostic = "SQL Error occured.")]
30    SQLXError(#[from] sqlx::Error),
31    #[error(code = "exception", diagnostic = "Failed to create transaction.")]
32    TransactionError,
33    #[error(code = "invalid", diagnostic = "Cannot commit non transaction.")]
34    NotTransaction,
35    #[error(code = "invalid", diagnostic = "Failed to commit the transaction.")]
36    FailedCommitTransaction,
37}
38
39/// Connection types supported by the repository traits.
40#[derive(Debug, Clone)]
41pub enum PGConnection {
42    Pool(sqlx::Pool<Postgres>, Cache<VersionId, Resource>),
43    Transaction(
44        Arc<Mutex<sqlx::Transaction<'static, Postgres>>>,
45        Cache<VersionId, Resource>,
46    ),
47}
48
49static TOTAL_CACHE_SIZE: u64 = 1000 * 10;
50
51impl PGConnection {
52    pub fn pool(pool: sqlx::Pool<Postgres>) -> Self {
53        PGConnection::Pool(pool, Cache::new(TOTAL_CACHE_SIZE))
54    }
55
56    pub fn cache(&self) -> &Cache<VersionId, Resource> {
57        match self {
58            PGConnection::Pool(_, cache) => cache,
59            PGConnection::Transaction(_, cache) => cache,
60        }
61    }
62}
63
64impl Repository for PGConnection {}