Skip to main content

cortex/
migrations.rs

1// Copyright 2015-2025 Deyan Ginev. See the LICENSE
2// file at the top-level directory of this distribution.
3//
4// Licensed under the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>.
5// This file may not be copied, modified, or distributed
6// except according to those terms.
7
8//! Embedded database migrations.
9//!
10//! The migrations under `migrations/` are baked into the binary at compile time, so `cortex init`
11//! (and any deployment) can self-migrate the database with **no `diesel_cli` on the host**.
12
13use diesel::pg::PgConnection;
14use diesel_migrations::{EmbeddedMigrations, MigrationHarness, embed_migrations};
15
16/// The set of migrations compiled into the binary (from the `migrations/` directory).
17pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
18
19/// Returns whether the database has any pending (un-applied) migrations.
20pub fn has_pending_migrations(connection: &mut PgConnection) -> bool {
21  connection.has_pending_migration(MIGRATIONS).unwrap_or(true)
22}
23
24/// Applies all pending migrations, returning the versions applied (empty when already current).
25pub fn run_pending_migrations(
26  connection: &mut PgConnection,
27) -> Result<Vec<String>, Box<dyn std::error::Error + Send + Sync>> {
28  let applied = connection.run_pending_migrations(MIGRATIONS)?;
29  Ok(applied.iter().map(|version| version.to_string()).collect())
30}