summaryrefslogtreecommitdiffstats
path: root/src/db.rs
diff options
context:
space:
mode:
authorSanto Cariotti <santo@dcariotti.me>2022-09-01 16:45:04 +0000
committerSanto Cariotti <santo@dcariotti.me>2022-09-01 16:45:04 +0000
commitab23761e090b8ab6311a360eada7131f6663a3bf (patch)
treeb5a99bb4cfc811e45fc2e3680b4f8b1e944515eb /src/db.rs
Fork from m6-ie project
Diffstat (limited to 'src/db.rs')
-rw-r--r--src/db.rs29
1 files changed, 29 insertions, 0 deletions
diff --git a/src/db.rs b/src/db.rs
new file mode 100644
index 0000000..43c3bd9
--- /dev/null
+++ b/src/db.rs
@@ -0,0 +1,29 @@
+use crate::errors::AppError;
+
+use sqlx::postgres::PgPool;
+
+/// Static variable used to manage the database connection. Called with value = None raises a panic
+/// error.
+static mut CONNECTION: Option<PgPool> = None;
+
+/// Setup database connection. Get variable `DATABASE_URL` from the environment. Sqlx crate already
+/// defines an error for environments without DATABASE_URL.
+pub async fn setup() -> Result<(), AppError> {
+ let database_url =
+ std::env::var("DATABASE_URL").expect("Define `DATABASE_URL` environment variable.");
+
+ unsafe {
+ CONNECTION = Some(PgPool::connect(&database_url).await?);
+ }
+
+ Ok(())
+}
+
+/// Get connection. Raises an error if `setup()` has not been called yet.
+/// Managing static `CONNECTION` is an unsafe operation.
+pub unsafe fn get_client() -> &'static PgPool {
+ match &CONNECTION {
+ Some(client) => client,
+ None => panic!("Connection not established!"),
+ }
+}