Skip to main content

haste_migrations/repository/
mod.rs

1//! The repository's migrations: the `.sql` files of `sql/repository`, with
2//! the steps of those that have code.
3//!
4//! The step of a migration is a module of this one, named after the
5//! migration with an `m` in front, and is listed in `STEPS`.
6//! `m20261126130000_example_step` is an example.
7
8use std::sync::Arc;
9
10use haste_encryption::SecretsProvider;
11use haste_fhir_operation_error::OperationOutcomeError;
12use haste_repository::pg::PGConnection;
13use haste_server::{config::ServerConfig, services, tenant_keys::TenantKeys};
14use sqlx::{PgPool, migrate::Migrator};
15
16use crate::Step;
17
18mod m20261126130000_example_step;
19mod m20261127130000_copy_user_mfa_secrets;
20mod m20261202120000_copy_user_mfa_secrets_again;
21
22/// What the steps of the repository's migrations are given: the server's
23/// configuration and the keys it names.
24pub struct Context {
25    /// The server's configuration.
26    pub config: Arc<ServerConfig>,
27    /// Where the keys the configuration names are read from.
28    pub secret_provider: Arc<dyn SecretsProvider + Send + Sync>,
29    /// Encryption under each tenant's own key.
30    pub tenant_keys: Arc<TenantKeys<PGConnection>>,
31}
32
33impl Context {
34    /// What the steps are given for the server `config` describes, whose
35    /// repository is the database of `pool`: its keys, as the server itself
36    /// gets them.
37    ///
38    /// # Errors
39    ///
40    /// Returns an error if the configuration names a secret provider the
41    /// server does not read from.
42    pub fn new(config: Arc<ServerConfig>, pool: &PgPool) -> Result<Self, OperationOutcomeError> {
43        let secret_provider = services::secret_provider(&config)?;
44        let repository = Arc::new(PGConnection::pool(pool.clone()));
45        Ok(Self {
46            tenant_keys: services::tenant_keys(&config, &secret_provider, repository),
47            secret_provider,
48            config,
49        })
50    }
51}
52
53/// The steps of the repository's migrations.
54#[allow(clippy::unreadable_literal)] // A version as its file name has it.
55const STEPS: &[Step<Context>] = &[
56    Step {
57        version: 20261126130000,
58        run: m20261126130000_example_step::run,
59    },
60    Step {
61        version: 20261127130000,
62        run: m20261127130000_copy_user_mfa_secrets::run,
63    },
64    Step {
65        version: 20261202120000,
66        run: m20261202120000_copy_user_mfa_secrets_again::run,
67    },
68];
69
70/// The repository's migrations, which the build embeds.
71///
72/// [`migrate`] applies them with their steps. Applied by themselves, those
73/// with a step are recorded without its work, which is right for a new, empty
74/// database only.
75#[must_use]
76pub fn migrator() -> Migrator {
77    sqlx::migrate!("./sql/repository")
78}
79
80/// Applies the repository's migrations that the database of `pool` lacks,
81/// their steps given `context`.
82///
83/// # Errors
84///
85/// Returns an error if a migration or its step fails (see [`crate::run`]).
86pub async fn migrate(pool: &PgPool, context: &Context) -> Result<(), OperationOutcomeError> {
87    crate::run(migrator(), pool, STEPS, context).await
88}
89
90#[cfg(test)]
91mod tests {
92    use std::path::Path;
93
94    use super::{STEPS, migrator};
95
96    /// Every module of this folder but `mod.rs` is the step of the migration
97    /// it is named after, and is listed in [`STEPS`].
98    #[test]
99    fn each_step_is_named_after_its_migration_and_listed() {
100        let migrator = migrator();
101        let folder = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/repository");
102
103        let mut named: Vec<i64> = std::fs::read_dir(folder)
104            .unwrap()
105            .map(|entry| entry.unwrap().file_name().into_string().unwrap())
106            .filter(|file| file != "mod.rs")
107            .map(|file| {
108                let (version, name) = file
109                    .strip_prefix('m')
110                    .and_then(|file| file.strip_suffix(".rs"))
111                    .and_then(|file| file.split_once('_'))
112                    .unwrap_or_else(|| panic!("`{file}` is not named `m<version>_<name>.rs`"));
113                let version: i64 = version
114                    .parse()
115                    .unwrap_or_else(|_| panic!("`{file}` does not start with a version"));
116                assert!(
117                    migrator.iter().any(|migration| migration.version == version
118                        && migration.description == name.replace('_', " ")),
119                    "`{file}` is not named after a migration of the repository"
120                );
121                version
122            })
123            .collect();
124        named.sort_unstable();
125
126        let mut listed: Vec<i64> = STEPS.iter().map(|step| step.version).collect();
127        listed.sort_unstable();
128        assert_eq!(
129            listed, named,
130            "the steps listed are not those of the step modules"
131        );
132    }
133}