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