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
use std::vec::Vec;
use postgres::{self, GenericConnection};
use super::error::Error;
use super::migration::Migration;
use super::Result;
/// Tracks and manages database migrations for this system.
pub struct MigrationIndex {
/// all database migrations, in order from first to last
migrations: Vec<Box<Migration>>
}
impl MigrationIndex {
/// Wrap the given Migrations list into a new MigrationIndex.
#[allow(dead_code)]
pub fn new(mut migrations: Vec<Box<Migration>>) -> Self {
migrations.shrink_to_fit();
MigrationIndex {
migrations: migrations
}
}
/// Runs all database migrations that haven't yet been applied to the database.
///
/// # Failures
///
/// Returns an error if a problem occurred when communicating with the database.
///
/// # Examples
///
/// ```no_run
/// # extern crate postgres;
/// # extern crate trek;
/// # fn main() {
/// # use postgres::{self, Connection, SslMode, Transaction};
/// # use trek::migration_index::MigrationIndex;
/// # use trek::migration::Migration;
/// # fn f() -> postgres::Result<()> {
/// let connection = Connection::connect("server url", SslMode::None).unwrap();
/// let transaction = connection.transaction().unwrap();
///
/// # let migration_list: Vec<Box<Migration>> = vec![];
/// let migrations = MigrationIndex::new(migration_list);
/// match migrations.run(&transaction) {
/// Ok(_) => {
/// try!(transaction.commit());
/// println!("All outstanding database migrations have been applied.");
/// },
/// Err(error) => {
/// // note: no need to manually roll back the transaction, it'll automatically roll
/// // back when the transaction variable goes out of scope
///
/// println!("Error updating database structure: {}", error);
/// }
/// }
/// # Ok(())
/// # };
/// # }
///
/// ```
pub fn run(&self, connection: &GenericConnection) -> Result<()> {
let mut schema_version = match MigrationIndex::schema_version(connection) {
Ok(schema_version_option) => schema_version_option,
Err(error) => {
return Err(Error::new(
"Error reading current schema version".to_owned(),
error
));
}
};
for migration in self.outstanding_migrations(schema_version.clone()).iter() {
if let Err(error) = MigrationIndex::update_schema_version(
connection, schema_version, Some(migration.to_string())
) {
return Err(Error::new(
"Error updating schema version".to_owned(),
error
));
}
if let Err(error) = migration.up(connection) {
return Err(Error::new(
format!("Error applying migration {}", migration),
error
));
}
schema_version = Some(migration.to_string());
println!("Ran migration {}", migration);
};
Ok(())
}
/// Rolls back the last database migration that was successfully applied to the database.
///
/// # Failures
///
/// Returns an error if a problem occurred when communicating with the database.
///
/// # Examples
///
/// ```no_run
/// # extern crate postgres;
/// # extern crate trek;
/// # fn main() {
/// # use postgres::{self, Connection, SslMode, Transaction};
/// # use trek::migration_index::MigrationIndex;
/// # use trek::migration::Migration;
/// # fn f() -> postgres::Result<()> {
/// let connection = Connection::connect("server url", SslMode::None).unwrap();
/// let transaction = connection.transaction().unwrap();
///
/// # let migration_list: Vec<Box<Migration>> = vec![];
/// let migrations = MigrationIndex::new(migration_list);
/// match migrations.rollback(&transaction) {
/// Ok(_) => {
/// try!(transaction.commit());
/// println!("Rollback of latest migration complete.");
/// },
/// Err(error) => {
/// // note: no need to manually roll back the transaction, it'll automatically roll
/// // back when the transaction variable goes out of scope
///
/// println!("Error error rolling back last applied migration: {}", error);
/// }
/// }
/// # Ok(())
/// # };
/// # }
///
/// ```
pub fn rollback(&self, connection: &GenericConnection) -> Result<()> {
let old_schema_version = match MigrationIndex::schema_version(connection) {
Ok(schema_version_option) => schema_version_option,
Err(error) => {
return Err(Error::new(
"Failed to get current database schema version".to_owned(),
error
))
}
};
let old_schema_version = match old_schema_version {
Some(schema_version) => schema_version,
None => {
// if there's nothing to roll back, this function call is a no-op
return Ok(());
}
};
let old_migration_index = self.current_index(&old_schema_version).unwrap();
let old_migration = self.migrations.get(old_migration_index).unwrap();
match old_migration_index {
0 => {
if let Err(error) = MigrationIndex::update_schema_version(
connection, Some(old_migration.to_string()), None
) {
return Err(Error::new(
format!(
"Failed to update schema version table when rolling back migration {}",
old_migration,
),
error
));
}
if let Err(error) = old_migration.down(connection) {
return Err(Error::new(
format!(
"The down() method of database migration {} failed",
old_migration,
),
error
));
}
println!(
"Rolled back migration {}, database is now empty.",
old_migration
);
Ok(())
},
_ => {
let new_migration = self.migrations.get(old_migration_index - 1).unwrap();
if let Err(error) = MigrationIndex::update_schema_version(
connection, Some(old_migration.to_string()), Some(new_migration.to_string())
) {
return Err(Error::new(
format!(
"Failed to update schema version table when rolling back migration {}",
new_migration,
),
error
));
}
if let Err(error) = old_migration.down(connection) {
return Err(Error::new(
format!(
"The down() method of database migration {} failed",
old_migration,
),
error
));
}
println!(
"Rolled back migration {}, database is now at version {}",
old_migration,
new_migration
);
Ok(())
}
}
}
/// Takes a queryable connection object and returns the current version of the database's
/// schema. No changes are made to the database.
///
/// # Panics
///
/// If the schema_version table that Trek uses to save a schema's current version has multiple
/// columns then this method will panic. It's expected that the schema_version table has only a
/// single column named after the last applied migration.
///
/// # Examples
///
/// ```no_run
/// # extern crate postgres;
/// # extern crate trek;
/// # fn main() {
/// # use postgres::{self, Connection, SslMode, Transaction};
/// # use trek::migration_index::MigrationIndex;
/// # use trek::migration::Migration;
/// # fn f() {
/// let connection = Connection::connect("server url", SslMode::None).unwrap();
///
/// match MigrationIndex::schema_version(&connection) {
/// Ok(result_option) => {
/// match result_option {
/// Some(name) => println!("Current database version is: {}", name),
/// None => println!("Database is empty, no migrations applied yet.")
/// };
/// },
/// Err(error) => {
/// println!("Error fetching schema version: {}", error);
/// }
/// };
/// # };
/// # }
///
/// ```
pub fn schema_version(
connection: &GenericConnection
) -> postgres::Result<Option<String>> {
let prepared_stmt = try!(connection.prepare(
"SELECT column_name FROM information_schema.columns
WHERE table_name=$1 LIMIT 1"
));
let result = try!(prepared_stmt.query(&[&"schema_version"]));
match result.len() {
0 => Ok(None),
1 => {
let version_string: String = try!(result.get(0).get_opt(0).unwrap());
Ok(Some(version_string))
},
_ => panic!(
"Failed to retrieve current database schema version. The query to get column name \
for version tracking table returned multiple rows."
)
}
}
/// Takes the current version of the database's schema and returns a slice containing all
/// migrations not yet applied to the database, in order from first to last.
fn outstanding_migrations(&self, current_version: Option<String>) -> &[Box<Migration>] {
match current_version {
Some(current_version) => {
match self.current_index(¤t_version) {
Some(current_index) => {
&self.migrations[(current_index + 1)..]
}
None => {
&*self.migrations
}
}
}
None => &*self.migrations
}
}
/// Takes the current version of the database's schema and returns the index of the migrations
/// field corresponding to the last applied database migration. Returns None if no migrations
/// have been applied to the database yet.
fn current_index(&self, current_version: &str) -> Option<usize> {
self.migrations.iter().position(|ref migration| {
migration.to_string() == *current_version
})
}
/// Takes a queryable connection object and uses it to record a new schema version in the
/// database's version table.
fn update_schema_version(
connection: &GenericConnection,
old_version: Option<String>,
new_version: Option<String>
) -> postgres::Result<()> {
match (old_version, new_version) {
(Some(old_version), Some(new_version)) => {
try!(connection.execute(
&format!(
"ALTER TABLE schema_version RENAME COLUMN \"{}\" TO \"{}\";",
&old_version, &new_version
),
&[]
));
},
(None, Some(new_version)) => {
try!(connection.execute(
&format!(
"CREATE TABLE schema_version (
\"{}\" INT NOT NULL
);",
&new_version
),
&[]
));
},
(Some(_old_version), None) => {
try!(connection.execute("DROP TABLE schema_version;", &[]));
},
(None, None) => {
// technically going from no database schema to no database schema is a no-op, but
// it probably indicates a bug so panic on this questionable input
panic!(
"Can't update schema version from None to None: at least one of old_version \
and new_version parameters must be Some"
);
}
}
Ok(())
}
}