toasty_core/schema/db/migration.rs
1/// A database migration generated from a [`diff::Schema`](super::super::diff::Schema) by a driver.
2///
3/// Currently only SQL migrations are supported. Multiple SQL statements
4/// within a single migration are separated by breakpoint markers
5/// (`-- #[toasty::breakpoint]`).
6///
7/// # Examples
8///
9/// ```ignore
10/// use toasty_core::schema::db::Migration;
11///
12/// let m = Migration::new_sql("CREATE TABLE users (id INTEGER PRIMARY KEY)".to_string());
13/// assert_eq!(m.statements(), vec!["CREATE TABLE users (id INTEGER PRIMARY KEY)"]);
14/// ```
15#[derive(Debug)]
16pub enum Migration {
17 /// A SQL migration containing one or more statements.
18 Sql(String),
19}
20
21impl Migration {
22 /// Creates a SQL migration from a single SQL string.
23 pub fn new_sql(sql: String) -> Self {
24 Migration::Sql(sql)
25 }
26
27 /// Creates a SQL migration from multiple SQL statements.
28 /// Statements are joined with `-- #[toasty::breakpoint]` markers.
29 pub fn new_sql_with_breakpoints<S: AsRef<str>>(statements: &[S]) -> Self {
30 let sql = statements
31 .iter()
32 .map(|s| s.as_ref())
33 .collect::<Vec<_>>()
34 .join("\n-- #[toasty::breakpoint]\n");
35 Migration::Sql(sql)
36 }
37
38 /// Returns individual SQL statements by splitting on breakpoint markers.
39 pub fn statements(&self) -> Vec<&str> {
40 match self {
41 Migration::Sql(sql) => sql.split("\n-- #[toasty::breakpoint]\n").collect(),
42 }
43 }
44}
45
46/// Metadata about a migration that has already been applied to a database.
47///
48/// Stores the unique migration ID assigned by the migration system.
49///
50/// # Examples
51///
52/// ```ignore
53/// use toasty_core::schema::db::AppliedMigration;
54///
55/// let applied = AppliedMigration::new(42);
56/// assert_eq!(applied.id(), 42);
57/// ```
58pub struct AppliedMigration {
59 id: u64,
60}
61
62impl AppliedMigration {
63 /// Creates a new `AppliedMigration` with the given ID.
64 pub fn new(id: u64) -> Self {
65 Self { id }
66 }
67
68 /// Returns the migration's unique ID.
69 pub fn id(&self) -> u64 {
70 self.id
71 }
72}