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
#![doc(html_root_url = "https://cmsd2.github.io/rust-docs/schemamama_rusqlite/schemamama_rusqlite/")]
#[macro_use]
extern crate schemamama;
extern crate rusqlite;
#[macro_use]
extern crate log;
use schemamama::{Adapter, Migration, Version};
use std::collections::BTreeSet;
use rusqlite::{SqliteConnection,SqliteResult,SqliteStatement};
#[derive(Debug)]
pub enum SqliteMigrationError {
UknownError,
RusqliteError(rusqlite::Error),
SqlError(String),
}
impl From<rusqlite::Error> for SqliteMigrationError {
fn from(err: rusqlite::Error) -> SqliteMigrationError {
SqliteMigrationError::RusqliteError(err)
}
}
pub type Result<T> = std::result::Result<T, SqliteMigrationError>;
pub trait SqliteMigration : Migration {
#[allow(unused_variables)]
fn up(&self, conn: &SqliteConnection) -> SqliteResult<()> { Ok(()) }
#[allow(unused_variables)]
fn down(&self, conn: &SqliteConnection) -> SqliteResult<()> { Ok(()) }
}
pub struct SqliteAdapter<'a> {
connection: &'a SqliteConnection
}
impl <'a> SqliteAdapter<'a> {
pub fn new(connection: &'a SqliteConnection) -> SqliteAdapter<'a> {
SqliteAdapter { connection: connection }
}
pub fn setup_schema(&self) {
let query = "CREATE TABLE IF NOT EXISTS schemamama (version BIGINT PRIMARY KEY);";
if let Err(e) = self.connection.execute(query, &[]) {
panic!("Schema setup failed: {:?}", e);
}
}
fn record_version(&self, version: Version) -> SqliteResult<()> {
let query = "INSERT INTO schemamama (version) VALUES ($1);";
let mut stmt = try!(self.connection.prepare(query));
match stmt.execute(&[&version]) {
Err(e) => {
warn!("Failed to delete version {:?}: {:?}", version, e);
Err(e)
}
_ => Ok(())
}
}
fn erase_version(&self, version: Version) -> SqliteResult<()> {
let query = "DELETE FROM schemamama WHERE version = $1;";
let mut stmt = self.connection.prepare(query).unwrap();
match stmt.execute(&[&version]) {
Err(e) => {
warn!("Failed to delete version {:?}: {:?}", version, e);
Err(e)
}
_ => Ok(())
}
}
fn execute_transaction<F>(&self, block: F) -> SqliteResult<()> where F: Fn(&SqliteConnection) -> SqliteResult<()> {
let tx = try!(self.connection.transaction());
try!(block(self.connection));
tx.commit()
}
fn prepare(&self, query: &str) -> Result<SqliteStatement> {
self.connection.prepare(query).map_err(SqliteMigrationError::from)
}
}
impl <'a> Adapter for SqliteAdapter<'a> {
type MigrationType = SqliteMigration;
type Error = SqliteMigrationError;
fn current_version(&self) -> Result<Option<Version>> {
let query = "SELECT version FROM schemamama ORDER BY version DESC LIMIT 1;";
let mut statement = try!(self.prepare(query));
let mut rows = try!(statement.query(&[]));
if let Some(row_result) = rows.next() {
let val = try!(row_result).get(0);
Ok(Some(val))
} else {
Ok(None)
}
}
fn migrated_versions(&self) -> Result<BTreeSet<Version>> {
let query = "SELECT version FROM schemamama;";
let mut statement = try!(self.prepare(query));
let rows = try!(statement.query_map(&[], |row_result| {
row_result.get(0)
}));
let mut versions = BTreeSet::new();
for vresult in rows {
versions.insert(try!(vresult));
}
Ok(versions)
}
fn apply_migration(&self, migration: &SqliteMigration) -> Result<()> {
try!(self.execute_transaction(|transaction| {
try!(migration.up(&transaction));
try!(self.record_version(migration.version()));
Ok(())
}));
Ok(())
}
fn revert_migration(&self, migration: &SqliteMigration) -> Result<()> {
try!(self.execute_transaction(|transaction| {
try!(migration.down(&transaction));
try!(self.erase_version(migration.version()));
Ok(())
}));
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::{SqliteMigration,SqliteAdapter};
use schemamama::{Migrator};
use rusqlite::{SqliteConnection,SqliteResult};
struct CreateUsers;
migration!(CreateUsers, 1, "create users table");
impl SqliteMigration for CreateUsers {
fn up(&self, conn: &SqliteConnection) -> SqliteResult<()> {
conn.execute("CREATE TABLE users (id BIGINT PRIMARY KEY);", &[]).map(|_| ())
}
fn down(&self, conn: &SqliteConnection) -> SqliteResult<()> {
conn.execute("DROP TABLE users;", &[]).map(|_| ())
}
}
#[test]
pub fn test_register() {
let conn = SqliteConnection::open_in_memory().unwrap();
let adapter = SqliteAdapter::new(&conn);
adapter.setup_schema();
let mut migrator = Migrator::new(adapter);
migrator.register(Box::new(CreateUsers));
migrator.up(Some(1)).unwrap();
assert_eq!(migrator.current_version().unwrap(), Some(1));
migrator.down(None).unwrap();
assert_eq!(migrator.current_version().unwrap(), None);
}
}