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
26pub fn run_db_migration(
27 conn: &mut Connection,
28) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
29 // Check DB connection!
30 match conn.ping() {
31 Ok(_) => {}
32 Err(e) => {
33 eprint!("[run_db_migration]: Error connecting to database: {e}");
34 return Err(Box::new(e));
35 }
36 }
37
38 // Run all pending migrations.
39 match conn.run_pending_migrations(MIGRATIONS) {
40 Ok(_) => Ok(()),
41 Err(e) => {
42 eprint!("[run_db_migration]: Error migrating database: {e}");
43 Err(e)
44 }
45 }
46}
47
48/// Revert all pending database migrations.
49///
50/// # Arguments
51///
52/// * `conn` - A mutable reference to a `Connection` object.
53///
54/// # Errors
55///
56/// * If there is an error while connecting to the database.
57/// * If there is an error while reverting the database migrations.
58pub fn revert_db_migration(
59 conn: &mut Connection,
60) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
61 // Check DB connection!
62 if conn.ping().is_ok() {
63 } else if let Err(e) = conn.ping() {
64 eprint!("[pg_cmdb]: Error connecting to database: {e}");
65 return Err(Box::new(e));
66 }
67
68 // Revert all pending migrations
69 match conn.revert_all_migrations(MIGRATIONS) {
70 Ok(_) => Ok(()),
71 Err(e) => {
72 eprint!("[pg_cmdb]: Error reverting database migrations: {e}");
73 Err(e)
74 }
75 }
76}