Skip to main content

gaman_core/migration_engine/
adapters.rs

1use std::collections::HashSet;
2use std::future::Future;
3use std::pin::Pin;
4
5use thiserror::Error;
6
7use crate::dialects::Dialect;
8use crate::migrations::Migration;
9
10use super::execution_diagnostic::DatabaseFailure;
11/// A boxed future that can be used by native hosts and single-threaded WASM adapters.
12pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
13
14/// Errors returned by a caller-owned migration store.
15#[derive(Debug, Error)]
16pub enum StoreError {
17    /// Loading migration history failed.
18    #[error("migration store load failed: {message}")]
19    Load { id: Option<String>, message: String },
20    /// Persisting a generated migration failed.
21    #[error("migration store save failed for '{id}': {message}")]
22    Save { id: String, message: String },
23    /// A migration already exists at the requested identity.
24    #[error("migration already exists: {id}")]
25    Conflict { id: String },
26    /// Stored migration content could not be decoded or validated.
27    #[error("invalid stored migration: {message}")]
28    InvalidMigration { message: String },
29    /// The backing migration store is unavailable.
30    #[error("migration store unavailable: {message}")]
31    Unavailable { message: String },
32}
33
34impl StoreError {
35    /// Creates an unavailable-store failure when a narrower category is not known.
36    pub fn unavailable(message: impl Into<String>) -> Self {
37        Self::Unavailable {
38            message: message.into(),
39        }
40    }
41}
42
43/// Errors returned by a caller-owned migration tracking store.
44#[derive(Debug, Error)]
45pub enum TrackingError {
46    /// Installing tracking storage failed.
47    #[error("tracking installation failed: {message}")]
48    Install { message: String },
49    /// Reading applied migration state failed.
50    #[error("tracking read failed: {message}")]
51    Read { message: String },
52    /// Recording one applied migration failed.
53    #[error("tracking record failed for '{id}': {message}")]
54    Record { id: String, message: String },
55    /// Removing one applied migration record failed.
56    #[error("tracking removal failed for '{id}': {message}")]
57    Unrecord { id: String, message: String },
58    /// The tracking backend is unavailable.
59    #[error("tracking store unavailable: {message}")]
60    Unavailable { message: String },
61}
62
63impl TrackingError {
64    /// Creates an unavailable-tracking failure when a narrower category is not known.
65    pub fn unavailable(message: impl Into<String>) -> Self {
66        Self::Unavailable {
67            message: message.into(),
68        }
69    }
70}
71
72/// Errors returned by a caller-owned SQL executor.
73#[derive(Debug, Error)]
74pub enum ExecutorError {
75    /// A target connection could not be established.
76    #[error("connection failed: {0}")]
77    Connect(String),
78    /// A SQL statement could not be prepared without execution.
79    #[error("prepare failed: {0}")]
80    Prepare(String),
81    /// A SQL statement could not be prepared and the database provided structured context.
82    #[error("prepare failed: {0}")]
83    PrepareDatabase(DatabaseFailure),
84    /// A query needed for migration tracking could not be executed.
85    #[error("query failed: {0}")]
86    Fetch(String),
87    /// A SQL statement could not be executed.
88    #[error("execute failed: {0}")]
89    Execute(String),
90    /// A SQL statement could not be executed and the database provided structured context.
91    #[error("execute failed: {0}")]
92    ExecuteDatabase(DatabaseFailure),
93    /// A transaction or migration lock operation failed.
94    #[error("transaction failed: {0}")]
95    Transaction(String),
96    /// Acquiring or releasing the migration lock failed.
97    #[error("migration lock failed: {0}")]
98    Lock(String),
99    /// The executor does not provide a required capability.
100    #[error("unsupported executor capability: {0}")]
101    Unsupported(String),
102}
103
104impl ExecutorError {
105    /// Returns stable database context when the executor received it directly from the driver.
106    pub(crate) fn database_failure(&self) -> Option<&DatabaseFailure> {
107        match self {
108            Self::PrepareDatabase(failure) | Self::ExecuteDatabase(failure) => Some(failure),
109            _ => None,
110        }
111    }
112}
113
114/// Loads and persists migration definitions without prescribing a storage medium.
115pub trait MigrationStore: Send + Sync {
116    /// Loads every migration visible to this host.
117    fn load_all<'a>(&'a self) -> BoxFuture<'a, Result<Vec<Migration>, StoreError>>;
118
119    /// Persists a newly generated migration atomically without replacing an existing identity.
120    ///
121    /// Implementations must not expose partial migration content. Concurrent saves for the same
122    /// identity must allow at most one writer to succeed and return [`StoreError::Conflict`] for
123    /// the others.
124    fn save<'a>(&'a self, migration: &'a Migration) -> BoxFuture<'a, Result<(), StoreError>>;
125}
126
127impl<T> TrackingStore for &T
128where
129    T: TrackingStore + ?Sized,
130{
131    fn install<'a>(
132        &'a self,
133        dialect: Dialect,
134        executor: &'a mut dyn Executor,
135    ) -> BoxFuture<'a, Result<(), TrackingError>> {
136        (**self).install(dialect, executor)
137    }
138
139    fn applied_ids<'a>(
140        &'a self,
141        dialect: Dialect,
142        executor: &'a mut dyn Executor,
143    ) -> BoxFuture<'a, Result<HashSet<String>, TrackingError>> {
144        (**self).applied_ids(dialect, executor)
145    }
146
147    fn record<'a>(
148        &'a self,
149        dialect: Dialect,
150        id: &'a str,
151        executor: &'a mut dyn Executor,
152    ) -> BoxFuture<'a, Result<(), TrackingError>> {
153        (**self).record(dialect, id, executor)
154    }
155
156    fn unrecord<'a>(
157        &'a self,
158        dialect: Dialect,
159        id: &'a str,
160        executor: &'a mut dyn Executor,
161    ) -> BoxFuture<'a, Result<(), TrackingError>> {
162        (**self).unrecord(dialect, id, executor)
163    }
164}
165
166/// Stores the applied migration IDs for a target environment.
167pub trait TrackingStore: Send + Sync {
168    /// Prepares the tracking backend before planning or applying migrations.
169    fn install<'a>(
170        &'a self,
171        dialect: Dialect,
172        executor: &'a mut dyn Executor,
173    ) -> BoxFuture<'a, Result<(), TrackingError>>;
174
175    /// Returns all applied migration IDs.
176    fn applied_ids<'a>(
177        &'a self,
178        dialect: Dialect,
179        executor: &'a mut dyn Executor,
180    ) -> BoxFuture<'a, Result<HashSet<String>, TrackingError>>;
181
182    /// Marks one migration as applied.
183    fn record<'a>(
184        &'a self,
185        dialect: Dialect,
186        id: &'a str,
187        executor: &'a mut dyn Executor,
188    ) -> BoxFuture<'a, Result<(), TrackingError>>;
189
190    /// Removes one migration from applied state.
191    fn unrecord<'a>(
192        &'a self,
193        dialect: Dialect,
194        id: &'a str,
195        executor: &'a mut dyn Executor,
196    ) -> BoxFuture<'a, Result<(), TrackingError>>;
197}
198
199/// Executes SQL and transactional migration boundaries for a caller-owned target.
200pub trait Executor: Send {
201    /// Prepares one SQL statement without executing it when the host supports preparation.
202    fn prepare<'a>(&'a mut self, _sql: &'a str) -> BoxFuture<'a, Result<(), ExecutorError>> {
203        Box::pin(async {
204            Err(ExecutorError::Prepare(
205                "statement preparation is not supported by this executor".to_string(),
206            ))
207        })
208    }
209
210    /// Executes one SQL statement.
211    fn execute<'a>(&'a mut self, sql: &'a str) -> BoxFuture<'a, Result<(), ExecutorError>>;
212
213    /// Executes one checked DML statement and returns its affected-row count.
214    fn execute_affected<'a>(
215        &'a mut self,
216        _sql: &'a str,
217    ) -> BoxFuture<'a, Result<u64, ExecutorError>> {
218        Box::pin(async {
219            Err(ExecutorError::Unsupported(
220                "affected-row execution is not supported by this executor".to_string(),
221            ))
222        })
223    }
224
225    /// Returns the first text column from each result row for tracking adapters.
226    fn fetch_strings<'a>(
227        &'a mut self,
228        _sql: &'a str,
229    ) -> BoxFuture<'a, Result<Vec<String>, ExecutorError>> {
230        Box::pin(async {
231            Err(ExecutorError::Fetch(
232                "querying is not supported by this executor".to_string(),
233            ))
234        })
235    }
236
237    /// Starts one atomic migration transaction.
238    fn begin<'a>(&'a mut self) -> BoxFuture<'a, Result<(), ExecutorError>>;
239
240    /// Commits one atomic migration transaction.
241    fn commit<'a>(&'a mut self) -> BoxFuture<'a, Result<(), ExecutorError>>;
242
243    /// Rolls back one atomic migration transaction.
244    fn rollback<'a>(&'a mut self) -> BoxFuture<'a, Result<(), ExecutorError>>;
245
246    /// Acquires an optional migration lock.
247    fn acquire_lock<'a>(&'a mut self) -> BoxFuture<'a, Result<(), ExecutorError>> {
248        Box::pin(async { Ok(()) })
249    }
250
251    /// Releases an optional migration lock.
252    fn release_lock<'a>(&'a mut self) -> BoxFuture<'a, Result<(), ExecutorError>> {
253        Box::pin(async { Ok(()) })
254    }
255}
256
257impl<T> Executor for &mut T
258where
259    T: Executor + ?Sized,
260{
261    fn prepare<'a>(&'a mut self, sql: &'a str) -> BoxFuture<'a, Result<(), ExecutorError>> {
262        (**self).prepare(sql)
263    }
264
265    fn execute<'a>(&'a mut self, sql: &'a str) -> BoxFuture<'a, Result<(), ExecutorError>> {
266        (**self).execute(sql)
267    }
268
269    fn execute_affected<'a>(
270        &'a mut self,
271        sql: &'a str,
272    ) -> BoxFuture<'a, Result<u64, ExecutorError>> {
273        (**self).execute_affected(sql)
274    }
275
276    fn fetch_strings<'a>(
277        &'a mut self,
278        sql: &'a str,
279    ) -> BoxFuture<'a, Result<Vec<String>, ExecutorError>> {
280        (**self).fetch_strings(sql)
281    }
282
283    fn begin<'a>(&'a mut self) -> BoxFuture<'a, Result<(), ExecutorError>> {
284        (**self).begin()
285    }
286
287    fn commit<'a>(&'a mut self) -> BoxFuture<'a, Result<(), ExecutorError>> {
288        (**self).commit()
289    }
290
291    fn rollback<'a>(&'a mut self) -> BoxFuture<'a, Result<(), ExecutorError>> {
292        (**self).rollback()
293    }
294
295    fn acquire_lock<'a>(&'a mut self) -> BoxFuture<'a, Result<(), ExecutorError>> {
296        (**self).acquire_lock()
297    }
298
299    fn release_lock<'a>(&'a mut self) -> BoxFuture<'a, Result<(), ExecutorError>> {
300        (**self).release_lock()
301    }
302}
303
304/// Name of the database table used by [`DatabaseTrackingStore`].
305pub const TRACKING_TABLE: &str = "gaman_migrations";
306
307/// Database-backed migration tracking implemented through the active executor.
308#[derive(Debug, Default, Clone, Copy)]
309pub struct DatabaseTrackingStore;
310
311impl TrackingStore for DatabaseTrackingStore {
312    fn install<'a>(
313        &'a self,
314        dialect: Dialect,
315        executor: &'a mut dyn Executor,
316    ) -> BoxFuture<'a, Result<(), TrackingError>> {
317        Box::pin(async move {
318            let statements = dialect
319                .tracking_install_sql(TRACKING_TABLE)
320                .ok_or_else(|| TrackingError::Install {
321                    message: format!(
322                        "{} does not provide tracking-table installation SQL",
323                        dialect.as_str()
324                    ),
325                })?;
326            for statement in statements {
327                executor
328                    .execute(&statement)
329                    .await
330                    .map_err(|error| TrackingError::Install {
331                        message: error.to_string(),
332                    })?;
333            }
334            Ok(())
335        })
336    }
337
338    fn applied_ids<'a>(
339        &'a self,
340        dialect: Dialect,
341        executor: &'a mut dyn Executor,
342    ) -> BoxFuture<'a, Result<HashSet<String>, TrackingError>> {
343        Box::pin(async move {
344            let sql =
345                dialect
346                    .tracking_list_sql(TRACKING_TABLE)
347                    .ok_or_else(|| TrackingError::Read {
348                        message: "dialect does not provide tracking read SQL".to_string(),
349                    })?;
350            executor
351                .fetch_strings(&sql)
352                .await
353                .map(|ids| ids.into_iter().collect())
354                .map_err(|error| TrackingError::Read {
355                    message: error.to_string(),
356                })
357        })
358    }
359
360    fn record<'a>(
361        &'a self,
362        dialect: Dialect,
363        id: &'a str,
364        executor: &'a mut dyn Executor,
365    ) -> BoxFuture<'a, Result<(), TrackingError>> {
366        Box::pin(async move {
367            let sql = dialect
368                .tracking_record_sql(TRACKING_TABLE, id)
369                .ok_or_else(|| TrackingError::Record {
370                    id: id.to_string(),
371                    message: "dialect does not provide tracking record SQL".to_string(),
372                })?;
373            executor
374                .execute(&sql)
375                .await
376                .map_err(|error| TrackingError::Record {
377                    id: id.to_string(),
378                    message: error.to_string(),
379                })
380        })
381    }
382
383    fn unrecord<'a>(
384        &'a self,
385        dialect: Dialect,
386        id: &'a str,
387        executor: &'a mut dyn Executor,
388    ) -> BoxFuture<'a, Result<(), TrackingError>> {
389        Box::pin(async move {
390            let sql = dialect
391                .tracking_unrecord_sql(TRACKING_TABLE, id)
392                .ok_or_else(|| TrackingError::Unrecord {
393                    id: id.to_string(),
394                    message: "dialect does not provide tracking removal SQL".to_string(),
395                })?;
396            executor
397                .execute(&sql)
398                .await
399                .map_err(|error| TrackingError::Unrecord {
400                    id: id.to_string(),
401                    message: error.to_string(),
402                })
403        })
404    }
405}