retrom_db/
lib.rs

1use diesel::{migration::MigrationVersion, prelude::*};
2use diesel_async::{pooled_connection::AsyncDieselConnectionManager, AsyncPgConnection};
3use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
4use std::fmt::Debug;
5
6pub mod schema;
7
8#[cfg(feature = "embedded")]
9pub mod embedded;
10
11#[derive(thiserror::Error, Debug)]
12pub enum Error {
13    #[error("Error running migrations: {0}")]
14    MigrationError(String),
15
16    #[cfg(feature = "embedded")]
17    #[error("Embedded DB error")]
18    EmbeddedError(#[from] postgresql_embedded::Error),
19
20    #[error("Could not create embedded database")]
21    NotExists,
22
23    #[error(transparent)]
24    IOError(#[from] std::io::Error),
25}
26
27pub type Result<T> = std::result::Result<T, Error>;
28
29pub type PoolConfig = AsyncDieselConnectionManager<AsyncPgConnection>;
30pub type Pool = deadpool::managed::Pool<PoolConfig>;
31pub type DBConnection = deadpool::managed::Object<PoolConfig>;
32
33pub type DBConnectionSync = diesel::pg::PgConnection;
34
35pub fn get_db_connection_sync(
36    db_url: &str,
37) -> std::result::Result<DBConnectionSync, diesel::ConnectionError> {
38    diesel::pg::PgConnection::establish(db_url)
39}
40
41pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
42
43pub fn run_migrations(
44    conn: &mut impl MigrationHarness<diesel::pg::Pg>,
45) -> Result<Vec<MigrationVersion>> {
46    conn.run_pending_migrations(MIGRATIONS)
47        .map_err(|e| Error::MigrationError(e.to_string()))
48}