43 lines
1.4 KiB
Rust
43 lines
1.4 KiB
Rust
use diesel::prelude::*;
|
|
use diesel::r2d2::{ConnectionManager, Pool};
|
|
use diesel::SqliteConnection;
|
|
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
|
|
|
|
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
|
|
|
|
/// Establishes a connection to the database using the given URL.
|
|
///
|
|
/// # Arguments
|
|
/// * `url` - The database URL to connect to.
|
|
///
|
|
/// # Panics
|
|
/// Panics if the database URL is not set or if the connection cannot be
|
|
/// established.
|
|
pub fn establish_connection(url: &str) -> SqliteConnection {
|
|
SqliteConnection::establish(url).unwrap_or_else(|_| panic!("Error connecting to {}", url))
|
|
}
|
|
|
|
/// Builds a connection pool for the given URL.
|
|
///
|
|
/// # Arguments
|
|
/// * `url` - The database URL to connect to.
|
|
///
|
|
/// # Panics
|
|
/// Panics if the connection pool cannot be created.
|
|
pub fn build_connection_pool(url: &str) -> Pool<ConnectionManager<SqliteConnection>> {
|
|
let manager = ConnectionManager::<SqliteConnection>::new(url);
|
|
Pool::builder().build(manager).expect("Failed to create connection pool.")
|
|
}
|
|
|
|
/// Runs any pending migrations.
|
|
///
|
|
/// This function should be called before the application starts.
|
|
///
|
|
/// # Arguments
|
|
/// * `conn` - The database connection to run the migrations on.
|
|
///
|
|
/// # Panics
|
|
/// Panics if there is an error running the migrations.
|
|
pub fn migrate(conn: &mut SqliteConnection) {
|
|
conn.run_pending_migrations(MIGRATIONS).unwrap();
|
|
}
|