Skip to main content

gaman_core/migration_engine/
catalog.rs

1use serde::{Deserialize, Serialize};
2use thiserror::Error;
3
4use super::adapters::{BoxFuture, ExecutorError, MigrationStore, StoreError, TrackingError};
5use super::engine::graph_from;
6use super::execution_diagnostic::StatementDiagnostic;
7use crate::clarifier::Clarification;
8use crate::graphs::{GraphError, MigrationGraph};
9use crate::migrations::Migration;
10use crate::offline_planner::OfflineError;
11use crate::sql_plan::SqlPlanError;
12/// Canonical migration content for offline presentation.
13#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct MigrationArtifact {
15    /// Migration identifier in graph order.
16    pub id: String,
17    /// Canonical YAML representation.
18    pub content: String,
19}
20
21/// Counts forward and backward migration movement.
22#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
23pub struct MigrationMovement {
24    /// Applied migrations.
25    pub applied: usize,
26    /// Reverted migrations.
27    pub reverted: usize,
28}
29
30/// Errors returned by [`MigrationEngine`].
31#[derive(Debug, Error)]
32pub enum EngineError {
33    /// Migration storage failed.
34    #[error(transparent)]
35    Store(#[from] StoreError),
36    /// Tracking storage failed.
37    #[error(transparent)]
38    Tracking(#[from] TrackingError),
39    /// SQL execution failed.
40    #[error(transparent)]
41    Executor(#[from] ExecutorError),
42    /// One rendered migration statement was rejected by the target database.
43    #[error("migration '{migration}' {direction} statement {statement_ordinal} failed: {source}")]
44    MigrationExecution {
45        /// Migration whose rendered SQL failed.
46        migration: String,
47        /// Whether Gaman was applying or rolling back that migration.
48        direction: &'static str,
49        /// One-based statement ordinal within the migration direction.
50        statement_ordinal: usize,
51        /// Bounded statement identity and optional database-provided location.
52        statement: Box<StatementDiagnostic>,
53        /// Database failure returned by the active executor.
54        #[source]
55        source: Box<ExecutorError>,
56    },
57    /// Migration graph construction failed.
58    #[error(transparent)]
59    Graph(#[from] GraphError),
60    /// Offline planning failed.
61    #[error(transparent)]
62    Offline(#[from] OfflineError),
63    /// SQL rendering failed.
64    #[error(transparent)]
65    SqlPlan(#[from] SqlPlanError),
66    /// User decisions are required before migration generation can continue.
67    #[error("migration generation needs clarification input")]
68    NeedsInput(Vec<Clarification>),
69    /// The requested operation cannot be completed from current migration state.
70    #[error("migration engine configuration error: {0}")]
71    Config(String),
72}
73
74/// Immutable, validated migration history observed by one lifecycle command.
75pub struct MigrationCatalog {
76    migrations: Vec<Migration>,
77    graph: MigrationGraph,
78    ordered: Vec<String>,
79}
80
81/// Command-scoped migration storage backed by an immutable catalog snapshot.
82pub(crate) struct CatalogMigrationStore<'a, M> {
83    pub(super) catalog: &'a MigrationCatalog,
84    pub(super) writer: &'a M,
85}
86
87impl<M> MigrationStore for CatalogMigrationStore<'_, M>
88where
89    M: MigrationStore,
90{
91    fn load_all<'a>(&'a self) -> BoxFuture<'a, Result<Vec<Migration>, StoreError>> {
92        Box::pin(async move { Ok(self.catalog.migrations.clone()) })
93    }
94
95    fn save<'a>(&'a self, migration: &'a Migration) -> BoxFuture<'a, Result<(), StoreError>> {
96        self.writer.save(migration)
97    }
98}
99
100impl MigrationCatalog {
101    /// Builds and validates a deterministic snapshot from caller-provided migrations.
102    pub fn new(migrations: Vec<Migration>) -> Result<Self, EngineError> {
103        let (graph, ordered) = graph_from(&migrations)?;
104        Ok(Self {
105            migrations,
106            graph,
107            ordered,
108        })
109    }
110
111    /// Returns migrations in their loaded storage representation.
112    pub fn migrations(&self) -> &[Migration] {
113        &self.migrations
114    }
115
116    /// Returns deterministic dependency order for the snapshot.
117    pub fn ordered_ids(&self) -> &[String] {
118        &self.ordered
119    }
120
121    /// Resolves an exact migration identifier or unique prefix within this snapshot.
122    pub fn resolve_id(&self, input: &str) -> Result<String, EngineError> {
123        Ok(self.graph.resolve_id(input)?)
124    }
125}