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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
#[macro_use]
extern crate log;
use std::collections::{BTreeMap, BTreeSet};
pub type Version = i64;
pub trait Migration {
fn version(&self) -> Version;
fn description(&self) -> &'static str;
}
#[derive(Debug)]
pub enum Direction {
Down,
Up,
}
#[derive(Debug)]
pub enum Error<E> {
Adapter(E),
Migration {
version: Version,
description: &'static str,
direction: Direction,
error: E,
}
}
#[macro_export]
macro_rules! migration {
($ty:ident, $version:expr, $description:expr) => {
impl $crate::Migration for $ty {
fn version(&self) -> $crate::Version { $version }
fn description(&self) -> &'static str { $description }
}
}
}
pub trait Adapter {
type MigrationType: Migration + ?Sized;
type Error;
fn current_version(&self) -> Result<Option<Version>, Self::Error>;
fn migrated_versions(&self) -> Result<BTreeSet<Version>, Self::Error>;
fn apply_migration(&self, migration: &Self::MigrationType) -> Result<(), Self::Error>;
fn revert_migration(&self, migration: &Self::MigrationType) -> Result<(), Self::Error>;
}
pub struct Migrator<T: Adapter> {
adapter: T,
migrations: BTreeMap<Version, Box<T::MigrationType>>
}
impl<T: Adapter> Migrator<T> {
pub fn new(adapter: T) -> Migrator<T> {
Migrator { adapter: adapter, migrations: BTreeMap::new() }
}
pub fn adapter(&self) -> &T {
&self.adapter
}
pub fn register(&mut self, migration: Box<T::MigrationType>) {
let version = migration.version();
if self.version_registered(version) {
warn!("Migration with version {:?} is already registered", version);
} else {
self.migrations.insert(version, migration);
}
}
pub fn version_registered(&self, version: Version) -> bool {
self.migrations.contains_key(&version)
}
pub fn registered_versions(&self) -> BTreeSet<Version> {
self.migrations.keys().cloned().collect()
}
pub fn first_version(&self) -> Option<Version> {
self.migrations.keys().next().map(|v| *v)
}
pub fn last_version(&self) -> Option<Version> {
self.migrations.keys().last().map(|v| *v)
}
pub fn current_version(&self) -> Result<Option<Version>, Error<T::Error>> {
match self.adapter.current_version() {
Ok(ver) => Ok(ver),
Err(err) => Err(Error::Adapter(err)),
}
}
pub fn migrated_versions(&self) -> Result<BTreeSet<Version>, Error<T::Error>> {
match self.adapter.migrated_versions() {
Ok(vers) => Ok(vers),
Err(err) => Err(Error::Adapter(err)),
}
}
pub fn down(&self, to: Option<Version>) -> Result<(), Error<T::Error>> {
let from = try!(self.current_version());
if from.is_none() {
return Ok(());
}
let migrated_versions = try!(self.migrated_versions());
let targets = self.migrations.iter()
.rev()
.filter(|&(&v, _)| within_range(v, to, from))
.filter(|&(v, _)| migrated_versions.contains(v));
for (&version, migration) in targets {
info!("Reverting migration {:?}: {}", version, migration.description());
if let Err(err) = self.adapter.revert_migration(migration) {
return Err(Error::Migration {
version: version,
description: migration.description(),
direction: Direction::Down,
error: err,
});
}
}
Ok(())
}
pub fn up(&self, to: Option<Version>) -> Result<(), Error<T::Error>> {
let migrated_versions = try!(self.migrated_versions());
let targets = self.migrations.iter()
.filter(|&(&v, _)| within_range(v, None, to))
.filter(|&(v, _)| !migrated_versions.contains(v));
for (&version, migration) in targets {
info!("Applying migration {:?}: {}", version, migration.description());
if let Err(err) = self.adapter.apply_migration(migration) {
return Err(Error::Migration {
version: version,
description: migration.description(),
direction: Direction::Up,
error: err,
});
}
}
Ok(())
}
}
fn within_range(version: Version, low: Option<Version>, high: Option<Version>) -> bool {
match (low, high) {
(None, None) => true,
(Some(low), None) => version > low,
(None, Some(high)) => version <= high,
(Some(low), Some(high)) => version > low && version <= high,
}
}
#[test]
fn test_within_range() {
assert!(within_range(0, None, None));
assert!(within_range(42, None, None));
assert!(within_range(100000, None, None));
assert!(!within_range(1, Some(2), Some(5)));
assert!(!within_range(2, Some(2), Some(5)));
assert!(within_range(3, Some(2), Some(5)));
assert!(within_range(5, Some(2), Some(5)));
assert!(!within_range(6, Some(2), Some(5)));
assert!(!within_range(0, Some(5), None));
assert!(!within_range(4, Some(5), None));
assert!(!within_range(5, Some(5), None));
assert!(within_range(6, Some(5), None));
assert!(within_range(60, Some(5), None));
assert!(within_range(0, None, Some(5)));
assert!(within_range(5, None, Some(5)));
assert!(!within_range(6, None, Some(5)));
}