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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
//! Migration recorder
use crate::backends::DatabaseConnection;
use chrono::{DateTime, Utc};
/// Migration record
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MigrationRecord {
/// The app.
pub app: String,
/// The name.
pub name: String,
/// The applied.
pub applied: DateTime<Utc>,
}
/// Migration recorder (in-memory only, for backward compatibility)
pub struct MigrationRecorder {
records: Vec<MigrationRecord>,
}
/// Database-backed migration recorder
pub struct DatabaseMigrationRecorder {
connection: DatabaseConnection,
}
impl MigrationRecorder {
/// Creates a new instance.
pub fn new() -> Self {
Self {
records: Vec::new(),
}
}
/// Performs the record applied operation.
pub fn record_applied(&mut self, app: &str, name: &str) {
self.records.push(MigrationRecord {
app: app.to_string(),
name: name.to_string(),
applied: Utc::now(),
});
}
/// Returns the applied migrations.
pub fn get_applied_migrations(&self) -> &[MigrationRecord] {
&self.records
}
/// Returns the pplied.
pub fn is_applied(&self, app: &str, name: &str) -> bool {
self.records.iter().any(|r| r.app == app && r.name == name)
}
/// Performs the ensure schema table operation.
pub fn ensure_schema_table(&self) {
// Ensure migration schema table exists
}
// Async versions for database operations
/// Performs the ensure schema table async operation.
pub async fn ensure_schema_table_async<T>(&self, _pool: &T) -> super::Result<()> {
Ok(())
}
/// Returns the pplied async.
pub async fn is_applied_async<T>(
&self,
_pool: &T,
app: &str,
name: &str,
) -> super::Result<bool> {
Ok(self.is_applied(app, name))
}
/// Performs the record applied async operation.
pub async fn record_applied_async<T>(
&mut self,
_pool: &T,
app: &str,
name: &str,
) -> super::Result<()> {
self.record_applied(app, name);
Ok(())
}
/// Remove a migration record (for rollback)
pub fn unapply(&mut self, app: &str, name: &str) {
self.records.retain(|r| !(r.app == app && r.name == name));
}
/// Get all applied migrations for a specific app
pub fn get_applied_for_app(&self, app: &str) -> Vec<MigrationRecord> {
self.records
.iter()
.filter(|r| r.app == app)
.cloned()
.collect()
}
/// Async version of unapply
pub async fn unapply_async<T>(
&mut self,
_pool: &T,
app: &str,
name: &str,
) -> super::Result<()> {
self.unapply(app, name);
Ok(())
}
/// Async version of get_applied_for_app
pub async fn get_applied_for_app_async<T>(
&self,
_pool: &T,
app: &str,
) -> super::Result<Vec<MigrationRecord>> {
Ok(self.get_applied_for_app(app))
}
}
impl Default for MigrationRecorder {
fn default() -> Self {
Self::new()
}
}
impl DatabaseMigrationRecorder {
/// Create a new database-backed migration recorder
///
/// # Examples
///
/// ```no_run
/// use reinhardt_db::migrations::recorder::DatabaseMigrationRecorder;
/// use reinhardt_db::backends::DatabaseConnection;
///
/// # async fn example() {
/// // For doctest purposes, using mock connection (URL is ignored in current implementation)
/// let connection = DatabaseConnection::connect_postgres("postgres://localhost/mydb").await.unwrap();
/// let recorder = DatabaseMigrationRecorder::new(connection);
/// // Verify recorder was created successfully
/// recorder.ensure_schema_table().await.unwrap();
/// # }
/// # tokio::runtime::Runtime::new().unwrap().block_on(example());
/// ```
pub fn new(connection: DatabaseConnection) -> Self {
Self { connection }
}
/// Performs the ensure schema table operation.
pub async fn ensure_schema_table(&self) -> super::Result<()> {
// `DatabaseType` is only referenced from the mysql-gated match arm below;
// import it under the same gate so the non-mysql build does not warn.
#[cfg(feature = "mysql")]
use crate::backends::types::DatabaseType;
// CockroachDB is wire-compatible with PostgreSQL but does NOT implement
// `pg_advisory_lock()` (returns `function undefined`). Route through a
// CockroachDB-specific path that locks a sentinel row via
// `SELECT ... FOR UPDATE` instead. See issue #4642.
#[cfg(feature = "postgres")]
if self.connection.is_cockroachdb() {
return self.ensure_schema_table_cockroachdb().await;
}
// MySQL `GET_LOCK()` / `RELEASE_LOCK()` are session-scoped: the lock is owned
// by the connection that called `GET_LOCK`, and `RELEASE_LOCK` only succeeds
// when issued on that same session. The pooled `DatabaseConnection::execute`
// path acquires a new pool connection per call, so acquiring and releasing
// through it routinely hits two different sessions — the lock is acquired on
// session A and the bogus release runs on session B, leaving the lock leaked
// in session A. Subsequent migration calls in the same process then time out
// waiting for the leaked lock (manifesting as the rollback timeout in
// issue #4585). To make the lock symmetrical, MySQL must acquire and release
// on a single dedicated pool connection that we hold for the lock's lifetime.
match self.connection.database_type() {
#[cfg(feature = "mysql")]
DatabaseType::Mysql => self.ensure_schema_table_mysql().await,
_ => {
// Acquire advisory lock to prevent concurrent schema modifications
self.acquire_schema_lock().await?;
// Execute schema operations
let result = self.ensure_schema_table_internal().await;
// Always release lock, even if operations failed
let _ = self.release_schema_lock().await;
result
}
}
}
/// CockroachDB-specific variant of `ensure_schema_table`.
///
/// CockroachDB does not implement PostgreSQL's `pg_advisory_lock()`
/// (returns `unknown function: pg_advisory_lock(): function undefined`),
/// so the generic Postgres path in `acquire_schema_lock` fails immediately.
/// To serialise concurrent migrators we use a sentinel-row mutex: a
/// single-row `_reinhardt_migration_lock` table whose row is locked with
/// `SELECT ... FOR UPDATE` inside a held transaction. CockroachDB blocks
/// concurrent `SELECT FOR UPDATE` on the same row until the holding
/// transaction commits, giving the same "one migrator at a time"
/// guarantee that `pg_advisory_lock` provides on real PostgreSQL.
///
/// The lock transaction is held on a dedicated pool connection for the
/// lifetime of `ensure_schema_table_internal`; the actual DDL still runs
/// through the shared `DatabaseConnection`. This mirrors the dedicated-
/// `PoolConnection` pattern used by `ensure_schema_table_mysql` (which
/// holds `GET_LOCK` for the same reason — issue #4585).
///
/// Bootstrap of the sentinel table itself is intentionally lock-free:
/// `CREATE TABLE IF NOT EXISTS` and `INSERT ... ON CONFLICT DO NOTHING`
/// are both idempotent under concurrent execution on CockroachDB, so
/// there is no chicken-and-egg race.
///
/// Fixes #4642.
#[cfg(feature = "postgres")]
async fn ensure_schema_table_cockroachdb(&self) -> super::Result<()> {
use sqlx::Connection as _;
let pool = self.connection.into_postgres().ok_or_else(|| {
super::MigrationError::DatabaseError(crate::backends::DatabaseError::ConnectionError(
"PostgreSQL backend unavailable when acquiring CockroachDB schema lock".to_string(),
))
})?;
let mut conn = pool.acquire().await.map_err(|e| {
super::MigrationError::DatabaseError(crate::backends::DatabaseError::ConnectionError(
format!("Failed to acquire CockroachDB connection for schema lock: {e}"),
))
})?;
// Bootstrap the sentinel lock table. Both statements are idempotent.
sqlx::query(
"CREATE TABLE IF NOT EXISTS _reinhardt_migration_lock (\
id INT PRIMARY KEY, locked_at TIMESTAMPTZ DEFAULT now())",
)
.execute(&mut *conn)
.await
.map_err(|e| {
super::MigrationError::DatabaseError(crate::backends::DatabaseError::QueryError(
format!("Failed to create CockroachDB migration lock table: {e}"),
))
})?;
sqlx::query(
"INSERT INTO _reinhardt_migration_lock (id) VALUES (1) \
ON CONFLICT (id) DO NOTHING",
)
.execute(&mut *conn)
.await
.map_err(|e| {
super::MigrationError::DatabaseError(crate::backends::DatabaseError::QueryError(
format!("Failed to seed CockroachDB migration lock row: {e}"),
))
})?;
// Acquire the lock by starting a transaction and locking the sentinel row.
// CockroachDB blocks concurrent `SELECT FOR UPDATE` of the same row until
// the holding transaction commits or rolls back.
let mut tx = conn.begin().await.map_err(|e| {
super::MigrationError::DatabaseError(crate::backends::DatabaseError::QueryError(
format!("Failed to begin CockroachDB migration lock transaction: {e}"),
))
})?;
sqlx::query("SELECT 1 FROM _reinhardt_migration_lock WHERE id = 1 FOR UPDATE")
.execute(&mut *tx)
.await
.map_err(|e| {
super::MigrationError::DatabaseError(crate::backends::DatabaseError::QueryError(
format!("Failed to acquire CockroachDB migration lock row: {e}"),
))
})?;
// Run schema bootstrap through the shared connection while the
// sentinel-row lock is held on `tx`. The DDL runs on a *different*
// pooled connection from the lock holder — that is intentional and
// safe: the only thing the lock needs to serialise is the bootstrap
// itself, and any concurrent migrator process will block on
// `SELECT ... FOR UPDATE` of the same row.
let result = self.ensure_schema_table_internal().await;
// Release the lock. COMMIT and ROLLBACK both release `SELECT FOR
// UPDATE` row locks in CockroachDB; choose ROLLBACK on the error
// path so the lock-table side effects (none here, but defensively)
// are not retained. Release-failure is logged but not surfaced —
// the row lock is dropped on connection close in any case.
let release_result = if result.is_ok() {
tx.commit().await
} else {
tx.rollback().await
};
if let Err(e) = release_result {
tracing::warn!(
error = %e,
"Failed to release CockroachDB migration lock; the row lock will be \
released when the connection is returned to the pool"
);
}
result
}
/// MySQL-specific variant of `ensure_schema_table` that holds the advisory
/// lock on a dedicated pool connection for the lifetime of the lock.
///
/// `GET_LOCK()` and `RELEASE_LOCK()` are session-scoped in MySQL: the lock
/// belongs to the connection (session) that successfully acquired it, and
/// only that same session can release it. Running these two statements on
/// different pool connections (as happens when each call goes through the
/// generic `DatabaseConnection::execute` path) leaks the lock into the
/// acquiring session, which is then returned to the pool while still
/// holding the named lock. Subsequent calls block waiting on that leaked
/// lock and surface as the `Failed to acquire migration lock (timeout)`
/// error reported in issue #4585.
///
/// This routine acquires a single `PoolConnection`, runs `GET_LOCK` on it,
/// performs the DDL through the shared connection (the lock still
/// serialises concurrent migrators because they all queue on the same
/// named lock), and finally runs `RELEASE_LOCK` on the same held
/// connection before returning it to the pool. The result: no leaked
/// session-bound lock between consecutive `apply_migrations` /
/// `rollback_migrations` calls.
#[cfg(feature = "mysql")]
async fn ensure_schema_table_mysql(&self) -> super::Result<()> {
let pool = self.connection.into_mysql().ok_or_else(|| {
super::MigrationError::DatabaseError(crate::backends::DatabaseError::ConnectionError(
"MySQL backend unavailable when acquiring schema lock".to_string(),
))
})?;
let mut conn = pool.acquire().await.map_err(|e| {
super::MigrationError::DatabaseError(crate::backends::DatabaseError::ConnectionError(
format!("Failed to acquire MySQL connection for schema lock: {e}"),
))
})?;
// Acquire the named advisory lock on this specific session, with a
// 10 second timeout (matches the previous behaviour).
//
// `GET_LOCK` can return NULL on internal errors (e.g. interrupted by
// `KILL`), so we model the column as `Option<i64>` and treat NULL as
// a failed acquisition.
let locked: Option<i64> = sqlx::query_scalar("SELECT GET_LOCK('reinhardt_migrations', 10)")
.fetch_one(&mut *conn)
.await
.map_err(|e| {
super::MigrationError::DatabaseError(crate::backends::DatabaseError::QueryError(
format!("Failed to call GET_LOCK on MySQL: {e}"),
))
})?;
if locked != Some(1) {
return Err(super::MigrationError::DatabaseError(
crate::backends::DatabaseError::QueryError(
"Failed to acquire migration lock (timeout)".to_string(),
),
));
}
// Execute schema operations while the lock is held. The DDL runs on
// the pooled `DatabaseConnection`, but the named lock — owned by
// `conn` here — still serialises any concurrent migrator process
// because `GET_LOCK` is a global named lock, not a row/table lock.
let result = self.ensure_schema_table_internal().await;
// Always release the lock on the same session that acquired it,
// regardless of whether the DDL succeeded.
//
// `RELEASE_LOCK` returns a column rather than signalling failure via
// `Err`: `Some(1)` = released, `Some(0)` = not held by this session,
// `None` = lock did not exist. Anything other than `Some(1)` indicates
// the release silently no-op'd on the wrong session and would
// reintroduce a lock leak — surface that as a warning. Mirrors the
// `GET_LOCK` handling above.
let release_result: Result<Option<i64>, _> =
sqlx::query_scalar("SELECT RELEASE_LOCK('reinhardt_migrations')")
.fetch_one(&mut *conn)
.await;
match release_result {
Ok(Some(1)) => {}
Ok(other) => {
tracing::warn!(
result = ?other,
"RELEASE_LOCK did not release the MySQL migration advisory lock; \
the session will release it on connection close"
);
}
Err(e) => {
tracing::warn!(
error = %e,
"Failed to call RELEASE_LOCK for the MySQL migration advisory lock; \
the session will release it on connection close"
);
}
}
result
}
/// Check if an index exists in MySQL
///
/// This is a MySQL-specific helper to check if an index already exists.
/// PostgreSQL and SQLite handle `IF NOT EXISTS` correctly, but MySQL
/// returns an error even with `IF NOT EXISTS` if the index already exists.
async fn check_index_exists(&self, table: &str, index: &str) -> super::Result<bool> {
// Use EXISTS pattern similar to is_applied() method for reliable type handling
let query = "SELECT EXISTS(
SELECT 1 FROM information_schema.statistics
WHERE table_schema = DATABASE()
AND table_name = ?
AND index_name = ?
) as exists_flag";
let result = self
.connection
.fetch_one(query, vec![table.into(), index.into()])
.await
.map_err(super::MigrationError::DatabaseError)?;
// Try to get as bool first, then as i64 for databases that return int
// This pattern matches the is_applied() implementation
if let Ok(exists) = result.get::<bool>("exists_flag") {
Ok(exists)
} else if let Ok(exists_int) = result.get::<i64>("exists_flag") {
Ok(exists_int > 0)
} else {
Ok(false)
}
}
/// Acquire a database-level advisory lock for schema operations
///
/// This prevents concurrent schema modifications that could cause conflicts.
/// Different databases use different locking mechanisms:
/// - PostgreSQL: pg_advisory_lock() with hash of string
/// - MySQL: GET_LOCK() with timeout
/// - SQLite: No additional lock needed (handled by transaction isolation)
async fn acquire_schema_lock(&self) -> super::Result<()> {
use crate::backends::types::DatabaseType;
match self.connection.database_type() {
DatabaseType::Postgres => {
// PostgreSQL advisory lock using string hash
self.connection
.execute(
"SELECT pg_advisory_lock(hashtext('reinhardt_migrations'))",
vec![],
)
.await
.map_err(super::MigrationError::DatabaseError)?;
}
DatabaseType::Mysql => {
// MySQL GET_LOCK with 10 second timeout
let result = self
.connection
.fetch_one(
"SELECT GET_LOCK('reinhardt_migrations', 10) as locked",
vec![],
)
.await
.map_err(super::MigrationError::DatabaseError)?;
// Try to get the lock status as i64 or bool
let locked = if let Ok(val) = result.get::<i64>("locked") {
val == 1
} else {
result.get::<bool>("locked").unwrap_or_default()
};
if !locked {
return Err(super::MigrationError::DatabaseError(
crate::backends::DatabaseError::QueryError(
"Failed to acquire migration lock (timeout)".to_string(),
),
));
}
}
DatabaseType::Sqlite => {
// SQLite uses transaction isolation, no additional lock needed
}
}
Ok(())
}
/// Release the database-level advisory lock
///
/// Should be called after schema operations complete, even if they fail.
async fn release_schema_lock(&self) -> super::Result<()> {
use crate::backends::types::DatabaseType;
match self.connection.database_type() {
DatabaseType::Postgres => {
self.connection
.execute(
"SELECT pg_advisory_unlock(hashtext('reinhardt_migrations'))",
vec![],
)
.await
.map_err(super::MigrationError::DatabaseError)?;
}
DatabaseType::Mysql => {
self.connection
.execute("SELECT RELEASE_LOCK('reinhardt_migrations')", vec![])
.await
.map_err(super::MigrationError::DatabaseError)?;
}
DatabaseType::Sqlite => {
// SQLite uses transaction isolation, no explicit unlock needed
}
}
Ok(())
}
/// Internal implementation of ensure_schema_table without locking
///
/// This is called by ensure_schema_table() after acquiring the lock.
async fn ensure_schema_table_internal(&self) -> super::Result<()> {
use crate::backends::types::DatabaseType;
use reinhardt_query::prelude::{
Alias, ColumnDef, Expr, MySqlQueryBuilder, PostgresQueryBuilder, Query,
QueryStatementBuilder, SqliteQueryBuilder,
};
// Build SQL using appropriate query builder based on database type
// Scope stmt to ensure it's dropped before await
let (create_table_sql, create_index_sql) = {
let create_table_stmt = Query::create_table()
.table(Alias::new("reinhardt_migrations"))
.if_not_exists()
.col(
ColumnDef::new("id")
.integer()
.not_null(true)
.auto_increment(true)
.primary_key(true),
)
.col(ColumnDef::new("app").string_len(255).not_null(true))
.col(ColumnDef::new("name").string_len(255).not_null(true))
.col(
ColumnDef::new("applied")
.timestamp()
.not_null(true)
.default(Expr::current_timestamp().into_simple_expr()),
)
.to_owned();
let create_index_stmt = Query::create_index()
.if_not_exists()
.name("reinhardt_migrations_app_name_unique")
.table(Alias::new("reinhardt_migrations"))
.col(Alias::new("app"))
.col(Alias::new("name"))
.unique()
.to_owned();
match self.connection.database_type() {
DatabaseType::Postgres => (
create_table_stmt.to_string(PostgresQueryBuilder),
create_index_stmt.to_string(PostgresQueryBuilder),
),
DatabaseType::Mysql => (
create_table_stmt.to_string(MySqlQueryBuilder),
create_index_stmt.to_string(MySqlQueryBuilder),
),
DatabaseType::Sqlite => (
create_table_stmt.to_string(SqliteQueryBuilder),
create_index_stmt.to_string(SqliteQueryBuilder),
),
}
}; // stmts are dropped here, before await
// Create table
self.connection
.execute(&create_table_sql, vec![])
.await
.map_err(super::MigrationError::DatabaseError)?;
// Create unique index on (app, name)
// MySQL requires explicit check because IF NOT EXISTS doesn't work for indexes
if self.connection.database_type() == DatabaseType::Mysql {
let index_exists = self
.check_index_exists(
"reinhardt_migrations",
"reinhardt_migrations_app_name_unique",
)
.await?;
if !index_exists {
self.connection
.execute(&create_index_sql, vec![])
.await
.map_err(super::MigrationError::DatabaseError)?;
}
} else {
// PostgreSQL, SQLite handle IF NOT EXISTS correctly
self.connection
.execute(&create_index_sql, vec![])
.await
.map_err(super::MigrationError::DatabaseError)?;
}
Ok(())
}
/// Check if a migration has been applied
///
/// # Examples
///
/// ```no_run
/// use reinhardt_db::migrations::recorder::DatabaseMigrationRecorder;
/// use reinhardt_db::backends::DatabaseConnection;
///
/// # async fn example() {
/// // For doctest purposes, using mock connection (URL is ignored in current implementation)
/// let connection = DatabaseConnection::connect_postgres("postgres://localhost/mydb").await.unwrap();
/// let recorder = DatabaseMigrationRecorder::new(connection);
/// recorder.ensure_schema_table().await.unwrap();
///
/// let is_applied = recorder.is_applied("myapp", "0001_initial").await.unwrap();
/// assert!(!is_applied); // Initially not applied
/// # }
/// # tokio::runtime::Runtime::new().unwrap().block_on(example());
/// ```
pub async fn is_applied(&self, app: &str, name: &str) -> super::Result<bool> {
use crate::backends::types::DatabaseType;
use reinhardt_query::prelude::{
Alias, Expr, ExprTrait, MySqlQueryBuilder, PostgresQueryBuilder, Query,
QueryStatementBuilder, SqliteQueryBuilder,
};
// Build SELECT EXISTS query using reinhardt-query
let subquery = Query::select()
.expr(Expr::value(1))
.from(Alias::new("reinhardt_migrations"))
.and_where(Expr::col(Alias::new("app")).eq(app))
.and_where(Expr::col(Alias::new("name")).eq(name))
.to_owned();
let stmt = Query::select()
.expr_as(Expr::exists(subquery), Alias::new("exists_flag"))
.to_owned();
let sql = match self.connection.database_type() {
DatabaseType::Postgres => stmt.to_string(PostgresQueryBuilder),
DatabaseType::Mysql => stmt.to_string(MySqlQueryBuilder),
DatabaseType::Sqlite => stmt.to_string(SqliteQueryBuilder),
};
let rows = self
.connection
.fetch_all(&sql, vec![])
.await
.map_err(super::MigrationError::DatabaseError)?;
if rows.is_empty() {
return Ok(false);
}
let row = &rows[0];
// Try to get as bool first, then as i64 for databases that return int
if let Ok(exists) = row.get::<bool>("exists_flag") {
Ok(exists)
} else if let Ok(exists_int) = row.get::<i64>("exists_flag") {
Ok(exists_int > 0)
} else {
Ok(false)
}
}
/// Record that a migration has been applied
///
/// # Examples
///
/// ```no_run
/// use reinhardt_db::migrations::recorder::DatabaseMigrationRecorder;
/// use reinhardt_db::backends::DatabaseConnection;
///
/// # async fn example() {
/// // For doctest purposes, using mock connection (URL is ignored in current implementation)
/// let connection = DatabaseConnection::connect_postgres("postgres://localhost/mydb").await.unwrap();
/// let recorder = DatabaseMigrationRecorder::new(connection);
/// recorder.ensure_schema_table().await.unwrap();
///
/// recorder.record_applied("myapp", "0001_initial").await.unwrap();
/// // Verify migration was recorded
/// let is_applied = recorder.is_applied("myapp", "0001_initial").await.unwrap();
/// assert!(is_applied);
/// # }
/// # tokio::runtime::Runtime::new().unwrap().block_on(example());
/// ```
pub async fn record_applied(&self, app: &str, name: &str) -> super::Result<()> {
use crate::backends::types::DatabaseType;
use reinhardt_query::prelude::{
Alias, MySqlQueryBuilder, PostgresQueryBuilder, Query, QueryStatementBuilder,
SqliteQueryBuilder,
};
// Build INSERT query using reinhardt-query
let now = Utc::now().format("%Y-%m-%d %H:%M:%S").to_string();
let stmt = Query::insert()
.into_table(Alias::new("reinhardt_migrations"))
.columns([Alias::new("app"), Alias::new("name"), Alias::new("applied")])
.values_panic([app.to_string(), name.to_string(), now])
.to_owned();
// Add conflict resolution for concurrent execution.
// Use to_string() to inline values directly into SQL, avoiding parameter
// binding since execute() is called with empty params.
let sql = match self.connection.database_type() {
DatabaseType::Postgres => {
// PostgreSQL: ON CONFLICT DO NOTHING
let base_sql = stmt.to_string(PostgresQueryBuilder::new());
format!("{} ON CONFLICT (app, name) DO NOTHING", base_sql)
}
DatabaseType::Mysql => {
// MySQL: INSERT IGNORE
let base_sql = stmt.to_string(MySqlQueryBuilder::new());
base_sql.replacen("INSERT", "INSERT IGNORE", 1)
}
DatabaseType::Sqlite => {
// SQLite: INSERT OR IGNORE
let base_sql = stmt.to_string(SqliteQueryBuilder::new());
base_sql.replacen("INSERT", "INSERT OR IGNORE", 1)
}
};
self.connection
.execute(&sql, vec![])
.await
.map_err(super::MigrationError::DatabaseError)?;
Ok(())
}
/// Get all applied migrations
///
/// # Examples
///
/// ```no_run
/// use reinhardt_db::migrations::recorder::DatabaseMigrationRecorder;
/// use reinhardt_db::backends::DatabaseConnection;
///
/// # async fn example() {
/// // For doctest purposes, using mock connection (URL is ignored in current implementation)
/// let connection = DatabaseConnection::connect_postgres("postgres://localhost/mydb").await.unwrap();
/// let recorder = DatabaseMigrationRecorder::new(connection);
/// recorder.ensure_schema_table().await.unwrap();
///
/// let migrations = recorder.get_applied_migrations().await.unwrap();
/// assert!(migrations.is_empty()); // Initially no migrations applied
/// # }
/// # tokio::runtime::Runtime::new().unwrap().block_on(example());
/// ```
pub async fn get_applied_migrations(&self) -> super::Result<Vec<MigrationRecord>> {
use crate::backends::types::DatabaseType;
use reinhardt_query::prelude::{
Alias, MySqlQueryBuilder, Order, PostgresQueryBuilder, Query, QueryStatementBuilder,
SqliteQueryBuilder,
};
// Build SELECT query using reinhardt-query
let stmt = Query::select()
.columns([Alias::new("app"), Alias::new("name"), Alias::new("applied")])
.from(Alias::new("reinhardt_migrations"))
.order_by(Alias::new("applied"), Order::Asc)
.to_owned();
let sql = match self.connection.database_type() {
DatabaseType::Postgres => stmt.to_string(PostgresQueryBuilder),
DatabaseType::Mysql => stmt.to_string(MySqlQueryBuilder),
DatabaseType::Sqlite => stmt.to_string(SqliteQueryBuilder),
};
let rows = self
.connection
.fetch_all(&sql, vec![])
.await
.map_err(super::MigrationError::DatabaseError)?;
let db_type = self.connection.database_type();
let mut records = Vec::new();
for row in rows {
let app: String = row
.get("app")
.map_err(super::MigrationError::DatabaseError)?;
let name: String = row
.get("name")
.map_err(super::MigrationError::DatabaseError)?;
// Parse timestamp from database
// SQLite stores CURRENT_TIMESTAMP as string "YYYY-MM-DD HH:MM:SS"
// PostgreSQL and MySQL return proper DateTime types
let applied: DateTime<Utc> = match db_type {
DatabaseType::Sqlite => {
let applied_str: String = row
.get("applied")
.map_err(super::MigrationError::DatabaseError)?;
// Parse SQLite's CURRENT_TIMESTAMP format (no timezone info, assume UTC)
chrono::NaiveDateTime::parse_from_str(&applied_str, "%Y-%m-%d %H:%M:%S")
.map(|naive| naive.and_utc())
.map_err(|e| {
super::MigrationError::DatabaseError(
crate::backends::DatabaseError::TypeError(format!(
"Failed to parse SQLite timestamp '{}': {}",
applied_str, e
)),
)
})?
}
_ => row
.get("applied")
.map_err(super::MigrationError::DatabaseError)?,
};
records.push(MigrationRecord { app, name, applied });
}
Ok(records)
}
/// Unapply a migration (remove from records)
///
/// Used when rolling back migrations.
pub async fn unapply(&self, app: &str, name: &str) -> super::Result<()> {
use crate::backends::types::DatabaseType;
use reinhardt_query::prelude::{
Alias, Expr, ExprTrait, MySqlQueryBuilder, PostgresQueryBuilder, Query,
QueryStatementBuilder, SqliteQueryBuilder,
};
// Build DELETE query using reinhardt-query
let stmt = Query::delete()
.from_table(Alias::new("reinhardt_migrations"))
.and_where(Expr::col(Alias::new("app")).eq(app))
.and_where(Expr::col(Alias::new("name")).eq(name))
.to_owned();
let sql = match self.connection.database_type() {
DatabaseType::Postgres => stmt.to_string(PostgresQueryBuilder),
DatabaseType::Mysql => stmt.to_string(MySqlQueryBuilder),
DatabaseType::Sqlite => stmt.to_string(SqliteQueryBuilder),
};
self.connection
.execute(&sql, vec![])
.await
.map_err(super::MigrationError::DatabaseError)?;
Ok(())
}
/// Get all applied migrations for a specific app
///
/// Returns migrations sorted by applied timestamp in ascending order.
///
/// # Examples
///
/// ```no_run
/// use reinhardt_db::migrations::recorder::DatabaseMigrationRecorder;
/// use reinhardt_db::backends::DatabaseConnection;
///
/// # async fn example() {
/// let connection = DatabaseConnection::connect_postgres("postgres://localhost/mydb").await.unwrap();
/// let recorder = DatabaseMigrationRecorder::new(connection);
/// recorder.ensure_schema_table().await.unwrap();
///
/// let migrations = recorder.get_applied_for_app("myapp").await.unwrap();
/// assert!(migrations.is_empty()); // Initially no migrations applied
/// # }
/// # tokio::runtime::Runtime::new().unwrap().block_on(example());
/// ```
pub async fn get_applied_for_app(&self, app: &str) -> super::Result<Vec<MigrationRecord>> {
use crate::backends::types::DatabaseType;
use reinhardt_query::prelude::{
Alias, Expr, ExprTrait, MySqlQueryBuilder, Order, PostgresQueryBuilder, Query,
QueryStatementBuilder, SqliteQueryBuilder,
};
// Build SELECT query using reinhardt-query with app filter
let stmt = Query::select()
.columns([Alias::new("app"), Alias::new("name"), Alias::new("applied")])
.from(Alias::new("reinhardt_migrations"))
.and_where(Expr::col(Alias::new("app")).eq(app))
.order_by(Alias::new("applied"), Order::Asc)
.to_owned();
let sql = match self.connection.database_type() {
DatabaseType::Postgres => stmt.to_string(PostgresQueryBuilder),
DatabaseType::Mysql => stmt.to_string(MySqlQueryBuilder),
DatabaseType::Sqlite => stmt.to_string(SqliteQueryBuilder),
};
let rows = self
.connection
.fetch_all(&sql, vec![])
.await
.map_err(super::MigrationError::DatabaseError)?;
let db_type = self.connection.database_type();
let mut records = Vec::new();
for row in rows {
let app_val: String = row
.get("app")
.map_err(super::MigrationError::DatabaseError)?;
let name: String = row
.get("name")
.map_err(super::MigrationError::DatabaseError)?;
// Parse timestamp from database
let applied: DateTime<Utc> = match db_type {
DatabaseType::Sqlite => {
let applied_str: String = row
.get("applied")
.map_err(super::MigrationError::DatabaseError)?;
chrono::NaiveDateTime::parse_from_str(&applied_str, "%Y-%m-%d %H:%M:%S")
.map(|naive| naive.and_utc())
.map_err(|e| {
super::MigrationError::DatabaseError(
crate::backends::DatabaseError::TypeError(format!(
"Failed to parse SQLite timestamp '{}': {}",
applied_str, e
)),
)
})?
}
_ => row
.get("applied")
.map_err(super::MigrationError::DatabaseError)?,
};
records.push(MigrationRecord {
app: app_val,
name,
applied,
});
}
Ok(records)
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::Utc;
#[test]
fn test_migration_recorder_creation() {
let recorder = MigrationRecorder::new();
assert_eq!(recorder.get_applied_migrations().len(), 0);
}
#[test]
fn test_record_applied() {
let mut recorder = MigrationRecorder::new();
recorder.record_applied("auth", "0001_initial");
assert_eq!(recorder.get_applied_migrations().len(), 1);
assert!(recorder.is_applied("auth", "0001_initial"));
}
#[test]
fn test_is_applied() {
let mut recorder = MigrationRecorder::new();
assert!(!recorder.is_applied("auth", "0001_initial"));
recorder.record_applied("auth", "0001_initial");
assert!(recorder.is_applied("auth", "0001_initial"));
assert!(!recorder.is_applied("auth", "0002_add_field"));
}
#[test]
fn test_get_applied_migrations() {
let mut recorder = MigrationRecorder::new();
recorder.record_applied("auth", "0001_initial");
recorder.record_applied("users", "0001_initial");
recorder.record_applied("auth", "0002_add_field");
let migrations = recorder.get_applied_migrations();
assert_eq!(migrations.len(), 3);
// Verify all migrations were recorded
assert!(
migrations
.iter()
.any(|m| m.app == "auth" && m.name == "0001_initial")
);
assert!(
migrations
.iter()
.any(|m| m.app == "users" && m.name == "0001_initial")
);
assert!(
migrations
.iter()
.any(|m| m.app == "auth" && m.name == "0002_add_field")
);
}
#[test]
fn test_migration_record_contains_timestamp() {
let mut recorder = MigrationRecorder::new();
let before = Utc::now();
recorder.record_applied("auth", "0001_initial");
let after = Utc::now();
let migrations = recorder.get_applied_migrations();
assert_eq!(migrations.len(), 1);
let record = &migrations[0];
// Check timestamp is within expected range
assert!(record.applied >= before);
assert!(record.applied <= after);
}
#[test]
fn test_multiple_apps_migrations() {
let mut recorder = MigrationRecorder::new();
recorder.record_applied("auth", "0001_initial");
recorder.record_applied("auth", "0002_add_field");
recorder.record_applied("users", "0001_initial");
recorder.record_applied("posts", "0001_initial");
assert!(recorder.is_applied("auth", "0001_initial"));
assert!(recorder.is_applied("auth", "0002_add_field"));
assert!(recorder.is_applied("users", "0001_initial"));
assert!(recorder.is_applied("posts", "0001_initial"));
assert!(!recorder.is_applied("comments", "0001_initial"));
}
#[tokio::test]
async fn test_async_record_applied() {
let mut recorder = MigrationRecorder::new();
recorder
.record_applied_async(&(), "auth", "0001_initial")
.await
.unwrap();
assert!(recorder.is_applied("auth", "0001_initial"));
}
#[tokio::test]
async fn test_async_is_applied() {
let mut recorder = MigrationRecorder::new();
recorder.record_applied("auth", "0001_initial");
let result = recorder
.is_applied_async(&(), "auth", "0001_initial")
.await
.unwrap();
assert!(result);
let result_not_applied = recorder
.is_applied_async(&(), "auth", "0002_add_field")
.await
.unwrap();
assert!(!result_not_applied);
}
#[tokio::test]
async fn test_ensure_schema_table_async() {
let recorder = MigrationRecorder::new();
let result = recorder.ensure_schema_table_async(&()).await;
assert!(result.is_ok());
}
}