-
Notifications
You must be signed in to change notification settings - Fork 130
/
Copy pathsync.rs
182 lines (159 loc) · 5.76 KB
/
sync.rs
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
use std::ops::Deref;
use crate::error::WrapMigrationError;
use crate::traits::{
insert_migration_query, verify_migrations, ASSERT_MIGRATIONS_TABLE_QUERY,
GET_APPLIED_MIGRATIONS_QUERY, GET_LAST_APPLIED_MIGRATION_QUERY,
};
use crate::{Error, Migration, Report, Target};
pub trait Transaction {
type Error: std::error::Error + Send + Sync + 'static;
fn execute<'a, T: Iterator<Item = &'a str>>(
&mut self,
queries: T,
) -> Result<usize, Self::Error>;
}
pub trait Query<T>: Transaction {
fn query(&mut self, query: &str) -> Result<T, Self::Error>;
}
pub fn migrate<T: Transaction>(
transaction: &mut T,
migrations: Vec<Migration>,
target: Target,
migration_table_name: &str,
grouped: bool,
) -> Result<Report, Error> {
let mut migration_batch = Vec::new();
let mut applied_migrations = Vec::new();
for mut migration in migrations.into_iter() {
if let Target::Version(input_target) | Target::FakeVersion(input_target) = target {
if input_target < migration.version() {
log::info!(
"stopping at migration: {}, due to user option",
input_target
);
break;
}
}
log::info!("applying migration: {}", migration);
migration.set_applied();
let insert_migration = insert_migration_query(&migration, migration_table_name);
let migration_sql = migration.sql().expect("sql must be Some!").to_string();
// If Target is Fake, we only update schema migrations table
if !matches!(target, Target::Fake | Target::FakeVersion(_)) {
applied_migrations.push(migration);
migration_batch.push(migration_sql);
}
migration_batch.push(insert_migration);
}
match (target, grouped) {
(Target::Fake | Target::FakeVersion(_), _) => {
log::info!("not going to apply any migration as fake flag is enabled");
}
(Target::Latest | Target::Version(_), true) => {
log::info!(
"going to apply batch migrations in single transaction: {:#?}",
applied_migrations.iter().map(ToString::to_string)
);
}
(Target::Latest | Target::Version(_), false) => {
log::info!(
"preparing to apply {} migrations: {:#?}",
applied_migrations.len(),
applied_migrations.iter().map(ToString::to_string)
);
}
};
if grouped {
transaction
.execute(migration_batch.iter().map(Deref::deref))
.migration_err("error applying migrations", None)?;
} else {
for (i, update) in migration_batch.into_iter().enumerate() {
transaction
.execute([update.as_str()].into_iter())
.migration_err("error applying update", Some(&applied_migrations[0..i / 2]))?;
}
}
Ok(Report::new(applied_migrations))
}
pub trait Migrate: Query<Vec<Migration>>
where
Self: Sized,
{
fn assert_migrations_table(&mut self, migration_table_name: &str) -> Result<usize, Error> {
// Needed cause some database vendors like Mssql have a non sql standard way of checking the migrations table,
// thou on this case it's just to be consistent with the async trait `AsyncMigrate`
self.execute(
[ASSERT_MIGRATIONS_TABLE_QUERY
.replace("%MIGRATION_TABLE_NAME%", migration_table_name)
.as_str()]
.into_iter(),
)
.migration_err("error asserting migrations table", None)
}
fn get_last_applied_migration(
&mut self,
migration_table_name: &str,
) -> Result<Option<Migration>, Error> {
let mut migrations = self
.query(
&GET_LAST_APPLIED_MIGRATION_QUERY
.replace("%MIGRATION_TABLE_NAME%", migration_table_name),
)
.migration_err("error getting last applied migration", None)?;
Ok(migrations.pop())
}
fn get_applied_migrations(
&mut self,
migration_table_name: &str,
) -> Result<Vec<Migration>, Error> {
let migrations = self
.query(
&GET_APPLIED_MIGRATIONS_QUERY
.replace("%MIGRATION_TABLE_NAME%", migration_table_name),
)
.migration_err("error getting applied migrations", None)?;
Ok(migrations)
}
fn get_unapplied_migrations(
&mut self,
migrations: &[Migration],
abort_divergent: bool,
abort_missing: bool,
migration_table_name: &str,
) -> Result<Vec<Migration>, Error> {
self.assert_migrations_table(migration_table_name)?;
let applied_migrations = self.get_applied_migrations(migration_table_name)?;
let migrations = verify_migrations(
applied_migrations,
migrations.to_vec(),
abort_divergent,
abort_missing,
)?;
if migrations.is_empty() {
log::info!("no migrations to apply");
}
Ok(migrations)
}
fn migrate(
&mut self,
migrations: &[Migration],
abort_divergent: bool,
abort_missing: bool,
grouped: bool,
target: Target,
migration_table_name: &str,
) -> Result<Report, Error> {
let migrations = self.get_unapplied_migrations(
migrations,
abort_divergent,
abort_missing,
migration_table_name,
)?;
if grouped || matches!(target, Target::Fake | Target::FakeVersion(_)) {
migrate(self, migrations, target, migration_table_name, true)
} else {
migrate(self, migrations, target, migration_table_name, false)
}
}
}