-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathadd.rs
More file actions
406 lines (354 loc) · 11.7 KB
/
add.rs
File metadata and controls
406 lines (354 loc) · 11.7 KB
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
403
404
405
406
use anyhow::Context;
use assert_cmd::cargo_bin_cmd;
use std::cmp::Ordering;
use std::fs::read_dir;
use std::ops::Index;
use std::path::{Path, PathBuf};
use tempfile::TempDir;
#[derive(Debug, PartialEq, Eq)]
struct FileName {
id: u64,
description: String,
suffix: String,
}
impl PartialOrd<Self> for FileName {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
if self.id != other.id {
self.id.partial_cmp(&other.id)
} else {
self.suffix.partial_cmp(&other.suffix)
}
}
}
impl FileName {
fn assert_is_timestamp(&self) {
assert!(
self.id > 20200101000000,
"{self:?} is too low for a timestamp"
);
}
}
impl From<PathBuf> for FileName {
fn from(path: PathBuf) -> Self {
let filename = path.file_name().unwrap().to_string_lossy();
let (id, rest) = filename.split_once("_").unwrap();
let id: u64 = id.parse().unwrap();
let (description, suffix) = rest.split_once(".").unwrap();
Self {
id,
description: description.to_string(),
suffix: suffix.to_string(),
}
}
}
struct AddMigrationsResult(Vec<FileName>);
impl AddMigrationsResult {
fn len(&self) -> usize {
self.0.len()
}
fn assert_is_reversible(&self) {
let mut up_cnt = 0;
let mut down_cnt = 0;
for file in self.0.iter() {
if file.suffix == "down.sql" {
down_cnt += 1;
} else if file.suffix == "up.sql" {
up_cnt += 1;
} else {
panic!("unknown suffix for {file:?}");
}
assert!(file.description.starts_with("hello_world"));
}
assert_eq!(up_cnt, down_cnt);
}
fn assert_is_not_reversible(&self) {
for file in self.0.iter() {
assert_eq!(file.suffix, "sql");
assert!(file.description.starts_with("hello_world"));
}
}
}
impl Index<usize> for AddMigrationsResult {
type Output = FileName;
fn index(&self, index: usize) -> &Self::Output {
&self.0[index]
}
}
struct AddMigrations {
tempdir: TempDir,
config_arg: Option<String>,
}
impl AddMigrations {
fn new() -> anyhow::Result<Self> {
anyhow::Ok(Self {
tempdir: TempDir::new()?,
config_arg: None,
})
}
fn with_config(mut self, filename: &str) -> anyhow::Result<Self> {
let path = format!("./tests/assets/{filename}");
let path = std::fs::canonicalize(&path)
.with_context(|| format!("error canonicalizing path {path:?}"))?;
let path = path
.to_str()
.with_context(|| format!("canonicalized version of path {path:?} is not UTF-8"))?;
self.config_arg = Some(format!("--config={path}"));
Ok(self)
}
fn run(
&self,
description: &str,
revesible: bool,
timestamp: bool,
sequential: bool,
expect_success: bool,
) -> anyhow::Result<&'_ Self> {
let cmd_result = cargo_bin_cmd!("cargo-sqlx")
.current_dir(&self.tempdir)
.args(
[
vec!["sqlx", "migrate", "add", description],
self.config_arg.as_deref().map_or(vec![], |arg| vec![arg]),
match revesible {
true => vec!["-r"],
false => vec![],
},
match timestamp {
true => vec!["--timestamp"],
false => vec![],
},
match sequential {
true => vec!["--sequential"],
false => vec![],
},
]
.concat(),
)
.env("RUST_BACKTRACE", "1")
.assert();
if expect_success {
cmd_result.success();
} else {
cmd_result.failure();
}
anyhow::Ok(self)
}
fn fs_output(&self) -> anyhow::Result<AddMigrationsResult> {
let files = recurse_files(&self.tempdir)?;
let mut fs_paths = Vec::with_capacity(files.len());
for path in files {
let relative_path = path.strip_prefix(self.tempdir.path())?.to_path_buf();
fs_paths.push(FileName::from(relative_path));
}
Ok(AddMigrationsResult(fs_paths))
}
}
fn recurse_files(path: impl AsRef<Path>) -> anyhow::Result<Vec<PathBuf>> {
let mut buf = vec![];
let entries = read_dir(path)?;
for entry in entries {
let entry = entry?;
let meta = entry.metadata()?;
if meta.is_dir() {
let mut subdir = recurse_files(entry.path())?;
buf.append(&mut subdir);
}
if meta.is_file() {
buf.push(entry.path());
}
}
buf.sort();
Ok(buf)
}
#[test]
fn add_migration_error_ambiguous() -> anyhow::Result<()> {
for reversible in [true, false] {
let files = AddMigrations::new()?
// Passing both `--timestamp` and `--reversible` should result in an error.
.run("hello world", reversible, true, true, false)?
.fs_output()?;
// Assert that no files are created
assert_eq!(files.0, []);
}
Ok(())
}
#[test]
fn add_migration_sequential() -> anyhow::Result<()> {
{
let files = AddMigrations::new()?
.run("hello world", false, false, true, true)?
.fs_output()?;
assert_eq!(files.len(), 1);
files.assert_is_not_reversible();
assert_eq!(files.0[0].id, 1);
}
{
let files = AddMigrations::new()?
.run("hello world1", false, false, true, true)?
.run("hello world2", true, false, true, true)?
.fs_output()?;
assert_eq!(files.len(), 3);
assert_eq!(files.0[0].id, 1);
assert_eq!(files.0[1].id, 2);
assert_eq!(files.0[1].suffix, "down.sql");
assert_eq!(files.0[2].id, 2);
assert_eq!(files.0[2].suffix, "up.sql");
}
Ok(())
}
#[test]
fn add_migration_sequential_reversible() -> anyhow::Result<()> {
{
let files = AddMigrations::new()?
.run("hello world", true, false, true, true)?
.fs_output()?;
assert_eq!(files.len(), 2);
files.assert_is_reversible();
assert_eq!(files.0[0].id, 1);
assert_eq!(files.0[0].id, 1);
}
{
let files = AddMigrations::new()?
.run("hello world1", true, false, true, true)?
.run("hello world2", true, true, false, true)?
.run("hello world3", true, false, true, true)?
.fs_output()?;
assert_eq!(files.len(), 6);
files.assert_is_reversible();
assert_eq!(files.0[0].id, 1);
assert_eq!(files.0[1].id, 1);
// sequential -> timestamp is one way
files.0[2].assert_is_timestamp();
files.0[3].assert_is_timestamp();
files.0[4].assert_is_timestamp();
files.0[5].assert_is_timestamp();
}
Ok(())
}
#[test]
fn add_migration_timestamp() -> anyhow::Result<()> {
{
let files = AddMigrations::new()?
.run("hello world", false, true, false, true)?
.fs_output()?;
assert_eq!(files.len(), 1);
files.assert_is_not_reversible();
files.0[0].assert_is_timestamp();
}
{
let files = AddMigrations::new()?
.run("hello world1", false, true, false, true)?
.run("hello world2", true, false, true, true)?
.fs_output()?;
assert_eq!(files.len(), 3);
files.0[0].assert_is_timestamp();
// sequential -> timestamp is one way
files.0[1].assert_is_timestamp();
files.0[2].assert_is_timestamp();
}
Ok(())
}
#[test]
fn add_migration_timestamp_reversible() -> anyhow::Result<()> {
{
let files = AddMigrations::new()?
.run("hello world", true, false, false, true)?
.fs_output()?;
assert_eq!(files.len(), 2);
files.assert_is_reversible();
// .up.sql and .down.sql
files[0].assert_is_timestamp();
assert_eq!(files[1].id, files[0].id);
}
{
let files = AddMigrations::new()?
.run("hello world", true, true, false, true)?
.fs_output()?;
assert_eq!(files.len(), 2);
files.assert_is_reversible();
// .up.sql and .down.sql
files[0].assert_is_timestamp();
assert_eq!(files[1].id, files[0].id);
}
{
let files = AddMigrations::new()?
.run("hello world1", true, true, false, true)?
// Reversible should be inferred, but sequential should be forced
.run("hello world2", false, false, true, true)?
.fs_output()?;
assert_eq!(files.len(), 4);
files.assert_is_reversible();
// First pair: .up.sql and .down.sql
files[0].assert_is_timestamp();
assert_eq!(files[1].id, files[0].id);
// Second pair; we set `--sequential` so this version should be one higher
assert_eq!(files[2].id, files[1].id + 1);
assert_eq!(files[3].id, files[1].id + 1);
}
Ok(())
}
#[test]
fn add_migration_config_default_type_reversible() -> anyhow::Result<()> {
let files = AddMigrations::new()?
.with_config("config_default_type_reversible.toml")?
// Type should default to reversible without any flags
.run("hello world", false, false, false, true)?
.run("hello world2", false, false, false, true)?
.run("hello world3", false, false, false, true)?
.fs_output()?;
assert_eq!(files.len(), 6);
files.assert_is_reversible();
files[0].assert_is_timestamp();
assert_eq!(files[1].id, files[0].id);
files[2].assert_is_timestamp();
assert_eq!(files[3].id, files[2].id);
files[4].assert_is_timestamp();
assert_eq!(files[5].id, files[4].id);
Ok(())
}
#[test]
fn add_migration_config_default_versioning_sequential() -> anyhow::Result<()> {
let files = AddMigrations::new()?
.with_config("config_default_versioning_sequential.toml")?
// Versioning should default to timestamp without any flags
.run("hello world", false, false, false, true)?
.run("hello world2", false, false, false, true)?
.run("hello world3", false, false, false, true)?
.fs_output()?;
assert_eq!(files.len(), 3);
files.assert_is_not_reversible();
assert_eq!(files[0].id, 1);
assert_eq!(files[1].id, 2);
assert_eq!(files[2].id, 3);
Ok(())
}
#[test]
fn add_migration_config_default_versioning_timestamp() -> anyhow::Result<()> {
let migrations = AddMigrations::new()?;
migrations
.run("hello world", false, false, true, true)?
// Default config should infer sequential even without passing `--sequential`
.run("hello world2", false, false, false, true)?
.run("hello world3", false, false, false, true)?;
let files = migrations.fs_output()?;
assert_eq!(files.len(), 3);
files.assert_is_not_reversible();
assert_eq!(files[0].id, 1);
assert_eq!(files[1].id, 2);
assert_eq!(files[2].id, 3);
// Now set a config that uses `default-versioning = "timestamp"`
let migrations = migrations.with_config("config_default_versioning_timestamp.toml")?;
// Now the default should be a timestamp
migrations
.run("hello world4", false, false, false, true)?
.run("hello world5", false, false, false, true)?;
let files = migrations.fs_output()?;
assert_eq!(files.len(), 5);
files.assert_is_not_reversible();
assert_eq!(files[0].id, 1);
assert_eq!(files[1].id, 2);
assert_eq!(files[2].id, 3);
files[3].assert_is_timestamp();
files[4].assert_is_timestamp();
Ok(())
}