Skip to main content

appstruct_migrate/runner/
baseline.rs

1use super::{
2    DriftStatus, MigrationError, ProjectMigrations, catalog, connect_database, history, reconcile,
3    stamp_schema_checksum,
4};
5use crate::{DatabaseSchema, initial_migration, to_json};
6use appstruct_schema::sql::quote_ident;
7use postgres::GenericClient;
8use std::path::Path;
9
10#[derive(Clone, Debug, PartialEq, Eq)]
11pub struct BaselineStatus {
12    pub migration: Option<String>,
13    pub registered: bool,
14    pub drift: DriftStatus,
15}
16
17/// Compare a proposed application's structure against one schema using a read-only transaction.
18/// This does not validate or register migration history.
19///
20/// # Errors
21///
22/// Returns connection or catalog errors. No project files, schema objects or business rows change.
23pub fn inspect_schema_structure(
24    database_url: &str,
25    schema: &str,
26    expected: &DatabaseSchema,
27) -> Result<DriftStatus, MigrationError> {
28    let mut client = connect_database(database_url)?;
29    let mut transaction = client
30        .build_transaction()
31        .read_only(true)
32        .start()
33        .map_err(|error| database_error(&error))?;
34    transaction
35        .query_one(
36            "SELECT set_config('search_path', $1, true)",
37            &[&quote_ident(schema)],
38        )
39        .map_err(|error| database_error(&error))?;
40    let issues = catalog::detect(&mut transaction, expected)?;
41    Ok(if issues.is_empty() {
42        DriftStatus::Clean
43    } else {
44        DriftStatus::Detected(issues)
45    })
46}
47
48/// Preview adoption of an existing database without writing files or database history.
49///
50/// # Errors
51///
52/// Rejects seeds, empty schemas, existing unrelated migrations, invalid history, and database
53/// failures. Schema differences are returned in `drift`.
54pub fn inspect_baseline(
55    project: &Path,
56    database_url: &str,
57    expected: &DatabaseSchema,
58) -> Result<BaselineStatus, MigrationError> {
59    let migrations = validate_project(project, expected)?;
60    let mut client = connect_database(database_url)?;
61    let applied = history::load(&mut client)?;
62    let reconciliation = reconcile(&migrations.files, &applied)?;
63    let issues = catalog::detect(&mut client, expected)?;
64    Ok(BaselineStatus {
65        migration: migrations.files.first().map(|file| file.id.clone()),
66        registered: reconciliation.applied == 1,
67        drift: if issues.is_empty() {
68            DriftStatus::Clean
69        } else {
70            DriftStatus::Detected(issues)
71        },
72    })
73}
74
75/// Register one canonical initial migration without executing its SQL or changing business rows.
76///
77/// # Errors
78///
79/// Requires a nonempty schema without seeds, a matching canonical migration and snapshot, clean
80/// history, and matching live structure. Catalog validation and history registration run in one
81/// transaction while holding table locks and the migration runner's advisory lock.
82pub fn baseline_project(
83    project: &Path,
84    database_url: &str,
85    expected: &DatabaseSchema,
86) -> Result<BaselineStatus, MigrationError> {
87    let migrations = validate_project(project, expected)?;
88    let migration = migrations.files.first().ok_or_else(|| {
89        MigrationError::Project(
90            "create the initial baseline migration before registering it".to_owned(),
91        )
92    })?;
93    let mut client = connect_database(database_url)?;
94    history::lock(&mut client)?;
95    let mut transaction = client
96        .transaction()
97        .map_err(|error| database_error(&error))?;
98    let applied = history::load(&mut transaction)?;
99    reconcile(&migrations.files, &applied)?;
100    require_matching_schema(&mut transaction, expected)?;
101    // Block concurrent schema changes while allowing normal row reads and writes. Qualify names
102    // so a table in a different search_path schema cannot be locked instead.
103    let schema: String = transaction
104        .query_one("SELECT current_schema()", &[])
105        .and_then(|row| row.try_get(0))
106        .map_err(|error| database_error(&error))?;
107    let tables = expected
108        .tables
109        .iter()
110        .map(|table| format!("{}.{}", quote_ident(&schema), quote_ident(&table.name)))
111        .collect::<Vec<_>>()
112        .join(", ");
113    transaction
114        .batch_execute(&format!(
115            "SET LOCAL lock_timeout = '5s'; LOCK TABLE {tables} IN SHARE UPDATE EXCLUSIVE MODE"
116        ))
117        .map_err(|error| database_error(&error))?;
118    require_matching_schema(&mut transaction, expected)?;
119    if applied.is_empty() {
120        history::ensure_table(&mut transaction)?;
121        transaction
122            .execute(
123                r#"INSERT INTO "_appstruct_migrations"
124    (migration_id, checksum, state, finished_at)
125VALUES ($1, $2, 'applied', CURRENT_TIMESTAMP)"#,
126                &[&migration.id, &migration.checksum],
127            )
128            .map_err(|error| database_error(&error))?;
129    }
130    transaction
131        .commit()
132        .map_err(|error| database_error(&error))?;
133    Ok(BaselineStatus {
134        migration: Some(migration.id.clone()),
135        registered: true,
136        drift: DriftStatus::Clean,
137    })
138}
139
140fn validate_project(
141    project: &Path,
142    expected: &DatabaseSchema,
143) -> Result<ProjectMigrations, MigrationError> {
144    if expected.tables.is_empty() || !expected.seeds.is_empty() {
145        return Err(MigrationError::Project(
146            "baseline requires a nonempty schema without seeds; handle seed data explicitly after adoption".to_owned(),
147        ));
148    }
149    let migrations = ProjectMigrations::load(project)?;
150    if migrations.files.is_empty() {
151        if project.join(".appstruct/schema.snapshot.json").exists() {
152            return Err(MigrationError::Project(
153                "baseline cannot replace an existing snapshot".to_owned(),
154            ));
155        }
156        return Ok(migrations);
157    }
158    let snapshot = to_json(expected).map_err(|error| MigrationError::Project(error.to_string()))?;
159    let canonical = stamp_schema_checksum(&initial_migration(expected), &snapshot);
160    if migrations.files.len() != 1 || migrations.files[0].sql != canonical {
161        return Err(MigrationError::Project(
162            "baseline accepts only one unchanged canonical initial migration matching the current Spec; it cannot skip arbitrary SQL or existing migration chains".to_owned(),
163        ));
164    }
165    Ok(migrations)
166}
167
168fn require_matching_schema(
169    client: &mut impl GenericClient,
170    expected: &DatabaseSchema,
171) -> Result<(), MigrationError> {
172    let issues = catalog::detect(client, expected)?;
173    if issues.is_empty() {
174        Ok(())
175    } else {
176        Err(MigrationError::Integrity(format!(
177            "database does not match the baseline: {}",
178            issues.join("; ")
179        )))
180    }
181}
182
183fn database_error(error: &postgres::Error) -> MigrationError {
184    MigrationError::Database(format!(
185        "cannot register migration baseline: {}",
186        super::database_message(error)
187    ))
188}