haste_migrations/repository/
mod.rs1use 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
22pub struct Context {
25 pub config: Arc<ServerConfig>,
27 pub secret_provider: Arc<dyn SecretsProvider + Send + Sync>,
29 pub tenant_keys: Arc<TenantKeys<PGConnection>>,
31}
32
33impl Context {
34 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#[allow(clippy::unreadable_literal)] const 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#[must_use]
76pub fn migrator() -> Migrator {
77 sqlx::migrate!("./sql/repository")
78}
79
80pub 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 #[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}