Added Postgres backend and SQLx.

This commit is contained in:
2026-09-19 22:13:38 +02:00
parent 04ebc95920
commit 15b8ae8f62
17 changed files with 1545 additions and 49 deletions
+29 -1
View File
@@ -4,15 +4,43 @@ services:
context: ./server context: ./server
dockerfile: Dockerfile dockerfile: Dockerfile
init: true init: true
depends_on:
postgres:
condition: service_healthy
environment: environment:
RUST_LOG: info RUST_LOG: trace
HOST: 0.0.0.0 HOST: 0.0.0.0
PORT: 3000 PORT: 3000
DATABASE_URL: postgres://expenses:expenses@postgres:5432/expenses
SQLX_OFFLINE: "true"
ports: ports:
- "3000:3000" - "3000:3000"
volumes: volumes:
- server-target:/app/target - server-target:/app/target
- ./server:/app - ./server:/app
networks:
- expenses_net
postgres:
image: postgres:17-alpine
environment:
POSTGRES_DB: expenses
POSTGRES_USER: expenses
POSTGRES_PASSWORD: expenses
healthcheck:
test: ["CMD-SHELL", "pg_isready -U expenses -d expenses"]
interval: 5s
timeout: 5s
retries: 5
volumes:
- postgres-data:/var/lib/postgresql/data
networks:
- expenses_net
volumes: volumes:
server-target: server-target:
postgres-data:
networks:
expenses_net:
name: expenses_net
+2
View File
@@ -0,0 +1,2 @@
[env]
SQLX_OFFLINE = "true"
@@ -0,0 +1,38 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT id, description, amount_cents, date\n FROM transactions\n ORDER BY date DESC, id DESC\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "description",
"type_info": "Text"
},
{
"ordinal": 2,
"name": "amount_cents",
"type_info": "Int8"
},
{
"ordinal": 3,
"name": "date",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": []
},
"nullable": [
false,
false,
false,
false
]
},
"hash": "9b91722c2119022fa62421e2d1eaca7557b0f5a31e99485548bdd5a37b0c56fb"
}
+1330 -7
View File
File diff suppressed because it is too large Load Diff
+8
View File
@@ -9,6 +9,14 @@ chrono = { version = "0.4.45", features = ["serde"] }
dotenv = "0.15.0" dotenv = "0.15.0"
serde = { version = "1.0.229", features = ["derive"] } serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.151" serde_json = "1.0.151"
sqlx = { version = "0.8.6", default-features = false, features = [
"runtime-tokio-rustls",
"postgres",
"macros",
"migrate",
"uuid",
"chrono",
] }
tokio = { version = "1.53.1", features = ["full"] } tokio = { version = "1.53.1", features = ["full"] }
tracing = "0.1.44" tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
+3 -8
View File
@@ -1,13 +1,8 @@
FROM rust:bookworm FROM rust:bookworm
RUN cargo install cargo-watch --locked RUN cargo install cargo-watch --locked \
&& cargo install sqlx-cli --version 0.8.6 --locked --no-default-features --features postgres,rustls
WORKDIR /app WORKDIR /app
CMD [ CMD ["cargo", "watch", "--watch", "src", "--watch", "Cargo.toml", "--watch", "Cargo.lock", "--exec", "run --locked"]
"cargo", "watch",
"--watch", "src",
"--watch", "Cargo.toml",
"--watch", "Cargo.lock",
"--exec", "run --locked"
]
@@ -0,0 +1,6 @@
CREATE TABLE transactions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
description TEXT NOT NULL,
amount_cents BIGINT NOT NULL,
date TIMESTAMPTZ NOT NULL DEFAULT now()
);
+1
View File
@@ -0,0 +1 @@
pub mod dtos;
+1
View File
@@ -0,0 +1 @@
pub mod transaction;
@@ -1,11 +1,9 @@
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use serde::Serialize;
use uuid::Uuid; use uuid::Uuid;
#[derive(Serialize)] pub struct TransactionRow {
pub struct Transaction {
pub id: Uuid, pub id: Uuid,
pub description: String, pub description: String,
pub amount: f64, pub amount_cents: i64,
pub date: DateTime<Utc>, pub date: DateTime<Utc>,
} }
+25
View File
@@ -0,0 +1,25 @@
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
#[derive(Debug)]
pub enum AppError {
Database(sqlx::Error),
}
impl From<sqlx::Error> for AppError {
fn from(error: sqlx::Error) -> Self {
Self::Database(error)
}
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
match self {
Self::Database(error) => tracing::error!(%error, "Database query failed"),
}
(StatusCode::INTERNAL_SERVER_ERROR, "Internal server error").into_response()
}
}
+18 -4
View File
@@ -1,8 +1,10 @@
use std::env; use std::env;
use sqlx::postgres::PgPoolOptions;
use tokio::net::TcpListener; use tokio::net::TcpListener;
mod models; mod database;
mod error;
mod routes; mod routes;
#[tokio::main] #[tokio::main]
@@ -14,14 +16,26 @@ async fn main() {
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.init(); .init();
let host = env::var("HOST").unwrap_or_else(|_| "0.0.0.0".to_string()); let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let port = env::var("PORT").unwrap_or_else(|_| "3000".to_string()); let pool = PgPoolOptions::new()
.max_connections(5)
.connect(&database_url)
.await
.expect("Failed to connect to database");
sqlx::migrate!()
.run(&pool)
.await
.expect("Failed to run database migrations");
let host = env::var("HOST").expect("HOST must be set");
let port = env::var("PORT").expect("PORT must be set");
let listener = TcpListener::bind(format!("{}:{}", host, port)) let listener = TcpListener::bind(format!("{}:{}", host, port))
.await .await
.expect("Failed to bind to address"); .expect("Failed to bind to address");
tracing::info!("Starting server at {}:{}", host, port); tracing::info!("Starting server at {}:{}", host, port);
axum::serve(listener, routes::create_router().into_make_service()) axum::serve(listener, routes::create_router(pool).into_make_service())
.await .await
.expect("Failed to start server"); .expect("Failed to start server");
} }
-1
View File
@@ -1 +0,0 @@
pub mod transaction;
+8 -5
View File
@@ -1,8 +1,11 @@
pub mod dtos;
mod transactions; mod transactions;
pub fn create_router() -> axum::Router { pub fn create_router(pool: sqlx::PgPool) -> axum::Router {
axum::Router::new().nest( axum::Router::new()
"/api", .nest(
axum::Router::new().nest("/transactions", transactions::create_router()), "/api",
) axum::Router::new().nest("/transactions", transactions::create_router()),
)
.with_state(pool)
} }
+1
View File
@@ -0,0 +1 @@
pub mod transaction;
+46
View File
@@ -0,0 +1,46 @@
use chrono::{DateTime, Utc};
use serde::Serialize;
use uuid::Uuid;
use crate::database::dtos::transaction::TransactionRow;
#[derive(Serialize)]
pub struct TransactionResponse {
pub id: Uuid,
pub description: String,
pub amount: f64,
pub date: DateTime<Utc>,
}
impl From<TransactionRow> for TransactionResponse {
fn from(row: TransactionRow) -> Self {
Self {
id: row.id,
description: row.description,
amount: row.amount_cents as f64 / 100.0,
date: row.date,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn converts_cents_to_major_currency_units() {
let id = Uuid::new_v4();
let date = Utc::now();
let response = TransactionResponse::from(TransactionRow {
id,
description: "Groceries".to_string(),
amount_cents: 4250,
date,
});
assert_eq!(response.id, id);
assert_eq!(response.description, "Groceries");
assert_eq!(response.amount, 42.5);
assert_eq!(response.date, date);
}
}
+26 -18
View File
@@ -1,23 +1,31 @@
use crate::models::transaction::Transaction; use axum::{Json, extract::State};
use sqlx::PgPool;
pub fn create_router() -> axum::Router { use crate::{
database::dtos::transaction::TransactionRow, error::AppError,
routes::dtos::transaction::TransactionResponse,
};
pub fn create_router() -> axum::Router<PgPool> {
axum::Router::new().route("/", axum::routing::get(get_transactions)) axum::Router::new().route("/", axum::routing::get(get_transactions))
} }
#[tracing::instrument] #[tracing::instrument(skip(pool))]
pub async fn get_transactions() -> axum::Json<Vec<Transaction>> { async fn get_transactions(
axum::Json(vec![ State(pool): State<PgPool>,
Transaction { ) -> Result<Json<Vec<TransactionResponse>>, AppError> {
id: uuid::Uuid::new_v4(), let rows = sqlx::query_as!(
description: "Groceries".to_string(), TransactionRow,
amount: 42.50, r#"
date: chrono::Utc::now(), SELECT id, description, amount_cents, date
}, FROM transactions
Transaction { ORDER BY date DESC, id DESC
id: uuid::Uuid::new_v4(), "#
description: "Coffee".to_string(), )
amount: 4.25, .fetch_all(&pool)
date: chrono::Utc::now(), .await?;
},
]) Ok(Json(
rows.into_iter().map(TransactionResponse::from).collect(),
))
} }