-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql.rs
More file actions
318 lines (271 loc) · 10.7 KB
/
Copy pathsql.rs
File metadata and controls
318 lines (271 loc) · 10.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
//! SQL file loading
//!
//! Reads `.sql` migration files from disk, parses them into IR using the
//! pg_query parser, and returns `MigrationUnit`s ready for catalog replay
//! and linting.
use crate::input::{LoadError, MigrationHistory, MigrationLoader, MigrationUnit};
use crate::parser::pg_query::parse_sql;
use std::path::{Path, PathBuf};
/// Loader for plain SQL migration files.
///
/// Reads `.sql` files from the configured migration directories, sorted
/// lexicographically by filename. Each file becomes one `MigrationUnit`.
///
/// Down migrations are detected by filename patterns: `.down.sql` or `_down.sql`.
#[derive(Default)]
pub struct SqlLoader;
impl SqlLoader {
/// Load a single SQL file and parse it into a `MigrationUnit`.
///
/// The file is read entirely into memory, parsed into IR nodes, and
/// wrapped in a `MigrationUnit` with metadata derived from the filename.
pub fn load_file(path: &Path) -> Result<MigrationUnit, LoadError> {
let source = std::fs::read_to_string(path).map_err(|e| LoadError::Io {
path: path.to_path_buf(),
source: e,
})?;
let statements = parse_sql(&source);
let filename = path
.file_name()
.map(|f| f.to_string_lossy().to_string())
.unwrap_or_else(|| path.to_string_lossy().to_string());
let is_down = filename.contains(".down.") || filename.contains("_down.");
Ok(MigrationUnit {
id: filename,
statements,
source_file: path.to_path_buf(),
source_line_offset: 1,
run_in_transaction: true,
is_down,
})
}
}
impl MigrationLoader for SqlLoader {
/// Load migrations from the given paths.
///
/// Each path can be either a directory (in which case all `.sql` files
/// within it are loaded, sorted lexicographically) or a direct path to
/// a `.sql` file.
///
/// Files that fail to read or parse are reported as errors. The loader
/// collects all SQL files across all paths, sorts them, and returns the
/// complete migration history.
fn load(&self, paths: &[PathBuf]) -> Result<MigrationHistory, LoadError> {
let mut sql_files: Vec<PathBuf> = Vec::new();
for path in paths {
if path.is_dir() {
let entries = collect_sql_files(path)?;
sql_files.extend(entries);
} else if path.is_file() {
if is_sql_file(path) {
sql_files.push(path.clone());
}
} else {
return Err(LoadError::Io {
path: path.clone(),
source: std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("Path does not exist: {}", path.display()),
),
});
}
}
// Sort lexicographically by filename to ensure deterministic ordering
sql_files.sort_by(|a, b| {
let a_name = a.file_name().unwrap_or_default();
let b_name = b.file_name().unwrap_or_default();
a_name.cmp(b_name)
});
let mut units = Vec::new();
for file in &sql_files {
let unit = SqlLoader::load_file(file)?;
units.push(unit);
}
Ok(MigrationHistory { units })
}
}
/// Collect all `.sql` files from a directory (non-recursive).
fn collect_sql_files(dir: &Path) -> Result<Vec<PathBuf>, LoadError> {
let entries = std::fs::read_dir(dir).map_err(|e| LoadError::Io {
path: dir.to_path_buf(),
source: e,
})?;
let mut files: Vec<PathBuf> = Vec::new();
for entry in entries {
let entry = entry.map_err(|e| LoadError::Io {
path: dir.to_path_buf(),
source: e,
})?;
let path = entry.path();
if path.is_file() && is_sql_file(&path) {
files.push(path);
}
}
Ok(files)
}
/// Check if a path has a `.sql` extension.
fn is_sql_file(path: &Path) -> bool {
path.extension()
.map(|ext| ext.eq_ignore_ascii_case("sql"))
.unwrap_or(false)
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
#[test]
fn test_is_sql_file() {
assert!(is_sql_file(Path::new("V001__create_table.sql")));
assert!(is_sql_file(Path::new("V001__create_table.SQL")));
assert!(is_sql_file(Path::new("/path/to/migration.sql")));
assert!(!is_sql_file(Path::new("changelog.xml")));
assert!(!is_sql_file(Path::new("readme.md")));
assert!(!is_sql_file(Path::new("noext")));
}
#[test]
fn test_load_file_basic() {
let dir = tempfile::tempdir().expect("Failed to create temp dir");
let file_path = dir.path().join("V001__create_users.sql");
fs::write(
&file_path,
"CREATE TABLE users (id integer PRIMARY KEY, name text NOT NULL);",
)
.expect("Failed to write test file");
let unit = SqlLoader::load_file(&file_path).expect("Failed to load file");
assert_eq!(unit.id, "V001__create_users.sql");
assert_eq!(unit.source_file, file_path);
assert_eq!(unit.source_line_offset, 1);
assert!(unit.run_in_transaction);
assert!(!unit.is_down);
assert!(!unit.statements.is_empty());
}
#[test]
fn test_load_file_down_migration_dot() {
let dir = tempfile::tempdir().expect("Failed to create temp dir");
let file_path = dir.path().join("V001__create_users.down.sql");
fs::write(&file_path, "DROP TABLE users;").expect("Failed to write test file");
let unit = SqlLoader::load_file(&file_path).expect("Failed to load file");
assert!(unit.is_down);
}
#[test]
fn test_load_file_down_migration_underscore() {
let dir = tempfile::tempdir().expect("Failed to create temp dir");
let file_path = dir.path().join("V001__create_users_down.sql");
fs::write(&file_path, "DROP TABLE users;").expect("Failed to write test file");
let unit = SqlLoader::load_file(&file_path).expect("Failed to load file");
assert!(unit.is_down);
}
#[test]
fn test_load_file_not_down_migration() {
let dir = tempfile::tempdir().expect("Failed to create temp dir");
let file_path = dir.path().join("V001__create_users.sql");
fs::write(&file_path, "CREATE TABLE users (id int);").expect("Failed to write test file");
let unit = SqlLoader::load_file(&file_path).expect("Failed to load file");
assert!(!unit.is_down);
}
#[test]
fn test_load_file_nonexistent() {
let result = SqlLoader::load_file(Path::new("/nonexistent/path/migration.sql"));
assert!(result.is_err());
match result {
Err(LoadError::Io { path, .. }) => {
assert_eq!(path, PathBuf::from("/nonexistent/path/migration.sql"));
}
other => panic!("Expected LoadError::Io, got: {:?}", other),
}
}
#[test]
fn test_load_file_multi_statement() {
let dir = tempfile::tempdir().expect("Failed to create temp dir");
let file_path = dir.path().join("V001__multi.sql");
fs::write(
&file_path,
"CREATE TABLE a (id int);\nCREATE TABLE b (id int);\nCREATE INDEX idx ON a (id);",
)
.expect("Failed to write test file");
let unit = SqlLoader::load_file(&file_path).expect("Failed to load file");
assert_eq!(unit.statements.len(), 3);
}
#[test]
fn test_loader_directory() {
let dir = tempfile::tempdir().expect("Failed to create temp dir");
// Create files in non-alphabetical order
fs::write(
dir.path().join("V002__add_index.sql"),
"CREATE INDEX idx ON users (name);",
)
.expect("write");
fs::write(
dir.path().join("V001__create_table.sql"),
"CREATE TABLE users (id int, name text);",
)
.expect("write");
fs::write(
dir.path().join("V003__alter.sql"),
"ALTER TABLE users ADD COLUMN email text;",
)
.expect("write");
// Also create a non-SQL file that should be ignored
fs::write(dir.path().join("README.md"), "# Migrations").expect("write");
let loader = SqlLoader;
let history = loader
.load(&[dir.path().to_path_buf()])
.expect("Failed to load migrations");
assert_eq!(history.units.len(), 3);
// Should be sorted lexicographically
assert_eq!(history.units[0].id, "V001__create_table.sql");
assert_eq!(history.units[1].id, "V002__add_index.sql");
assert_eq!(history.units[2].id, "V003__alter.sql");
}
#[test]
fn test_loader_single_file_path() {
let dir = tempfile::tempdir().expect("Failed to create temp dir");
let file_path = dir.path().join("migration.sql");
fs::write(&file_path, "CREATE TABLE t (id int);").expect("write");
let loader = SqlLoader;
let history = loader.load(&[file_path]).expect("Failed to load migration");
assert_eq!(history.units.len(), 1);
}
#[test]
fn test_loader_nonexistent_path() {
let loader = SqlLoader;
let result = loader.load(&[PathBuf::from("/nonexistent/path")]);
assert!(result.is_err());
}
#[test]
fn test_loader_empty_paths() {
let loader = SqlLoader;
let history = loader.load(&[]).expect("Empty paths should succeed");
assert!(history.units.is_empty());
}
#[test]
fn test_loader_multiple_directories() {
let dir1 = tempfile::tempdir().expect("Failed to create temp dir");
let dir2 = tempfile::tempdir().expect("Failed to create temp dir");
fs::write(
dir1.path().join("V001__first.sql"),
"CREATE TABLE a (id int);",
)
.expect("write");
fs::write(
dir2.path().join("V002__second.sql"),
"CREATE TABLE b (id int);",
)
.expect("write");
let loader = SqlLoader;
let history = loader
.load(&[dir1.path().to_path_buf(), dir2.path().to_path_buf()])
.expect("Failed to load migrations");
assert_eq!(history.units.len(), 2);
}
#[test]
fn test_collect_sql_files_ignores_non_sql() {
let dir = tempfile::tempdir().expect("Failed to create temp dir");
fs::write(dir.path().join("migration.sql"), "SELECT 1;").expect("write");
fs::write(dir.path().join("changelog.xml"), "<xml/>").expect("write");
fs::write(dir.path().join("notes.txt"), "notes").expect("write");
let files = collect_sql_files(dir.path()).expect("collect failed");
assert_eq!(files.len(), 1);
assert!(files[0].to_string_lossy().contains("migration.sql"));
}
}