Skip to main content

flix_db/
connection.rs

1//! Types and functions related to [`DatabaseConnection`]s.
2
3use sea_orm::{DatabaseConnection, DbErr};
4use sea_orm_migration::MigratorTrait as _;
5
6/// A newtype wrapping a [`DatabaseConnection`].
7#[derive(Debug)]
8pub struct Connection(DatabaseConnection);
9
10impl Connection {
11	/// Helper function for applying database migrations while wrapping a
12	/// [`DatabaseConnection`] in a newtype.
13	///
14	/// # Errors
15	/// Fails if connecting or applying migrations fail.
16	#[inline]
17	pub async fn try_from(db: DatabaseConnection) -> Result<Self, DbErr> {
18		// The migrations only create views which store no data, so it is
19		// important to down before up since modifications are impossible.
20		//
21		// Syncing the schema registry allows all real tables to be upgraded.
22		// It is important to sync twice to ensure internal consistency so that
23		// the views can be recreated on the latest schema.
24		crate::migration::Migrator::down(&db, None).await?;
25		db.get_schema_registry("flix_db::*").sync(&db).await?;
26		db.get_schema_registry("flix_db::*").sync(&db).await?;
27		crate::migration::Migrator::up(&db, None).await?;
28		Ok(Self(db))
29	}
30}
31
32impl AsRef<DatabaseConnection> for Connection {
33	#[inline]
34	fn as_ref(&self) -> &DatabaseConnection {
35		&self.0
36	}
37}
38
39#[cfg(test)]
40impl Connection {
41	pub(crate) fn take(self) -> DatabaseConnection {
42		self.0
43	}
44}