Skip to content

Commit

Permalink
Feat: Integrate configuration module for database connection string
Browse files Browse the repository at this point in the history
  • Loading branch information
aryansri-19 committed Jul 6, 2024
1 parent 94ee5b2 commit feadbee
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 12 deletions.
11 changes: 6 additions & 5 deletions src/db/mod.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
use std::env;

use dotenv::dotenv;
use tokio::sync::OnceCell;
use tokio_postgres::{Client, Error, NoTls};

use crate::configuration::get_configuration;

static CLIENT: OnceCell<Client> = OnceCell::const_new();

async fn init_client() -> Result<Client, Error> {
dotenv().ok();
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let database_url = get_configuration()
.expect("Failed to read configuration")
.database
.connection_string();

let (client, connection) = tokio_postgres::connect(&database_url, NoTls).await?;

Expand Down
16 changes: 9 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,17 +195,19 @@ impl Task {

pub async fn list_tasks(date: Option<NaiveDate>) -> Result<Vec<Task>, Box<dyn Error>> {
let client = get_client().await?;
let date_params: NaiveDate;
let (query, params): (&str, &[&(dyn ToSql + Sync)]) = match date {
Some(_d) =>
Some(d) => {
date_params = d;
(
"SELECT description, priority, difficulty, deadline FROM todo WHERE deadline = $1::date",
&[&date.unwrap()],
),
None =>
(
"SELECT description, priority, difficulty, deadline FROM todo",
&[],
&[&date_params],
)
}
None => (
"SELECT description, priority, difficulty, deadline FROM todo",
&[],
),
};
let rows = client
.query(query, params)
Expand Down

0 comments on commit feadbee

Please sign in to comment.