Skip to main content

haste_migrations/
search.rs

1//! The PG search index's migrations: the `.sql` files of `sql/search`.
2//!
3//! `haste-fhir-search` decides which table and column hold each search
4//! parameter, so it is what knows whether a database has them all. [`migrate`]
5//! applies the migrations and then has it check; [`pending_migration`] has it
6//! write the migration creating what the database lacks, which `generate
7//! search-migration` saves in `sql/search`. A change to an existing object (a
8//! column's type, an index's definition) is written by hand: drop it, then
9//! create it.
10
11use haste_fhir_operation_error::OperationOutcomeError;
12use haste_fhir_search::pg_search::migration as schema;
13use sqlx::{PgPool, migrate::Migrator};
14
15/// Records which search migrations ran. Not sqlx's default table, which the
16/// repository's migrations use: the search index may share their database.
17const MIGRATIONS_TABLE: &str = "_sqlx_search_migrations";
18
19fn migrator() -> Migrator {
20    let mut migrator = sqlx::migrate!("./sql/search");
21    migrator.dangerous_set_table_name(MIGRATIONS_TABLE);
22    migrator
23}
24
25/// Applies the search migrations that the database of `pool` lacks. None has
26/// a step.
27async fn apply(pool: &PgPool) -> Result<(), OperationOutcomeError> {
28    crate::run(migrator(), pool, &[], &()).await
29}
30
31/// Applies the search migrations that the database of `pool` lacks, then
32/// checks the database has everything the search schema needs.
33///
34/// # Errors
35///
36/// Returns an error if a migration fails (see [`crate::run`]), or if the
37/// database still lacks a table, column or index the schema needs: a missing
38/// column would otherwise surface as a failed write or search later on.
39pub async fn migrate(pool: &PgPool) -> Result<(), OperationOutcomeError> {
40    apply(pool).await?;
41    schema::check(pool).await?;
42
43    tracing::info!("PG search index tables migrated.");
44    Ok(())
45}
46
47/// Applies the search migrations that the database of `pool` lacks, then
48/// returns the migration creating what the search schema still needs, or
49/// `None` when the database lacks nothing.
50///
51/// # Errors
52///
53/// Returns an error if a migration fails (see [`crate::run`]) or the catalog
54/// cannot be read.
55pub async fn pending_migration(pool: &PgPool) -> Result<Option<String>, OperationOutcomeError> {
56    apply(pool).await?;
57    schema::pending_migration(pool).await
58}