migra/
managers.rs

1use crate::errors::{DbKind, Error, MigraResult, StdResult};
2use crate::migration;
3
4/// Used to execute SQL.
5///
6/// Is a super trait for managers.
7pub trait BatchExecute {
8    /// Executes sql via original database client
9    fn batch_execute(&mut self, sql: &str) -> StdResult<()>;
10}
11
12/// Used to manage transaction in the database connection.
13pub trait ManageTransaction: BatchExecute {
14    /// Opens transaction in database connection.
15    fn begin_transaction(&mut self) -> MigraResult<()> {
16        self.batch_execute("BEGIN")
17            .map_err(|err| Error::db(err, DbKind::OpenTransaction))
18    }
19
20    /// Cancels (Rollbacks) transaction in database connection.
21    fn rollback_transaction(&mut self) -> MigraResult<()> {
22        self.batch_execute("ROLLBACK")
23            .map_err(|err| Error::db(err, DbKind::RollbackTransaction))
24    }
25
26    /// Apply (Commit) transaction in database connection.
27    fn commit_transaction(&mut self) -> MigraResult<()> {
28        self.batch_execute("COMMIT")
29            .map_err(|err| Error::db(err, DbKind::CommitTransaction))
30    }
31}
32
33/// Used to manage migrations in the database connection.
34pub trait ManageMigrations: BatchExecute {
35    /// Applies SQL. Similar to [`BatchExecute`], but returns migra [Error].
36    ///
37    /// [BatchExecute]: managers::BatchExecute
38    fn apply_sql(&mut self, sql: &str) -> MigraResult<()> {
39        self.batch_execute(sql)
40            .map_err(|err| Error::db(err, DbKind::ApplySql))
41    }
42
43    /// Creates migration table.
44    fn create_migrations_table(&mut self) -> MigraResult<()>;
45
46    /// Inserts new migration to table.
47    fn insert_migration(&mut self, name: &str) -> MigraResult<u64>;
48
49    /// Deletes migration from table.
50    fn delete_migration(&mut self, name: &str) -> MigraResult<u64>;
51
52    /// Get applied migrations from table.
53    fn get_applied_migrations(&mut self) -> MigraResult<migration::List>;
54
55    /// Applies SQL to upgrade database schema and inserts new migration to table.
56    ///
57    /// **Note:** Must be run in a transaction otherwise if the migration causes any
58    /// error the data in the database may be inconsistent.
59    fn run_upgrade_migration(&mut self, name: &str, content: &str) -> MigraResult<()> {
60        self.apply_sql(content)?;
61        self.insert_migration(name)?;
62        Ok(())
63    }
64
65    /// Applies SQL to downgrade database schema and deletes migration from table.
66    ///
67    /// **Note:** Must be run in a transaction otherwise if the migration causes any
68    /// error the data in the database may be inconsistent.
69    fn run_downgrade_migration(&mut self, name: &str, content: &str) -> MigraResult<()> {
70        self.apply_sql(content)?;
71        self.delete_migration(name)?;
72        Ok(())
73    }
74}