custom_arrays/
lib.rs

1use diesel::r2d2::R2D2Connection;
2use diesel::PgConnection;
3use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
4use std::error::Error;
5
6pub mod model;
7mod schema;
8// Alias for a pooled connection.
9// pub type Connection = diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::pg::PgConnection>>;
10
11// Alias for a normal, single, connection.
12pub type Connection = PgConnection;
13
14pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations");
15
16/// Runs all pending database migrations.
17///
18/// Will return an error if the database connection is invalid, or if any of the
19/// migrations fail. Otherwise, it returns Ok()
20///
21/// # Errors
22///
23/// * If the database connection is invalid
24/// * If checking for pending database migrations fails
25/// * If any of the database migrations fail
26///
27pub fn run_db_migration(
28    conn: &mut Connection,
29) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
30    // Check DB connection!
31    match conn.ping() {
32        Ok(_) => {}
33        Err(e) => {
34            eprint!("[run_db_migration]: Error connecting to database: {}", e);
35            return Err(Box::new(e));
36        }
37    }
38
39    // Run all pending migrations.
40    match conn.run_pending_migrations(MIGRATIONS) {
41        Ok(_) => Ok(()),
42        Err(e) => {
43            eprint!("[run_db_migration]: Error migrating database: {}", e);
44            Err(e)
45        }
46    }
47}
48
49/// Revert all pending database migrations.
50///
51/// # Arguments
52///
53/// * `conn` - A mutable reference to a `Connection` object.
54///
55/// # Errors
56///
57/// * If there is an error while connecting to the database.
58/// * If there is an error while reverting the database migrations.
59///
60pub fn revert_db_migration(
61    conn: &mut Connection,
62) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
63    // Check DB connection!
64    if conn.ping().is_ok() {
65    } else if let Err(e) = conn.ping() {
66        eprint!("[pg_cmdb]: Error connecting to database: {}", e);
67        return Err(Box::new(e));
68    }
69
70    // Revert all pending migrations
71    match conn.revert_all_migrations(MIGRATIONS) {
72        Ok(_) => Ok(()),
73        Err(e) => {
74            eprint!("[pg_cmdb]: Error reverting database migrations: {}", e);
75            Err(e)
76        }
77    }
78}