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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
use regex::Regex;
use siphasher::sip::SipHasher13;
use time::OffsetDateTime;
use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};
use crate::error::Kind;
use crate::{AsyncMigrate, Error, Migrate};
use std::fmt::Formatter;
pub fn file_match_re() -> Regex {
Regex::new(r"^([U|V])(\d+(?:\.\d+)?)__(\w+)").unwrap()
}
lazy_static::lazy_static! {
static ref RE: regex::Regex = file_match_re();
}
#[derive(Clone, PartialEq)]
pub enum Type {
Versioned,
Unversioned,
}
impl fmt::Display for Type {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let version_type = match self {
Type::Versioned => "V",
Type::Unversioned => "U",
};
write!(f, "{}", version_type)
}
}
impl fmt::Debug for Type {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let version_type = match self {
Type::Versioned => "Versioned",
Type::Unversioned => "Unversioned",
};
write!(f, "{}", version_type)
}
}
#[derive(Clone, Copy, Debug)]
pub enum Target {
Latest,
Version(u32),
Fake,
FakeVersion(u32),
}
#[derive(Clone, Debug)]
enum State {
Applied,
Unapplied,
}
#[derive(Clone, Debug)]
pub struct Migration {
state: State,
name: String,
checksum: u64,
version: i32,
prefix: Type,
sql: Option<String>,
applied_on: Option<OffsetDateTime>,
}
impl Migration {
pub fn unapplied(input_name: &str, sql: &str) -> Result<Migration, Error> {
let captures = RE
.captures(input_name)
.filter(|caps| caps.len() == 4)
.ok_or_else(|| Error::new(Kind::InvalidName, None))?;
let version: i32 = captures[2]
.parse()
.map_err(|_| Error::new(Kind::InvalidVersion, None))?;
let name: String = (&captures[3]).into();
let prefix = match &captures[1] {
"V" => Type::Versioned,
"U" => Type::Unversioned,
_ => unreachable!(),
};
let mut hasher = SipHasher13::new();
name.hash(&mut hasher);
version.hash(&mut hasher);
sql.hash(&mut hasher);
let checksum = hasher.finish();
Ok(Migration {
state: State::Unapplied,
name,
version,
prefix,
sql: Some(sql.into()),
applied_on: None,
checksum,
})
}
pub(crate) fn applied(
version: i32,
name: String,
applied_on: OffsetDateTime,
checksum: u64,
) -> Migration {
Migration {
state: State::Applied,
name,
checksum,
version,
prefix: Type::Versioned,
sql: None,
applied_on: Some(applied_on),
}
}
pub(crate) fn set_applied(&mut self) {
self.applied_on = Some(OffsetDateTime::now_utc());
self.state = State::Applied;
}
pub(crate) fn sql(&self) -> Option<&str> {
self.sql.as_deref()
}
pub fn version(&self) -> u32 {
self.version as u32
}
pub fn prefix(&self) -> &Type {
&self.prefix
}
pub fn name(&self) -> &str {
&self.name
}
pub fn applied_on(&self) -> Option<&OffsetDateTime> {
self.applied_on.as_ref()
}
pub fn checksum(&self) -> u64 {
self.checksum
}
}
impl fmt::Display for Migration {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "{}{}__{}", self.prefix, self.version, self.name)
}
}
impl Eq for Migration {}
impl PartialEq for Migration {
fn eq(&self, other: &Migration) -> bool {
self.version == other.version
&& self.name == other.name
&& self.checksum() == other.checksum()
}
}
impl Ord for Migration {
fn cmp(&self, other: &Migration) -> Ordering {
self.version.cmp(&other.version)
}
}
impl PartialOrd for Migration {
fn partial_cmp(&self, other: &Migration) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[derive(Clone, Debug)]
pub struct Report {
applied_migrations: Vec<Migration>,
}
impl Report {
pub(crate) fn new(applied_migrations: Vec<Migration>) -> Report {
Report { applied_migrations }
}
pub fn applied_migrations(&self) -> &Vec<Migration> {
&self.applied_migrations
}
}
pub struct Runner {
grouped: bool,
abort_divergent: bool,
abort_missing: bool,
migrations: Vec<Migration>,
target: Target,
}
impl Runner {
pub fn new(migrations: &[Migration]) -> Runner {
Runner {
grouped: false,
target: Target::Latest,
abort_divergent: true,
abort_missing: true,
migrations: migrations.to_vec(),
}
}
pub fn get_migrations(&self) -> &Vec<Migration> {
&self.migrations
}
pub fn set_target(self, target: Target) -> Runner {
Runner { target, ..self }
}
pub fn set_grouped(self, grouped: bool) -> Runner {
Runner { grouped, ..self }
}
pub fn set_abort_divergent(self, abort_divergent: bool) -> Runner {
Runner {
abort_divergent,
..self
}
}
pub fn set_abort_missing(self, abort_missing: bool) -> Runner {
Runner {
abort_missing,
..self
}
}
pub fn get_last_applied_migration<C>(&self, conn: &'_ mut C) -> Result<Option<Migration>, Error>
where
C: Migrate,
{
Migrate::get_last_applied_migration(conn)
}
pub async fn get_last_applied_migration_async<C>(
&self,
conn: &mut C,
) -> Result<Option<Migration>, Error>
where
C: AsyncMigrate + Send,
{
AsyncMigrate::get_last_applied_migration(conn).await
}
pub fn get_applied_migrations<C>(&self, conn: &'_ mut C) -> Result<Vec<Migration>, Error>
where
C: Migrate,
{
Migrate::get_applied_migrations(conn)
}
pub async fn get_applied_migrations_async<C>(
&self,
conn: &mut C,
) -> Result<Vec<Migration>, Error>
where
C: AsyncMigrate + Send,
{
AsyncMigrate::get_applied_migrations(conn).await
}
pub fn run<C>(&self, conn: &'_ mut C) -> Result<Report, Error>
where
C: Migrate,
{
Migrate::migrate(
conn,
&self.migrations,
self.abort_divergent,
self.abort_missing,
self.grouped,
self.target,
)
}
pub async fn run_async<C>(&self, conn: &mut C) -> Result<Report, Error>
where
C: AsyncMigrate + Send,
{
AsyncMigrate::migrate(
conn,
&self.migrations,
self.abort_divergent,
self.abort_missing,
self.grouped,
self.target,
)
.await
}
}