oneiriq-surql 0.2.2

Code-first database toolkit for SurrealDB - schema definitions, migrations, query building, and typed CRUD (Rust port of oneiriq-surql). Published as the `oneiriq-surql` crate; imported as `use surql::...`.
Documentation
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
//! Migration execution engine.
//!
//! Port of `surql/migration/executor.py`. Runs individual [`Migration`]
//! definitions against a live [`DatabaseClient`] inside a
//! [`Transaction`] (client-side buffered BEGIN/COMMIT) and records the
//! outcome in the [`MigrationHistory`] table.
//!
//! All items here require the `client` cargo feature.
//!
//! ## Deviations from Python
//!
//! * The Python implementation chooses between issuing raw `BEGIN` /
//!   `COMMIT` / `CANCEL` statements (remote) and running outside a
//!   transaction (embedded). The Rust port always uses
//!   [`Transaction`], which buffers statements client-side and flushes
//!   them as a single atomic `BEGIN…COMMIT` request.
//! * `get_migration_status` returns a structured
//!   [`MigrationStatusReport`] (total / applied / pending) instead of a
//!   flat list of [`MigrationStatus`].
//! * All arguments that the Python API accepts as a `list[Migration]`
//!   are replaced by a `migrations_dir: &Path`: the Rust runtime
//!   re-discovers migrations from disk at each call, matching the
//!   "migrations on disk" convention of the port.

use std::path::Path;
use std::time::Instant;

use chrono::Utc;

use crate::connection::{DatabaseClient, Transaction};
use crate::error::{Result, SurqlError};
use crate::migration::discovery::discover_migrations;
use crate::migration::history::{
    ensure_migration_table, get_applied_migrations as history_get_applied, is_migration_applied,
    record_migration, remove_migration_record,
};
use crate::migration::models::{
    Migration, MigrationDirection, MigrationHistory, MigrationPlan, MigrationState, MigrationStatus,
};

/// Aggregate status of a migrations directory relative to the database.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MigrationStatusReport {
    /// Total migrations discovered on disk.
    pub total: usize,
    /// Migrations that have been applied to the database.
    pub applied: Vec<MigrationStatus>,
    /// Migrations that have not yet been applied.
    pub pending: Vec<MigrationStatus>,
}

impl MigrationStatusReport {
    /// Total applied count (convenience).
    pub fn applied_count(&self) -> usize {
        self.applied.len()
    }

    /// Total pending count (convenience).
    pub fn pending_count(&self) -> usize {
        self.pending.len()
    }
}

/// Options controlling a [`migrate_up`] run.
#[derive(Debug, Clone, Default)]
pub struct MigrateUpOptions {
    /// Apply at most this many pending migrations (`None` = apply all).
    pub steps: Option<usize>,
}

/// Execute a single migration in the requested direction.
///
/// Runs the migration's SurrealQL statements inside a
/// [`Transaction`]; on success records (or removes, when rolling back)
/// the migration from the history table.
///
/// Returns the resulting [`MigrationStatus`], including timing and, on
/// failure, the error message captured during execution.
///
/// # Errors
///
/// Returns [`SurqlError::MigrationExecution`] when the transaction
/// itself cannot be begun or the history update fails. Per-statement
/// failures are reported via a [`MigrationStatus`] with
/// [`MigrationState::Failed`] and a populated `error`.
pub async fn execute_migration(
    client: &DatabaseClient,
    migration: &Migration,
    direction: MigrationDirection,
) -> Result<MigrationStatus> {
    let statements: &[String] = match direction {
        MigrationDirection::Up => &migration.up,
        MigrationDirection::Down => &migration.down,
    };

    let start = Instant::now();

    let mut tx = Transaction::begin(client)
        .await
        .map_err(|e| SurqlError::MigrationExecution {
            reason: format!("failed to begin transaction for {}: {e}", migration.version),
        })?;

    for (idx, statement) in statements.iter().enumerate() {
        if let Err(err) = tx.execute(statement).await {
            let _ = tx.rollback().await;
            return Ok(MigrationStatus {
                migration: migration.clone(),
                state: MigrationState::Failed,
                applied_at: None,
                error: Some(format!("statement {idx} failed: {err}")),
            });
        }
    }

    if let Err(err) = tx.commit().await {
        return Ok(MigrationStatus {
            migration: migration.clone(),
            state: MigrationState::Failed,
            applied_at: None,
            error: Some(format!("commit failed: {err}")),
        });
    }

    let applied_at = Utc::now();
    let execution_time_ms = u64::try_from(start.elapsed().as_millis()).ok();

    match direction {
        MigrationDirection::Up => {
            let entry = MigrationHistory {
                version: migration.version.clone(),
                description: migration.description.clone(),
                applied_at,
                checksum: migration.checksum.clone().unwrap_or_default(),
                execution_time_ms,
            };
            record_migration(client, &entry)
                .await
                .map_err(|e| SurqlError::MigrationExecution {
                    reason: format!("failed to record migration {}: {e}", migration.version),
                })?;
        }
        MigrationDirection::Down => {
            remove_migration_record(client, &migration.version)
                .await
                .map_err(|e| SurqlError::MigrationExecution {
                    reason: format!(
                        "failed to remove migration record {}: {e}",
                        migration.version
                    ),
                })?;
        }
    }

    let state = match direction {
        MigrationDirection::Up => MigrationState::Applied,
        MigrationDirection::Down => MigrationState::Pending,
    };

    Ok(MigrationStatus {
        migration: migration.clone(),
        state,
        applied_at: Some(applied_at),
        error: None,
    })
}

/// Apply all pending migrations found in `migrations_dir`.
///
/// Honours [`MigrateUpOptions::steps`] to cap the number of migrations
/// applied. Returns one [`MigrationStatus`] per migration that was
/// attempted.
///
/// Execution stops at the first failure; the failed migration's status
/// is included in the returned vector but subsequent migrations are
/// not attempted.
///
/// # Errors
///
/// Returns [`SurqlError::MigrationExecution`] or
/// [`SurqlError::MigrationDiscovery`] if the directory cannot be
/// scanned or the history table cannot be ensured.
pub async fn migrate_up(
    client: &DatabaseClient,
    migrations_dir: &Path,
    opts: MigrateUpOptions,
) -> Result<Vec<MigrationStatus>> {
    ensure_migration_table(client).await?;
    let pending = get_pending_migrations(client, migrations_dir).await?;
    let to_apply: Vec<Migration> = match opts.steps {
        Some(n) => pending.into_iter().take(n).collect(),
        None => pending,
    };

    let mut out = Vec::with_capacity(to_apply.len());
    for migration in to_apply {
        let status = execute_migration(client, &migration, MigrationDirection::Up).await?;
        let failed = status.state == MigrationState::Failed;
        out.push(status);
        if failed {
            break;
        }
    }
    Ok(out)
}

/// Roll back the last `steps` applied migrations.
///
/// Walks the applied migrations in reverse chronological order and
/// runs each `down` body inside its own transaction. Stops at the
/// first failure (the failed status is included in the return value).
///
/// # Errors
///
/// Returns [`SurqlError::MigrationExecution`] on history or discovery
/// failure.
pub async fn migrate_down(
    client: &DatabaseClient,
    migrations_dir: &Path,
    steps: u32,
) -> Result<Vec<MigrationStatus>> {
    if steps == 0 {
        return Ok(Vec::new());
    }
    ensure_migration_table(client).await?;
    let mut applied = get_applied_migrations_ordered(client, migrations_dir).await?;
    applied.reverse();

    let take = usize::try_from(steps)
        .unwrap_or(usize::MAX)
        .min(applied.len());
    let to_roll = &applied[..take];

    // Join applied history metadata with on-disk migrations by version.
    let all_on_disk = discover_migrations(migrations_dir)?;
    let by_version: std::collections::BTreeMap<String, Migration> = all_on_disk
        .into_iter()
        .map(|m| (m.version.clone(), m))
        .collect();

    let mut out = Vec::with_capacity(to_roll.len());
    for history in to_roll {
        let Some(migration) = by_version.get(&history.version) else {
            out.push(MigrationStatus {
                migration: Migration {
                    version: history.version.clone(),
                    description: history.description.clone(),
                    path: std::path::PathBuf::new(),
                    up: Vec::new(),
                    down: Vec::new(),
                    checksum: Some(history.checksum.clone()),
                    depends_on: Vec::new(),
                },
                state: MigrationState::Failed,
                applied_at: None,
                error: Some(format!(
                    "cannot roll back {}: migration file missing on disk",
                    history.version
                )),
            });
            break;
        };
        let status = execute_migration(client, migration, MigrationDirection::Down).await?;
        let failed = status.state == MigrationState::Failed;
        out.push(status);
        if failed {
            break;
        }
    }
    Ok(out)
}

/// List migrations that have not yet been applied, sorted by version.
///
/// # Errors
///
/// Returns [`SurqlError::MigrationExecution`] on discovery or history
/// failure.
pub async fn get_pending_migrations(
    client: &DatabaseClient,
    migrations_dir: &Path,
) -> Result<Vec<Migration>> {
    ensure_migration_table(client).await?;
    let on_disk = discover_migrations(migrations_dir)?;
    let applied = history_get_applied(client).await?;
    let applied_set: std::collections::BTreeSet<String> =
        applied.iter().map(|m| m.version.clone()).collect();

    let mut pending: Vec<Migration> = on_disk
        .into_iter()
        .filter(|m| !applied_set.contains(&m.version))
        .collect();
    pending.sort_by(|a, b| a.version.cmp(&b.version));
    Ok(pending)
}

/// Return every applied migration history row in `applied_at` order.
///
/// # Errors
///
/// Returns [`SurqlError::MigrationExecution`] if the history query
/// fails.
pub async fn get_applied_migrations_ordered(
    client: &DatabaseClient,
    _migrations_dir: &Path,
) -> Result<Vec<MigrationHistory>> {
    history_get_applied(client)
        .await
        .map_err(|e| SurqlError::MigrationExecution {
            reason: format!("failed to read applied migrations: {e}"),
        })
}

/// Compute an applied / pending status report for a migrations directory.
///
/// # Errors
///
/// Returns [`SurqlError::MigrationExecution`] if discovery or the
/// history query fail.
pub async fn get_migration_status(
    client: &DatabaseClient,
    migrations_dir: &Path,
) -> Result<MigrationStatusReport> {
    ensure_migration_table(client).await?;
    let on_disk = discover_migrations(migrations_dir)?;
    let applied_history = history_get_applied(client).await?;
    let applied_map: std::collections::BTreeMap<String, &MigrationHistory> = applied_history
        .iter()
        .map(|h| (h.version.clone(), h))
        .collect();

    let mut applied = Vec::new();
    let mut pending = Vec::new();
    for migration in on_disk.iter().cloned() {
        if let Some(history) = applied_map.get(&migration.version) {
            applied.push(MigrationStatus {
                migration,
                state: MigrationState::Applied,
                applied_at: Some(history.applied_at),
                error: None,
            });
        } else {
            pending.push(MigrationStatus {
                migration,
                state: MigrationState::Pending,
                applied_at: None,
                error: None,
            });
        }
    }
    applied.sort_by(|a, b| a.migration.version.cmp(&b.migration.version));
    pending.sort_by(|a, b| a.migration.version.cmp(&b.migration.version));

    Ok(MigrationStatusReport {
        total: on_disk.len(),
        applied,
        pending,
    })
}

/// Build the next migration plan (all pending migrations, forward).
///
/// # Errors
///
/// See [`get_pending_migrations`].
pub async fn create_migration_plan(
    client: &DatabaseClient,
    migrations_dir: &Path,
) -> Result<MigrationPlan> {
    let pending = get_pending_migrations(client, migrations_dir).await?;
    Ok(MigrationPlan {
        migrations: pending,
        direction: MigrationDirection::Up,
    })
}

/// Execute a [`MigrationPlan`] end-to-end.
///
/// For an `Up` plan, migrations are applied in ascending version order.
/// For a `Down` plan, they are applied in reverse order. Execution
/// stops at the first failure; the failed status is included in the
/// return value.
///
/// # Errors
///
/// Returns [`SurqlError::MigrationExecution`] if the history table
/// cannot be ensured.
pub async fn execute_migration_plan(
    client: &DatabaseClient,
    plan: MigrationPlan,
) -> Result<Vec<MigrationStatus>> {
    ensure_migration_table(client).await?;
    let mut migrations = plan.migrations;
    migrations.sort_by(|a, b| a.version.cmp(&b.version));
    if plan.direction == MigrationDirection::Down {
        migrations.reverse();
    }
    let mut out = Vec::with_capacity(migrations.len());
    for migration in migrations {
        let status = execute_migration(client, &migration, plan.direction).await?;
        let failed = status.state == MigrationState::Failed;
        out.push(status);
        if failed {
            break;
        }
    }
    Ok(out)
}

/// Validate a migrations directory for duplicate versions and broken
/// dependencies.
///
/// Returns a list of human-readable error messages. An empty list
/// means the directory is self-consistent.
///
/// # Errors
///
/// Returns [`SurqlError::MigrationDiscovery`] if the directory cannot
/// be read.
pub async fn validate_migrations(migrations_dir: &Path) -> Result<Vec<String>> {
    let migrations = discover_migrations(migrations_dir)?;
    let mut errors = Vec::new();

    let mut seen: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
    for m in &migrations {
        *seen.entry(m.version.clone()).or_insert(0) += 1;
    }
    for (version, count) in &seen {
        if *count > 1 {
            errors.push(format!("duplicate migration version: {version} (x{count})"));
        }
    }

    let versions: std::collections::BTreeSet<String> =
        migrations.iter().map(|m| m.version.clone()).collect();
    for m in &migrations {
        for dep in &m.depends_on {
            if !versions.contains(dep) {
                errors.push(format!(
                    "migration {} depends on missing migration {dep}",
                    m.version
                ));
            }
        }
    }

    Ok(errors)
}

/// Verify via the history table whether a migration is applied.
///
/// Convenience wrapper over [`is_migration_applied`] for use by the
/// rollback layer.
///
/// # Errors
///
/// See [`is_migration_applied`].
pub async fn version_is_applied(client: &DatabaseClient, version: &str) -> Result<bool> {
    is_migration_applied(client, version).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;
    use tempfile::tempdir;

    fn write_migration(dir: &Path, filename: &str, body: &str) {
        std::fs::write(dir.join(filename), body).unwrap();
    }

    #[tokio::test]
    async fn validate_migrations_detects_duplicates() {
        let tmp = tempdir().unwrap();
        write_migration(
            tmp.path(),
            "20260101_000000_a.surql",
            "-- @metadata\n-- version: v1\n-- description: a\n-- @up\nDEFINE TABLE t1;\n-- @down\nREMOVE TABLE t1;\n",
        );
        write_migration(
            tmp.path(),
            "20260102_000000_b.surql",
            "-- @metadata\n-- version: v1\n-- description: b\n-- @up\nDEFINE TABLE t2;\n-- @down\nREMOVE TABLE t2;\n",
        );
        let errors = validate_migrations(tmp.path()).await.unwrap();
        assert!(errors.iter().any(|e| e.contains("duplicate")));
    }

    #[tokio::test]
    async fn validate_migrations_detects_missing_dep() {
        let tmp = tempdir().unwrap();
        write_migration(
            tmp.path(),
            "20260101_000000_a.surql",
            "-- @metadata\n-- version: v1\n-- description: a\n-- depends_on: vX\n-- @up\nDEFINE TABLE t;\n-- @down\nREMOVE TABLE t;\n",
        );
        let errors = validate_migrations(tmp.path()).await.unwrap();
        assert!(errors.iter().any(|e| e.contains("missing migration vX")));
    }

    #[tokio::test]
    async fn validate_migrations_empty_dir_returns_empty_errors() {
        let tmp = tempdir().unwrap();
        let errors = validate_migrations(tmp.path()).await.unwrap();
        assert!(errors.is_empty());
    }

    #[test]
    fn migration_status_report_counts() {
        let report = MigrationStatusReport {
            total: 3,
            applied: vec![MigrationStatus {
                migration: Migration {
                    version: "v1".into(),
                    description: String::new(),
                    path: PathBuf::new(),
                    up: vec![],
                    down: vec![],
                    checksum: None,
                    depends_on: vec![],
                },
                state: MigrationState::Applied,
                applied_at: None,
                error: None,
            }],
            pending: Vec::new(),
        };
        assert_eq!(report.applied_count(), 1);
        assert_eq!(report.pending_count(), 0);
    }
}