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;
11pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
13
14#[derive(Debug, Error)]
16pub enum StoreError {
17 #[error("migration store load failed: {message}")]
19 Load { id: Option<String>, message: String },
20 #[error("migration store save failed for '{id}': {message}")]
22 Save { id: String, message: String },
23 #[error("migration already exists: {id}")]
25 Conflict { id: String },
26 #[error("invalid stored migration: {message}")]
28 InvalidMigration { message: String },
29 #[error("migration store unavailable: {message}")]
31 Unavailable { message: String },
32}
33
34impl StoreError {
35 pub fn unavailable(message: impl Into<String>) -> Self {
37 Self::Unavailable {
38 message: message.into(),
39 }
40 }
41}
42
43#[derive(Debug, Error)]
45pub enum TrackingError {
46 #[error("tracking installation failed: {message}")]
48 Install { message: String },
49 #[error("tracking read failed: {message}")]
51 Read { message: String },
52 #[error("tracking record failed for '{id}': {message}")]
54 Record { id: String, message: String },
55 #[error("tracking removal failed for '{id}': {message}")]
57 Unrecord { id: String, message: String },
58 #[error("tracking store unavailable: {message}")]
60 Unavailable { message: String },
61}
62
63impl TrackingError {
64 pub fn unavailable(message: impl Into<String>) -> Self {
66 Self::Unavailable {
67 message: message.into(),
68 }
69 }
70}
71
72#[derive(Debug, Error)]
74pub enum ExecutorError {
75 #[error("connection failed: {0}")]
77 Connect(String),
78 #[error("prepare failed: {0}")]
80 Prepare(String),
81 #[error("prepare failed: {0}")]
83 PrepareDatabase(DatabaseFailure),
84 #[error("query failed: {0}")]
86 Fetch(String),
87 #[error("execute failed: {0}")]
89 Execute(String),
90 #[error("execute failed: {0}")]
92 ExecuteDatabase(DatabaseFailure),
93 #[error("transaction failed: {0}")]
95 Transaction(String),
96 #[error("migration lock failed: {0}")]
98 Lock(String),
99 #[error("unsupported executor capability: {0}")]
101 Unsupported(String),
102}
103
104impl ExecutorError {
105 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
114pub trait MigrationStore: Send + Sync {
116 fn load_all<'a>(&'a self) -> BoxFuture<'a, Result<Vec<Migration>, StoreError>>;
118
119 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
166pub trait TrackingStore: Send + Sync {
168 fn install<'a>(
170 &'a self,
171 dialect: Dialect,
172 executor: &'a mut dyn Executor,
173 ) -> BoxFuture<'a, Result<(), TrackingError>>;
174
175 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 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 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
199pub trait Executor: Send {
201 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 fn execute<'a>(&'a mut self, sql: &'a str) -> BoxFuture<'a, Result<(), ExecutorError>>;
212
213 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 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 fn begin<'a>(&'a mut self) -> BoxFuture<'a, Result<(), ExecutorError>>;
239
240 fn commit<'a>(&'a mut self) -> BoxFuture<'a, Result<(), ExecutorError>>;
242
243 fn rollback<'a>(&'a mut self) -> BoxFuture<'a, Result<(), ExecutorError>>;
245
246 fn acquire_lock<'a>(&'a mut self) -> BoxFuture<'a, Result<(), ExecutorError>> {
248 Box::pin(async { Ok(()) })
249 }
250
251 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
304pub const TRACKING_TABLE: &str = "gaman_migrations";
306
307#[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}