Skip to main content

appstruct_migrate/
runner.rs

1mod catalog;
2mod history;
3mod project;
4
5use crate::DatabaseSchema;
6use postgres::{Client, Config, NoTls, config::SslMode};
7use postgres_native_tls::MakeTlsConnector;
8use sha2::{Digest, Sha256};
9use std::fmt;
10use std::path::Path;
11
12use project::{MigrationFile, ProjectMigrations, reconcile};
13
14const SCHEMA_CHECKSUM_PREFIX: &str = "-- appstruct:schema-sha256=";
15const TRANSACTION_PREFIX: &str = "-- appstruct:transaction=";
16
17#[derive(Clone, Debug, PartialEq, Eq)]
18pub enum DriftStatus {
19    Clean,
20    Deferred,
21    Detected(Vec<String>),
22}
23
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub struct MigrationStatus {
26    pub applied: usize,
27    pub pending: usize,
28    pub drift: DriftStatus,
29}
30
31#[derive(Clone, Debug, PartialEq, Eq)]
32pub struct ApplyReport {
33    pub applied_now: usize,
34    pub total_applied: usize,
35    pub drift: DriftStatus,
36}
37
38#[derive(Clone, Debug, PartialEq, Eq)]
39pub enum MigrationError {
40    Project(String),
41    Database(String),
42    Integrity(String),
43}
44
45impl fmt::Display for MigrationError {
46    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
47        match self {
48            Self::Project(message) | Self::Database(message) | Self::Integrity(message) => {
49                formatter.write_str(message)
50            }
51        }
52    }
53}
54
55impl std::error::Error for MigrationError {}
56
57#[must_use]
58pub fn stamp_schema_checksum(sql: &str, snapshot: &str) -> String {
59    let marker = format!(
60        "{SCHEMA_CHECKSUM_PREFIX}{}\n",
61        checksum(snapshot.as_bytes())
62    );
63    sql.split_once('\n').map_or_else(
64        || format!("{sql}\n{marker}"),
65        |(first, rest)| format!("{first}\n{marker}{rest}"),
66    )
67}
68
69/// Inspect disk migrations, history, and database schema state.
70///
71/// # Errors
72///
73/// Returns an error for invalid project state, database failures, dirty history, or checksum
74/// mismatches.
75pub fn status_project(
76    project: &Path,
77    database_url: &str,
78) -> Result<MigrationStatus, MigrationError> {
79    let project = ProjectMigrations::load(project)?;
80    let mut client = connect_database(database_url)?;
81    let applied = history::load(&mut client)?;
82    let reconciliation = reconcile(&project.files, &applied)?;
83    let drift = if reconciliation.pending == 0 {
84        detect_drift(&mut client, &project.schema)?
85    } else {
86        DriftStatus::Deferred
87    };
88    Ok(MigrationStatus {
89        applied: reconciliation.applied,
90        pending: reconciliation.pending,
91        drift,
92    })
93}
94
95/// Apply every pending disk migration and verify the resulting PostgreSQL schema.
96///
97/// # Errors
98///
99/// Returns an error for invalid project state, database failures, dirty history, or checksum
100/// mismatches. Transaction-disabled failures remain recorded for manual recovery.
101pub fn apply_project(project: &Path, database_url: &str) -> Result<ApplyReport, MigrationError> {
102    let project = ProjectMigrations::load(project)?;
103    let mut client = connect_database(database_url)?;
104    history::lock(&mut client)?;
105    history::ensure_table(&mut client)?;
106    let applied = history::load(&mut client)?;
107    let reconciliation = reconcile(&project.files, &applied)?;
108    let pending_start = reconciliation.applied;
109    for migration in &project.files[pending_start..] {
110        history::apply(&mut client, migration)?;
111    }
112    let drift = detect_drift(&mut client, &project.schema)?;
113    Ok(ApplyReport {
114        applied_now: reconciliation.pending,
115        total_applied: project.files.len(),
116        drift,
117    })
118}
119
120/// Connect to PostgreSQL using the same TLS policy as migration commands.
121///
122/// # Errors
123///
124/// Returns an error when the URL is invalid, TLS cannot be initialized, or PostgreSQL rejects the
125/// connection.
126pub fn connect_database(database_url: &str) -> Result<Client, MigrationError> {
127    let config = database_url.parse::<Config>().map_err(|error| {
128        MigrationError::Database(format!(
129            "invalid PostgreSQL connection configuration: {error}"
130        ))
131    })?;
132    let result = if config.get_ssl_mode() == SslMode::Disable {
133        config.connect(NoTls)
134    } else {
135        let connector = native_tls::TlsConnector::builder()
136            .build()
137            .map_err(|error| {
138                MigrationError::Database(format!("cannot initialize PostgreSQL TLS: {error}"))
139            })?;
140        config.connect(MakeTlsConnector::new(connector))
141    };
142    result.map_err(|error| {
143        MigrationError::Database(format!(
144            "cannot connect to PostgreSQL: {}",
145            database_message(&error)
146        ))
147    })
148}
149
150fn database_message(error: &postgres::Error) -> String {
151    error.as_db_error().map_or_else(
152        || error.to_string(),
153        |database| database.message().to_owned(),
154    )
155}
156
157fn detect_drift(
158    client: &mut Client,
159    expected: &DatabaseSchema,
160) -> Result<DriftStatus, MigrationError> {
161    let issues = catalog::detect(client, expected)?;
162    if issues.is_empty() {
163        Ok(DriftStatus::Clean)
164    } else {
165        Ok(DriftStatus::Detected(issues))
166    }
167}
168
169fn checksum(content: &[u8]) -> String {
170    format!("{:x}", Sha256::digest(content))
171}
172
173#[cfg(test)]
174mod tests;