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
use crate::{MigrationError, MigrationFn, Result};
use tokio_postgres::{Client, Transaction};
use tracing::Instrument;
/// A registered migration.
pub struct Migration {
/// Version string, e.g. "2026-01-17-create-users"
pub version: &'static str,
/// Function name for debugging
pub name: &'static str,
/// The migration function
pub run: MigrationFn,
/// Source file path (CARGO_MANIFEST_DIR, file!())
pub source_file: (&'static str, &'static str),
}
impl Migration {
/// Get the resolved source file path.
///
/// This handles the complexity of `file!()` in workspace members, where
/// `file!()` returns a path relative to the workspace root (e.g.,
/// `examples/my-app-db/src/...`) while `CARGO_MANIFEST_DIR` is the
/// absolute path to the crate (e.g., `/path/to/workspace/examples/my-app-db`).
pub fn source_path(&self) -> std::path::PathBuf {
let (manifest_dir, file_path) = self.source_file;
let file_path = std::path::Path::new(file_path);
if file_path.is_absolute() {
return file_path.to_path_buf();
}
// Try manifest_dir + file_path first (works for non-workspace crates)
let full = std::path::Path::new(manifest_dir).join(file_path);
if full.exists() {
return full;
}
// file!() in workspace members includes the path from workspace root
// e.g., file!() = "examples/my-app-db/src/..." and manifest_dir ends with "examples/my-app-db"
// Strip the duplicated crate path portion
if let Some(crate_name) = std::path::Path::new(manifest_dir).file_name() {
let crate_name = crate_name.to_string_lossy();
let file_str = file_path.to_string_lossy();
if let Some(pos) = file_str.find(&*crate_name) {
let relative = &file_str[pos + crate_name.len()..];
let relative = relative.trim_start_matches('/');
let full = std::path::Path::new(manifest_dir).join(relative);
if full.exists() {
return full;
}
}
}
// Try walking up to workspace root
let mut workspace = std::path::Path::new(manifest_dir);
while let Some(parent) = workspace.parent() {
let candidate = parent.join(file_path);
if candidate.exists() {
return candidate;
}
workspace = parent;
}
// Last resort: return the combined path even if it doesn't exist
std::path::Path::new(manifest_dir).join(file_path)
}
}
/// Context passed to migration functions.
///
/// Wraps a database transaction, ensuring all migration operations are atomic.
pub struct MigrationContext<'a> {
tx: &'a Transaction<'a>,
}
impl<'a> MigrationContext<'a> {
pub fn new(tx: &'a Transaction<'a>) -> Self {
Self { tx }
}
/// Execute a SQL statement.
pub async fn execute(&self, sql: &str) -> Result<u64> {
let span = tracing::debug_span!(
"migration.execute",
sql = %sql,
affected = tracing::field::Empty,
);
let affected = self
.tx
.execute(sql, &[])
.instrument(span.clone())
.await
.map_err(|e| crate::Error::from_postgres_with_sql(e, sql))?;
span.record("affected", affected);
Ok(affected)
}
/// Execute a SQL statement with parameters.
pub async fn execute_params(
&self,
sql: &str,
params: &[&(dyn tokio_postgres::types::ToSql + Sync)],
) -> Result<u64> {
let span = tracing::debug_span!(
"migration.execute",
sql = %sql,
params = params.len(),
affected = tracing::field::Empty,
);
let affected = self
.tx
.execute(sql, params)
.instrument(span.clone())
.await
.map_err(|e| crate::Error::from_postgres_with_sql(e, sql))?;
span.record("affected", affected);
Ok(affected)
}
/// Run a backfill operation in batches until it returns 0 rows affected.
///
/// Note: Since we're in a transaction, all batches are part of the same
/// atomic operation. For very large backfills that need to commit
/// incrementally, consider breaking into multiple migrations.
pub async fn backfill<F, Fut>(&self, mut f: F) -> Result<u64>
where
F: FnMut(&Transaction<'a>) -> Fut,
Fut: std::future::Future<Output = Result<u64>>,
{
let mut total = 0u64;
loop {
let affected = f(self.tx).await?;
if affected == 0 {
break;
}
total += affected;
}
Ok(total)
}
/// Get the underlying transaction for complex operations.
pub fn transaction(&self) -> &Transaction<'a> {
self.tx
}
}
/// Runs migrations against a database.
pub struct MigrationRunner<'a> {
client: &'a mut Client,
}
impl<'a> MigrationRunner<'a> {
pub fn new(client: &'a mut Client) -> Self {
Self { client }
}
/// Get the total number of registered migrations.
pub fn total_defined() -> usize {
inventory::iter::<Migration>.into_iter().count()
}
/// Ensure the migrations tracking table exists.
pub async fn init(&self) -> Result<()> {
self.client
.execute(
"CREATE TABLE IF NOT EXISTS _dibs_migrations (
version TEXT PRIMARY KEY,
applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)",
&[],
)
.await?;
Ok(())
}
/// Get all applied migrations with their timestamps.
pub async fn applied(&self) -> Result<Vec<AppliedMigration>> {
let rows = self
.client
.query(
"SELECT version, applied_at FROM _dibs_migrations ORDER BY version",
&[],
)
.await?;
Ok(rows
.iter()
.map(|r| AppliedMigration {
version: r.get(0),
applied_at: r.get(1),
})
.collect())
}
/// Get all pending migrations (registered but not applied).
pub fn pending(&self, applied: &[AppliedMigration]) -> Vec<&'static Migration> {
let applied_versions: std::collections::HashSet<&str> =
applied.iter().map(|m| m.version.as_str()).collect();
let mut migrations: Vec<_> = inventory::iter::<Migration>
.into_iter()
.filter(|m| !applied_versions.contains(m.version))
.collect();
migrations.sort_by_key(|m| m.version);
migrations
}
/// Run all pending migrations.
///
/// Each migration runs in its own transaction. If a migration fails,
/// all its changes are rolled back and subsequent migrations are skipped.
///
/// Returns `MigrationError` on failure, which includes the exact source
/// location where the error occurred (captured via `#[track_caller]`).
pub async fn migrate(&mut self) -> std::result::Result<Vec<RanMigration>, MigrationError> {
self.init().await?;
let applied = self.applied().await?;
let pending = self.pending(&applied);
let mut ran = Vec::new();
for migration in pending {
let start = std::time::Instant::now();
// Each migration runs in its own transaction
let tx = self.client.transaction().await?;
let mut ctx = MigrationContext::new(&tx);
(migration.run)(&mut ctx).await?;
// Record the migration as applied (inside the same transaction)
tx.execute(
"INSERT INTO _dibs_migrations (version) VALUES ($1)",
&[&migration.version],
)
.await?;
// Commit the transaction
tx.commit().await?;
ran.push(RanMigration {
version: migration.version,
duration: start.elapsed(),
});
}
Ok(ran)
}
/// Get status of all migrations.
pub async fn status(&self) -> Result<Vec<MigrationStatus>> {
self.init().await?;
let applied = self.applied().await?;
let applied_versions: std::collections::HashSet<&str> =
applied.iter().map(|m| m.version.as_str()).collect();
let mut all: Vec<_> = inventory::iter::<Migration>
.into_iter()
.map(|m| MigrationStatus {
version: m.version,
name: m.name,
applied: applied_versions.contains(m.version),
source_path: m.source_path(),
})
.collect();
all.sort_by_key(|m| m.version);
Ok(all)
}
}
/// Status of a single migration.
pub struct MigrationStatus {
pub version: &'static str,
pub name: &'static str,
pub applied: bool,
pub source_path: std::path::PathBuf,
}
/// A migration that was already applied.
pub struct AppliedMigration {
pub version: String,
pub applied_at: chrono::DateTime<chrono::Utc>,
}
/// A migration that was just run.
pub struct RanMigration {
pub version: &'static str,
pub duration: std::time::Duration,
}