rusty_api/core/
db.rs

1/*!
2 * Database module.
3 *
4 * This module handles the database connection and provides functions to interact
5 * with the database, including querying and updating user fields.
6 */
7use sqlx::{Pool, Sqlite, SqlitePool};
8use std::env;
9use actix_web::HttpResponse;
10use crate::DB_POOL;
11
12/**
13 * Initialize the database connection.
14 *
15 * This function creates a connection pool to the SQLite database specified in
16 * the `DATABASE_URL` environment variable. If the variable is not set, it defaults
17 * to `sqlite:./users.db.db`.
18 *
19 * # Returns
20 * A `Result` containing the connection pool or an error if the connection fails.
21 */
22pub async fn init_db() -> Result<Pool<Sqlite>, sqlx::Error> {
23    let db_url = env::var("DATABASE_URL").unwrap_or("sqlite:./users.db".to_string());
24    let pool = SqlitePool::connect(&db_url).await?;
25
26    Ok(pool)
27}
28
29
30/**
31 * Get a user field from the database.
32 *
33 * This function retrieves a specific field from the `users` table for a given user ID.
34 *
35 * # Arguments
36 * - `user_id`: The ID of the user to retrieve the field for.
37 * - `field`: The name of the field to retrieve.
38 *
39 * # Returns
40 * An `HttpResponse` containing the value of the field or an error message if the field is not found.
41 */
42pub async fn get_user_field(user_id: i32, field: &str) -> HttpResponse {
43    let query = format!("SELECT {} FROM users WHERE id = ?", field);
44    let result: Option<(String,)> = match sqlx::query_as(&query)
45        .bind(user_id)
46        .fetch_optional(&*DB_POOL)
47        .await
48    {
49        Ok(result) => result,
50        Err(_) => return HttpResponse::InternalServerError().body("Database error"),
51    };
52
53    match result {
54        Some((value,)) => HttpResponse::Ok().body(value),
55        None => HttpResponse::NotFound().body(format!("Field '{}' not found for user", field)),
56    }
57}
58
59/**
60 * Set a user field in the database.
61 *
62 * This function updates a specific field in the `users` table for a given user ID.
63 *
64 * # Arguments
65 * - `user_id`: The ID of the user to update the field for.
66 * - `field`: The name of the field to update.
67 * - `value`: The new value to set for the field.
68 *
69 * # Returns
70 * An `HttpResponse` indicating the success or failure of the operation.
71 */
72pub async fn set_user_field(user_id: i32, field: &str, value: &str) -> HttpResponse {
73    let query = format!("UPDATE users SET {} = ? WHERE id = ?", field);
74    let result = sqlx::query(&query)
75        .bind(value)
76        .bind(user_id)
77        .execute(&*DB_POOL)
78        .await;
79
80    match result {
81        Ok(rows_affected) if rows_affected.rows_affected() > 0 => {
82            HttpResponse::Ok().body(format!("Field '{}' updated successfully", field))
83        }
84        Ok(_) => HttpResponse::NotFound().body(format!("User with ID '{}' not found", user_id)),
85        Err(_) => HttpResponse::InternalServerError().body("Database error"),
86    }
87}