Skip to main content

diesel_async/
migrations.rs

1use diesel::migration::{Migration, MigrationVersion, Result};
2
3use crate::AsyncConnection;
4use crate::async_connection_wrapper::AsyncConnectionWrapper;
5
6/// A diesel-migration [`MigrationHarness`](diesel_migrations::MigrationHarness) to run migrations
7/// via an [`AsyncConnection`](crate::AsyncConnection)
8///
9/// Internally this harness is using [`tokio::task::block_in_place`] and [`AsyncConnectionWrapper`]
10/// to utilize sync Diesel's migration infrastructure. For most applications this shouldn't
11/// be problematic as migrations are usually run at application startup and most applications
12/// default to use the multithreaded tokio runtime. In turn this also means that you cannot use
13/// this migration harness if you use the current thread variant of the tokio runtime or if
14/// you run migrations in a very special setup (e.g by using [`tokio::select!`] or [`tokio::join!`]
15/// on a future produced by running the migrations). Consider manually construct a blocking task via
16/// [`tokio::task::spawn_blocking`] instead.
17///
18/// ## Example
19///
20/// ```no_run
21/// # include!("doctest_setup.rs");
22/// # async fn run_test() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>>{
23/// use diesel_async::AsyncMigrationHarness;
24/// use diesel_migrations::{FileBasedMigrations, MigrationHarness};
25///
26/// let mut connection = connection_no_data().await;
27///
28/// // Alternatively use `diesel_migrations::embed_migrations!()`
29/// // to get a list of migrations
30/// let migrations = FileBasedMigrations::find_migrations_directory()?;
31///
32/// let mut harness = AsyncMigrationHarness::new(connection);
33/// harness.run_pending_migrations(migrations)?;
34/// // get back the connection from the harness
35/// let connection = harness.into_inner();
36/// #      Ok(())
37/// # }
38/// # #[tokio::main]
39/// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
40/// #     run_test().await?;
41/// #     Ok(())
42/// # }
43/// ```
44///
45/// ## Example with pool
46///
47/// ```no_run
48/// # include!("doctest_setup.rs");
49/// # #[cfg(feature = "deadpool")]
50/// # use diesel_async::pooled_connection::AsyncDieselConnectionManager;
51/// #
52/// # #[cfg(all(feature = "postgres", feature = "deadpool"))]
53/// # fn get_config() -> AsyncDieselConnectionManager<diesel_async::AsyncPgConnection> {
54/// #     let db_url = database_url_from_env("PG_DATABASE_URL");
55/// let config = AsyncDieselConnectionManager::<diesel_async::AsyncPgConnection>::new(db_url);
56/// #     config
57/// #  }
58/// #
59/// # #[cfg(all(feature = "mysql", feature = "deadpool"))]
60/// # fn get_config() -> AsyncDieselConnectionManager<diesel_async::AsyncMysqlConnection> {
61/// #     let db_url = database_url_from_env("MYSQL_DATABASE_URL");
62/// #    let config = AsyncDieselConnectionManager::<diesel_async::AsyncMysqlConnection>::new(db_url);
63/// #     config
64/// #  }
65/// #
66/// # #[cfg(all(feature = "mariadb", feature = "deadpool"))]
67/// # fn get_config() -> AsyncDieselConnectionManager<diesel_async::AsyncMariadbConnection> {
68/// #     let db_url = database_url_from_env("MARIADB_DATABASE_URL");
69/// #    let config = AsyncDieselConnectionManager::<diesel_async::AsyncMariadbConnection>::new(db_url);
70/// #     config
71/// #  }
72/// #
73/// # #[cfg(all(feature = "sqlite", feature = "deadpool"))]
74/// # fn get_config() -> AsyncDieselConnectionManager<diesel_async::sync_connection_wrapper::SyncConnectionWrapper<diesel::SqliteConnection>> {
75/// #     let db_url = database_url_from_env("SQLITE_DATABASE_URL");
76/// #     let config = AsyncDieselConnectionManager::<diesel_async::sync_connection_wrapper::SyncConnectionWrapper<diesel::SqliteConnection>>::new(db_url);
77/// #     config
78/// # }
79/// # #[cfg(feature = "deadpool")]
80/// # async fn run_test() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>>{
81/// use diesel_async::pooled_connection::deadpool::Pool;
82/// use diesel_async::AsyncMigrationHarness;
83/// use diesel_migrations::{FileBasedMigrations, MigrationHarness};
84///
85/// // Alternatively use `diesel_migrations::embed_migrations!()`
86/// // to get a list of migrations
87/// let migrations = FileBasedMigrations::find_migrations_directory()?;
88///
89/// let pool = Pool::builder(get_config()).build()?;
90/// let mut harness = AsyncMigrationHarness::new(pool.get().await?);
91/// harness.run_pending_migrations(migrations)?;
92/// #      Ok(())
93/// # }
94///
95/// # #[cfg(not(feature = "deadpool"))]
96/// # async fn run_test() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>>
97/// # {
98/// #   Ok(())
99/// # }
100/// #
101/// # #[tokio::main]
102/// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
103/// #     run_test().await?;
104/// #     Ok(())
105/// # }
106/// ```
107pub struct AsyncMigrationHarness<C> {
108    conn: AsyncConnectionWrapper<C, crate::async_connection_wrapper::implementation::Tokio>,
109}
110
111impl<C> AsyncMigrationHarness<C>
112where
113    C: AsyncConnection,
114{
115    /// Construct a new `AsyncMigrationHarness` from a given connection
116    pub fn new(connection: C) -> Self {
117        Self {
118            conn: AsyncConnectionWrapper::from(connection),
119        }
120    }
121
122    /// Return the connection stored inside this instance of `AsyncMigrationHarness`
123    pub fn into_inner(self) -> C {
124        self.conn.into_inner()
125    }
126}
127
128impl<C> From<C> for AsyncMigrationHarness<C>
129where
130    C: AsyncConnection,
131{
132    fn from(value: C) -> Self {
133        AsyncMigrationHarness::new(value)
134    }
135}
136
137impl<C> diesel_migrations::MigrationHarness<C::Backend> for AsyncMigrationHarness<C>
138where
139    C: AsyncConnection,
140    AsyncConnectionWrapper<C, crate::async_connection_wrapper::implementation::Tokio>:
141        diesel::Connection<Backend = C::Backend> + diesel_migrations::MigrationHarness<C::Backend>,
142{
143    fn run_migration(
144        &mut self,
145        migration: &dyn Migration<C::Backend>,
146    ) -> Result<MigrationVersion<'static>> {
147        tokio::task::block_in_place(|| {
148            diesel_migrations::MigrationHarness::run_migration(&mut self.conn, migration)
149        })
150    }
151
152    fn revert_migration(
153        &mut self,
154        migration: &dyn Migration<C::Backend>,
155    ) -> Result<MigrationVersion<'static>> {
156        tokio::task::block_in_place(|| {
157            diesel_migrations::MigrationHarness::revert_migration(&mut self.conn, migration)
158        })
159    }
160
161    fn applied_migrations(&mut self) -> Result<Vec<MigrationVersion<'static>>> {
162        tokio::task::block_in_place(|| {
163            diesel_migrations::MigrationHarness::applied_migrations(&mut self.conn)
164        })
165    }
166}