@@ -9,6 +9,7 @@ use std::slice;
9
9
pub struct Migrator {
10
10
pub migrations : Cow < ' static , [ Migration ] > ,
11
11
pub ignore_missing : bool ,
12
+ pub locking : bool ,
12
13
}
13
14
14
15
fn validate_applied_migrations (
@@ -56,6 +57,7 @@ impl Migrator {
56
57
Ok ( Self {
57
58
migrations : Cow :: Owned ( source. resolve ( ) . await . map_err ( MigrateError :: Source ) ?) ,
58
59
ignore_missing : false ,
60
+ locking : true ,
59
61
} )
60
62
}
61
63
@@ -65,6 +67,19 @@ impl Migrator {
65
67
self
66
68
}
67
69
70
+ /// Specify whether or not to lock database during migration. Defaults to `true`.
71
+ ///
72
+ /// ### Warning
73
+ /// Disabling locking can lead to errors or data loss if multiple clients attempt to apply migrations simultaneously
74
+ /// without some sort of mutual exclusion.
75
+ ///
76
+ /// This should only be used if the database does not support locking, e.g. CockroachDB which talks the Postgres
77
+ /// protocol but does not support advisory locks used by SQLx's migrations support for Postgres.
78
+ pub fn set_locking ( & mut self , locking : bool ) -> & Self {
79
+ self . locking = locking;
80
+ self
81
+ }
82
+
68
83
/// Get an iterator over all known migrations.
69
84
pub fn iter ( & self ) -> slice:: Iter < ' _ , Migration > {
70
85
self . migrations . iter ( )
@@ -103,7 +118,9 @@ impl Migrator {
103
118
C : Migrate ,
104
119
{
105
120
// lock the database for exclusive access by the migrator
106
- conn. lock ( ) . await ?;
121
+ if self . locking {
122
+ conn. lock ( ) . await ?;
123
+ }
107
124
108
125
// creates [_migrations] table only if needed
109
126
// eventually this will likely migrate previous versions of the table
@@ -141,7 +158,9 @@ impl Migrator {
141
158
142
159
// unlock the migrator to allow other migrators to run
143
160
// but do nothing as we already migrated
144
- conn. unlock ( ) . await ?;
161
+ if self . locking {
162
+ conn. unlock ( ) . await ?;
163
+ }
145
164
146
165
Ok ( ( ) )
147
166
}
@@ -170,7 +189,9 @@ impl Migrator {
170
189
let mut conn = migrator. acquire ( ) . await ?;
171
190
172
191
// lock the database for exclusive access by the migrator
173
- conn. lock ( ) . await ?;
192
+ if self . locking {
193
+ conn. lock ( ) . await ?;
194
+ }
174
195
175
196
// creates [_migrations] table only if needed
176
197
// eventually this will likely migrate previous versions of the table
@@ -201,7 +222,9 @@ impl Migrator {
201
222
202
223
// unlock the migrator to allow other migrators to run
203
224
// but do nothing as we already migrated
204
- conn. unlock ( ) . await ?;
225
+ if self . locking {
226
+ conn. unlock ( ) . await ?;
227
+ }
205
228
206
229
Ok ( ( ) )
207
230
}
0 commit comments