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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
#[macro_use]
extern crate log;
#[macro_use]
extern crate macros;
extern crate kvdb;
extern crate kvdb_rocksdb;
use std::{
collections::BTreeMap,
error, fs, io,
path::{Path, PathBuf},
sync::Arc,
};
use kvdb::DBTransaction;
use kvdb_rocksdb::{CompactionProfile, Database, DatabaseConfig};
fn other_io_err<E>(e: E) -> io::Error
where
E: Into<Box<dyn error::Error + Send + Sync>>,
{
io::Error::new(io::ErrorKind::Other, e)
}
#[derive(Clone)]
pub struct Config {
pub batch_size: usize,
pub compaction_profile: CompactionProfile,
}
impl Default for Config {
fn default() -> Self {
Config {
batch_size: 1024,
compaction_profile: Default::default(),
}
}
}
pub struct Batch {
inner: BTreeMap<Vec<u8>, Vec<u8>>,
batch_size: usize,
column: Option<u32>,
}
impl Batch {
pub fn new(config: &Config, col: Option<u32>) -> Self {
Batch {
inner: BTreeMap::new(),
batch_size: config.batch_size,
column: col,
}
}
pub fn insert(&mut self, key: Vec<u8>, value: Vec<u8>, dest: &mut Database) -> io::Result<()> {
self.inner.insert(key, value);
if self.inner.len() == self.batch_size {
self.commit(dest)?;
}
Ok(())
}
pub fn commit(&mut self, dest: &mut Database) -> io::Result<()> {
if self.inner.is_empty() {
return Ok(());
}
let mut transaction = DBTransaction::new();
for keypair in &self.inner {
transaction.put(self.column, &keypair.0, &keypair.1);
}
self.inner.clear();
dest.write(transaction)
}
}
pub trait Migration: 'static {
fn pre_columns(&self) -> Option<u32> {
self.columns()
}
fn columns(&self) -> Option<u32>;
fn alters_existing(&self) -> bool {
true
}
fn version(&self) -> u32;
fn migrate(
&mut self,
source: Arc<Database>,
config: &Config,
destination: &mut Database,
col: Option<u32>,
) -> io::Result<()>;
}
pub trait SimpleMigration: 'static {
fn columns(&self) -> Option<u32>;
fn version(&self) -> u32;
fn migrated_column_index(&self) -> Option<u32>;
fn simple_migrate(&mut self, key: Vec<u8>, value: Vec<u8>) -> Option<(Vec<u8>, Vec<u8>)>;
}
impl<T: SimpleMigration> Migration for T {
fn columns(&self) -> Option<u32> {
SimpleMigration::columns(self)
}
fn version(&self) -> u32 {
SimpleMigration::version(self)
}
fn alters_existing(&self) -> bool {
true
}
fn migrate(
&mut self,
source: Arc<Database>,
config: &Config,
dest: &mut Database,
col: Option<u32>,
) -> io::Result<()> {
let migration_needed = col == SimpleMigration::migrated_column_index(self);
let mut batch = Batch::new(config, col);
let iter = match source.iter(col) {
Some(iter) => iter,
None => return Ok(()),
};
for (key, value) in iter {
if migration_needed {
if let Some((key, value)) = self.simple_migrate(key.into_vec(), value.into_vec()) {
batch.insert(key, value, dest)?;
}
} else {
batch.insert(key.into_vec(), value.into_vec(), dest)?;
}
}
batch.commit(dest)
}
}
pub struct ChangeColumns {
pub pre_columns: Option<u32>,
pub post_columns: Option<u32>,
pub version: u32,
}
impl Migration for ChangeColumns {
fn pre_columns(&self) -> Option<u32> {
self.pre_columns
}
fn columns(&self) -> Option<u32> {
self.post_columns
}
fn version(&self) -> u32 {
self.version
}
fn alters_existing(&self) -> bool {
false
}
fn migrate(
&mut self,
_: Arc<Database>,
_: &Config,
_: &mut Database,
_: Option<u32>,
) -> io::Result<()> {
Ok(())
}
}
fn database_path(path: &Path) -> PathBuf {
let mut temp_path = path.to_owned();
temp_path.pop();
temp_path
}
enum TempIndex {
One,
Two,
}
impl TempIndex {
fn swap(&mut self) {
match *self {
TempIndex::One => *self = TempIndex::Two,
TempIndex::Two => *self = TempIndex::One,
}
}
fn path(&self, db_root: &Path) -> PathBuf {
let mut buf = db_root.to_owned();
match *self {
TempIndex::One => buf.push("temp_migration_1"),
TempIndex::Two => buf.push("temp_migration_2"),
};
buf
}
}
pub struct Manager {
config: Config,
migrations: Vec<Box<dyn Migration>>,
}
impl Manager {
pub fn new(config: Config) -> Self {
Manager {
config: config,
migrations: vec![],
}
}
pub fn add_migration<T>(&mut self, migration: T) -> io::Result<()>
where
T: Migration,
{
let is_new = match self.migrations.last() {
Some(last) => migration.version() > last.version(),
None => true,
};
match is_new {
true => Ok(self.migrations.push(Box::new(migration))),
false => Err(other_io_err("Cannot add migration.")),
}
}
pub fn execute(&mut self, old_path: &Path, version: u32) -> io::Result<PathBuf> {
let config = self.config.clone();
let migrations = self.migrations_from(version);
trace!(target: "migration", "Total migrations to execute for version {}: {}", version, migrations.len());
if migrations.is_empty() {
return Err(other_io_err("Migration impossible"));
};
let columns = migrations.get(0).and_then(|m| m.pre_columns());
trace!(target: "migration", "Expecting database to contain {:?} columns", columns);
let mut db_config = DatabaseConfig {
max_open_files: 64,
memory_budget: None,
compaction: config.compaction_profile,
columns: columns,
};
let db_root = database_path(old_path);
let mut temp_idx = TempIndex::One;
let mut temp_path = old_path.to_path_buf();
let old_path_str = old_path
.to_str()
.ok_or_else(|| other_io_err("Migration impossible."))?;
let mut cur_db = Arc::new(Database::open(&db_config, old_path_str)?);
for migration in migrations {
trace!(target: "migration", "starting migration to version {}", migration.version());
let current_columns = db_config.columns;
db_config.columns = migration.columns();
if migration.alters_existing() {
temp_path = temp_idx.path(&db_root);
let temp_path_str = temp_path
.to_str()
.ok_or_else(|| other_io_err("Migration impossible."))?;
let mut new_db = Database::open(&db_config, temp_path_str)?;
match current_columns {
None => migration.migrate(cur_db.clone(), &config, &mut new_db, None)?,
Some(v) => {
for col in 0..v {
migration.migrate(cur_db.clone(), &config, &mut new_db, Some(col))?
}
}
}
cur_db = Arc::new(new_db);
temp_idx.swap();
let _ = fs::remove_dir_all(temp_idx.path(&db_root));
} else {
let goal_columns = migration.columns().unwrap_or(0);
while cur_db.num_columns() < goal_columns {
cur_db.add_column().map_err(other_io_err)?;
}
while cur_db.num_columns() > goal_columns {
cur_db.drop_column().map_err(other_io_err)?;
}
}
}
Ok(temp_path)
}
pub fn is_needed(&self, version: u32) -> bool {
match self.migrations.last() {
Some(last) => version < last.version(),
None => false,
}
}
fn migrations_from(&mut self, version: u32) -> Vec<&mut Box<dyn Migration>> {
self.migrations
.iter_mut()
.filter(|m| m.version() > version)
.collect()
}
}
pub struct Progress {
current: usize,
max: usize,
}
impl Default for Progress {
fn default() -> Self {
Progress {
current: 0,
max: 100_000,
}
}
}
impl Progress {
pub fn tick(&mut self) {
self.current += 1;
if self.current == self.max {
self.current = 0;
flush!(".");
}
}
}