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
use crate::error::Result;
use rusqlite::{Connection, NO_PARAMS};
use sql_support::ConnExt;
const VERSION: i64 = 2;
const CREATE_SCHEMA_SQL: &str = include_str!("../sql/create_schema.sql");
const CREATE_SYNC_TEMP_TABLES_SQL: &str = include_str!("../sql/create_sync_temp_tables.sql");
fn get_current_schema_version(db: &Connection) -> Result<i64> {
Ok(db.query_one::<i64>("PRAGMA user_version")?)
}
pub fn init(db: &Connection) -> Result<()> {
let user_version = get_current_schema_version(db)?;
if user_version == 0 {
create(db)?;
} else if user_version != VERSION {
if user_version < VERSION {
upgrade(db, user_version)?;
} else {
log::warn!(
"Loaded future schema version {} (we only understand version {}). \
Optimistically ",
user_version,
VERSION
);
db.execute_batch(&format!("PRAGMA user_version = {};", VERSION))?;
}
create(db)?;
}
Ok(())
}
fn create(db: &Connection) -> Result<()> {
log::debug!("Creating schema");
db.execute_batch(CREATE_SCHEMA_SQL)?;
db.execute(
&format!("PRAGMA user_version = {version}", version = VERSION),
NO_PARAMS,
)?;
Ok(())
}
fn upgrade(db: &Connection, from: i64) -> Result<()> {
log::debug!("Upgrading schema from {} to {}", from, VERSION);
if from == VERSION {
return Ok(());
}
if from == 1 {
log::debug!("Upgrading schema from 1 to 2");
db.execute_batch("ALTER TABLE storage_sync_mirror RENAME TO old_mirror;")?;
db.execute_batch(CREATE_SCHEMA_SQL)?;
db.execute_batch(
"INSERT OR IGNORE INTO storage_sync_mirror(guid, ext_id, data)
SELECT guid, ext_id, data FROM old_mirror;",
)?;
db.execute_batch("DROP TABLE old_mirror;")?;
db.execute_batch("PRAGMA user_version = 2;")?;
}
Ok(())
}
pub fn create_empty_sync_temp_tables(db: &Connection) -> Result<()> {
log::debug!("Initializing sync temp tables");
db.execute_batch(CREATE_SYNC_TEMP_TABLES_SQL)?;
Ok(())
}
#[cfg(test)]
pub mod test {
use prettytable::{Cell, Row};
use rusqlite::Result as RusqliteResult;
use rusqlite::{types::Value, Connection, NO_PARAMS};
#[allow(unused)]
pub fn print_table(conn: &Connection, table_name: &str) -> RusqliteResult<()> {
let mut stmt = conn.prepare(&format!("SELECT * FROM {}", table_name))?;
let mut rows = stmt.query(NO_PARAMS)?;
let mut table = prettytable::Table::new();
let mut titles = Row::empty();
for col in rows.columns().expect("must have columns") {
titles.add_cell(Cell::new(col.name()));
}
table.set_titles(titles);
while let Some(sql_row) = rows.next()? {
let mut table_row = Row::empty();
for i in 0..sql_row.column_count() {
let val = match sql_row.get::<_, Value>(i)? {
Value::Null => "null".to_string(),
Value::Integer(i) => i.to_string(),
Value::Real(f) => f.to_string(),
Value::Text(s) => s,
Value::Blob(b) => format!("<blob with {} bytes>", b.len()),
};
table_row.add_cell(Cell::new(&val));
}
table.add_row(table_row);
}
table.printstd();
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::db::test::new_mem_db;
use rusqlite::Error;
#[test]
fn test_create_schema_twice() {
let db = new_mem_db();
db.execute_batch(CREATE_SCHEMA_SQL)
.expect("should allow running twice");
}
#[test]
fn test_create_empty_sync_temp_tables_twice() {
let db = new_mem_db();
create_empty_sync_temp_tables(&db).expect("should work first time");
db.execute_batch(
"INSERT INTO temp.storage_sync_staging
(guid, ext_id) VALUES
('guid', 'ext_id');",
)
.expect("should work once");
let count = db
.query_row_and_then(
"SELECT COUNT(*) FROM temp.storage_sync_staging;",
rusqlite::NO_PARAMS,
|row| row.get::<_, u32>(0),
)
.expect("query should work");
assert_eq!(count, 1, "should be one row");
create_empty_sync_temp_tables(&db).expect("should second first time");
let count = db
.query_row_and_then(
"SELECT COUNT(*) FROM temp.storage_sync_staging;",
rusqlite::NO_PARAMS,
|row| row.get::<_, u32>(0),
)
.expect("query should work");
assert_eq!(count, 0, "should be no rows");
}
#[test]
fn test_upgrade_1_2() -> Result<()> {
let _ = env_logger::try_init();
let old_create_table = "CREATE TABLE IF NOT EXISTS storage_sync_mirror (
guid TEXT NOT NULL PRIMARY KEY,
ext_id TEXT NOT NULL UNIQUE,
data TEXT
);";
let db = new_mem_db();
db.execute_batch("DROP TABLE storage_sync_mirror;")?;
db.execute_batch(old_create_table)?;
db.execute_batch(
"INSERT INTO storage_sync_mirror(guid, ext_id, data)
VALUES
('guid-1', 'ext-id-1', 'data-1'),
('guid-2', 'ext-id-2', 'data-2')",
)?;
db.execute_batch("PRAGMA user_version = 1")?;
assert!(db
.execute_batch(
"INSERT INTO storage_sync_mirror(guid, ext_id, data)
VALUES ('guid-3', NULL, NULL);"
)
.is_err());
upgrade(&db, 1)?;
assert_eq!(get_current_schema_version(&db)?, VERSION);
db.execute_batch(
"INSERT INTO storage_sync_mirror(guid, ext_id, data)
VALUES ('guid-3', NULL, NULL);",
)?;
let get_id_data = |guid: &str| -> Result<(Option<String>, Option<String>)> {
let (ext_id, data) = db
.try_query_row::<_, Error, _>(
"SELECT ext_id, data FROM storage_sync_mirror WHERE guid = :guid",
&[(":guid", &guid.to_string())],
|row| Ok((row.get(0)?, row.get(1)?)),
true,
)?
.expect("row should exist.");
Ok((ext_id, data))
};
assert_eq!(
get_id_data("guid-1")?,
(Some("ext-id-1".to_string()), Some("data-1".to_string()))
);
assert_eq!(
get_id_data("guid-2")?,
(Some("ext-id-2".to_string()), Some("data-2".to_string()))
);
assert_eq!(get_id_data("guid-3")?, (None, None));
Ok(())
}
}