Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,17 @@ edition = "2024"


[dependencies]
sqlx = { version = "0.8", features = ["runtime-tokio-native-tls", "postgres"] }
deadpool-postgres = { version = "0.14.1", features = ["serde"] }
serde = { version = "1.0", features = ["derive"] }
moka = { version = "0.12", features = ["future"] }
uuid = { version = "1.0", features = ["v4"] }
tokio-postgres = "0.7.13"
env_logger = "0.11.6"
actix-web = "4.11.0"
actix-cors = "0.7.1"
deadpool = "0.12.2"
serde_json = "1.0"
tokio = "1.47.1"
log = "0.4"


Expand Down
79 changes: 43 additions & 36 deletions src/db/pgsql_handlers.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use serde::{Deserialize, Serialize};
use sqlx::postgres::PgPool;
use sqlx::Row;
use deadpool_postgres::{
PoolError as PgError,
Pool as PgPool
};


#[derive(Deserialize, Serialize)]
Expand All @@ -21,34 +23,33 @@ pub struct Record {


// DB working state Check
pub async fn health_check(db_pool: &PgPool) -> Result<(), sqlx::Error> {
pub async fn health_check(db_pool: &PgPool) -> Result<(), PgError> {
// Simple query to check if the database is responsive
sqlx::query("SELECT 1")
.fetch_one(db_pool)
.await
.map(|_| ()) // If successful, return Ok(())
let client = db_pool.get().await?;
let _ = client.query("SELECT 1", &[]).await?;
Ok(())
}


// Sample private function to create a new note
async fn create_single_note(db_pool: &PgPool, note: Note) -> Result<i32, sqlx::Error> {
let row = sqlx::query(
r#"
INSERT INTO notes (title, content)
VALUES ($1, $2)
RETURNING id
"#
)
.bind(&note.title)
.bind(&note.content)
.fetch_one(db_pool)
.await?;

Ok(row.get("id"))
async fn create_single_note(db_pool: &PgPool, note: Note) -> Result<i32, PgError> {
let client = db_pool.get().await?;
let result = client
.query(
r#"
INSERT INTO notes (title, content)
VALUES ($1, $2)
RETURNING id
"#,
&[&note.title, &note.content],
)
.await?;
Ok(result[0].get("id"))
}


// Add few sample data in DB
pub async fn add_new_notes(db_pool: &PgPool, values: Vec<Note>) -> Result<(), sqlx::Error> {
pub async fn add_new_notes(db_pool: &PgPool, values: Vec<Note>) -> Result<(), PgError> {
for note in values {
// We can do like this to purely put the query in one function and call it in another function
// We can even do some processing before calling the query (but all db related stuff should be in db module only)
Expand All @@ -59,19 +60,25 @@ pub async fn add_new_notes(db_pool: &PgPool, values: Vec<Note>) -> Result<(), sq
}

// Fetch all notes from DB
pub async fn fetch_all_notes(db_pool: &PgPool) -> Result<Vec<Record>, sqlx::Error> {
let result = sqlx::query(
r#"
SELECT id, title, content FROM notes
"#
)
.map(|row: sqlx::postgres::PgRow| Record {
id: row.get("id"),
title: row.get("title"),
content: row.get("content"),
})
.fetch_all(db_pool)
.await;
pub async fn fetch_all_notes(db_pool: &PgPool) -> Result<Vec<Record>, PgError> {
let client = db_pool.get().await?;
let rows = client
.query(
r#"
SELECT id, title, content FROM notes
"#,
&[],
)
.await?;

let notes = rows
.iter()
.map(|row| Record {
id: row.get("id"),
title: row.get("title"),
content: row.get("content"),
})
.collect();

result
Ok(notes)
}
6 changes: 3 additions & 3 deletions src/routes/health.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::db::pgsql_handlers::health_check as check_db;
use crate::db::pgsql_handlers::health_check as health_check_pgsql;
use actix_web::{get, web, HttpResponse, Responder};
use sqlx::PgPool;
use deadpool_postgres::Pool as PgPool;


// Health check endpoint
Expand All @@ -13,7 +13,7 @@ async fn api_health_check() -> impl Responder {
// Database health check
#[get("/pgsql")]
async fn db_health_check(state: web::Data<PgPool>) -> impl Responder {
match check_db(&state).await {
match health_check_pgsql(&state).await {
Ok(_) => HttpResponse::Ok().body("Database is running!"),
Err(err) => HttpResponse::InternalServerError().json(format!("Failed: {}", err)),
}
Expand Down
2 changes: 1 addition & 1 deletion src/routes/sample_db.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::db::pgsql_handlers::{Note, add_new_notes, fetch_all_notes};
use actix_web::{get, post, web, HttpResponse, Responder};
use crate::types::{AppCache, make_key};
use sqlx::PgPool;
use deadpool_postgres::Pool as PgPool;


#[post("/create-note")]
Expand Down
Loading