Skip to main content

waveless_commons/databases/
mod.rs

1// Waveless
2// Copyright (C) 2026 Oscar Alvarez Gonzalez
3
4use crate::*;
5
6use object::*;
7
8pub type DbConns = HashMap<DatabaseId, Arc<dyn AnyDatabaseConnection>>;
9
10/// The database's connections' pools manager.
11#[derive(Clone, Constructor, Debug)]
12pub struct DatabasesManager {
13    inner: HashMap<DatabaseId, Arc<dyn AnyDatabaseConnection>>,
14    primary_id: DatabaseId,
15}
16
17impl DatabasesManager {
18    pub fn acquire() -> &'static Self {
19        DATABASES_CONNS
20            .get()
21            .ok_or(eyre!("Databases connections should have been initialized."))
22            .unwrap()
23    }
24}
25
26#[async_trait]
27pub trait AnyDatabaseConnection: AnyExt {
28    async fn execute(&self, input: DatabaseInput) -> Result<DatabaseOutput>;
29}
30
31pub trait DatabaseConsumer {
32    fn databases(&self) -> CheapVec<DatabaseId>;
33
34    fn get_db_handle(&self) -> Result<DbConns> {
35        let db_ids = self.databases();
36
37        let _db_pool = DatabasesManager::acquire();
38
39        Ok(match db_ids.len() {
40            0 => HashMap::from([_db_pool.primary_db()?]),
41            _ => _db_pool.search_many(&db_ids)?,
42        })
43    }
44}
45
46#[derive(Debug)]
47pub enum DatabaseInput {
48    Query(CompactString),
49    QueryValues(CompactString, CheapVec<CompactString, 8>),
50    Bytes(Bytes),
51    Any(Box<dyn Any + Send + Sync>),
52}
53
54#[derive(Debug)]
55pub enum DatabaseOutput {
56    Bytes(Bytes),
57    Any(Box<dyn Any + Send + Sync>),
58}
59
60impl DatabasesManager {
61    /// Creates a new databases pools manager and loads it into the [`DATABASES_CONNS`] 's `OnceCell`.
62    #[instrument(skip_all)]
63    pub async fn load(databases: CheapVec<project::DatabaseConfig>) -> Result<()> {
64        if !databases.iter().any(|db| *db.is_primary()) {
65            bail!("There is no database set as primary.")
66        };
67
68        let mut primary_name: MaybeUninit<CompactString> = MaybeUninit::zeroed();
69
70        let mut inner = HashMap::new();
71
72        for db_config in databases {
73            info!("Creating {}'s pool.", db_config.id());
74
75            let (pool, _) = db_config
76                .connection()
77                .new_conn(
78                    db_config.id().to_owned(),
79                    *db_config.pool_min_size(),
80                    *db_config.pool_max_size(),
81                )
82                .await?;
83
84            if *db_config.is_primary() {
85                primary_name.write(db_config.id().to_owned());
86            }
87
88            inner.insert(db_config.id().to_owned(), pool);
89        }
90
91        let database_pools = DatabasesManager::new(inner, unsafe { primary_name.assume_init() });
92
93        DATABASES_CONNS.set(database_pools).unwrap();
94
95        Ok(())
96    }
97
98    /// Returns the primary database set for this project if any exists.
99    pub fn primary_db(&self) -> Result<(DatabaseId, Arc<dyn AnyDatabaseConnection>)> {
100        Ok((
101            self.primary_id.to_owned(),
102            self.inner
103                .get(&self.primary_id)
104                .wrap_err("No primary database has been defined for this project.")?
105                .to_owned(),
106        ))
107    }
108
109    /// Searches for the database given it's id.
110    pub fn search(&self, id: &DatabaseId) -> Result<Arc<dyn AnyDatabaseConnection>> {
111        self.inner
112            .get(id)
113            .ok_or(eyre!("Cannot find a database with the given id."))
114            .map(|val| val.to_owned())
115    }
116
117    /// Searches for the databases given their ids.
118    pub fn search_many(
119        &self,
120        ids: &CheapVec<DatabaseId>,
121    ) -> Result<HashMap<CompactString, Arc<dyn AnyDatabaseConnection>>> {
122        ids.as_ref()
123            .iter()
124            .map(|id| self.search(id).map(|db_conn| (id.to_owned(), db_conn)))
125            .collect::<Result<HashMap<_, _>>>()
126    }
127}
128
129impl Into<DbConns> for DatabasesManager {
130    fn into(self) -> DbConns {
131        self.inner
132            .iter()
133            .map(|(id, conn)| (id.to_owned(), conn.to_owned()))
134            .collect::<HashMap<_, _>>()
135    }
136}
137
138impl ObjectArtifact {
139    pub async fn check_checksums_in_object(&self, db_conns: DbConns) -> Result<()> {
140        for EndpointGeneratorChecksum { method, checksum } in self.databases_checksums() {
141            // Run the endpoint generator.
142            let (_, Some(current_checksum)) = method.generate(db_conns.to_owned()).await? else {
143                return Err(eyre!("Endpoint generator did not return any checksum.")
144                    .suggestion("Are you sure the generator is set to return a checksum?"));
145            };
146
147            if current_checksum != *checksum {
148                bail!(
149                    "The database schema has changed since the last build! Build the project again using the current schema."
150                );
151            } else {
152                info!("Checksum `{}` verified.", hex::encode(checksum));
153            }
154        }
155        Ok(())
156    }
157}