1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
use crate::{DynError, Migration, PlanExecErrorKind};
use async_trait::async_trait;
use std::{
any::{self, Any},
collections::HashMap,
fmt,
};
#[async_trait]
pub trait MigrationCtxProvider: Send + 'static {
type Ctx: Send + 'static;
async fn create_in_commit_mode(self: Box<Self>) -> Result<Self::Ctx, DynError>;
async fn create_in_no_commit_mode(self: Box<Self>) -> Option<Result<Self::Ctx, DynError>>;
}
pub(crate) struct DynMigration {
pub(crate) name: String,
pub(crate) script: Box<dyn DynMigrationScript>,
}
impl DynMigration {
pub(crate) fn new(name: String, migration: impl Migration + 'static) -> DynMigration {
Self {
name,
script: Box::new(migration),
}
}
}
impl fmt::Debug for DynMigration {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self { name, script: _ } = self;
f.debug_struct("DynMigration")
.field("name", name)
.field("script", &"Box<dyn MigrationScript>")
.finish()
}
}
#[derive(Debug, Copy, Clone)]
pub enum MigrationRunMode {
Commit,
NoCommit,
}
pub(crate) enum MigrationDirection {
Up,
Down,
}
impl fmt::Display for MigrationDirection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MigrationDirection::Up => f.write_str("up"),
MigrationDirection::Down => f.write_str("down"),
}
}
}
pub(crate) struct DynMigrationScriptCtx<'reg> {
pub(crate) ctx_registry: &'reg mut CtxRegistry,
pub(crate) run_mode: MigrationRunMode,
pub(crate) direction: MigrationDirection,
}
#[async_trait]
pub(crate) trait DynMigrationScript {
async fn exec(&mut self, ctx: &mut DynMigrationScriptCtx<'_>) -> Result<(), PlanExecErrorKind>;
}
#[async_trait]
impl<Mig: Migration> DynMigrationScript for Mig {
async fn exec(&mut self, ctx: &mut DynMigrationScriptCtx<'_>) -> Result<(), PlanExecErrorKind> {
let migration_ctx = ctx.ctx_registry.get_mut(ctx.run_mode).await?;
let result = match ctx.direction {
MigrationDirection::Up => self.up(migration_ctx).await,
MigrationDirection::Down => self.down(migration_ctx).await,
};
result.map_err(PlanExecErrorKind::ExecMigrationScript)
}
}
enum CtxRegistryEntry<Ctx> {
Uninit(Option<Box<dyn MigrationCtxProvider<Ctx = Ctx>>>),
Init(Ctx),
CtxLacksNoCommitMode,
}
impl<Ctx> CtxRegistryEntry<Ctx> {
fn set_init(&mut self, ctx: Ctx) -> &mut Ctx {
*self = Self::Init(ctx);
match self {
Self::Init(it) => it,
_ => unreachable!("BUG: we've set the enum to `Init` variant!"),
}
}
}
pub(crate) struct CtxRegistry(HashMap<any::TypeId, Box<dyn any::Any + Send>>);
impl CtxRegistry {
pub(crate) fn new() -> Self {
Self(HashMap::new())
}
async fn get_mut<Ctx: Send + 'static>(
&mut self,
run_mode: MigrationRunMode,
) -> Result<&mut Ctx, PlanExecErrorKind> {
let entry: &mut CtxRegistryEntry<Ctx> = {
let type_id = std::any::TypeId::of::<CtxRegistryEntry<Ctx>>();
let val = self.0.get_mut(&type_id).unwrap_or_else(|| {
panic!(
"Tried to use migration context of type {}, but no provider for it is registered",
any::type_name::<Ctx>(),
)
});
val.downcast_mut()
.expect("BUG: invalid type id used in Box<dyn Any> map")
};
let provider = match entry {
CtxRegistryEntry::Init(ctx) => return Ok(ctx),
CtxRegistryEntry::CtxLacksNoCommitMode => {
return Err(PlanExecErrorKind::CtxLacksNoCommitMode)
}
CtxRegistryEntry::Uninit(provider) => provider,
};
let provider = provider.take().expect(
"BUG: this method should not be called after the provider \
has failed to create the context",
);
let result = match run_mode {
MigrationRunMode::Commit => provider.create_in_commit_mode().await,
MigrationRunMode::NoCommit => {
provider.create_in_no_commit_mode().await.ok_or_else(|| {
*entry = CtxRegistryEntry::CtxLacksNoCommitMode;
PlanExecErrorKind::CtxLacksNoCommitMode
})?
}
};
let ctx = result.map_err(|source| PlanExecErrorKind::CreateMigrationCtx {
source,
run_mode,
ctx_type: any::type_name::<Ctx>(),
})?;
Ok(entry.set_init(ctx))
}
pub(crate) fn insert<P: MigrationCtxProvider>(&mut self, provider: P) {
let val = CtxRegistryEntry::Uninit(Some(Box::new(provider)));
let prev_ctx = self.0.insert(val.type_id(), Box::new(val));
if prev_ctx.is_some() {
panic!(
"Tried to register a provider for migration context of type `{}` second time",
any::type_name::<P::Ctx>(),
)
}
}
}