Database Access Function

Overview

Database access functions are crucial components in applications that require interaction with a database. These functions are responsible for performing operations such as querying, inserting, updating, and deleting records, collectively known as CRUD operations. By utilizing the sqlx crate, these functions construct and execute SQL queries, converting the results into Rust data structures. This separation of concerns ensures that database access functions adhere to the single responsibility principle, keeping them distinct from handler functions. The handler functions, in turn, are responsible for sending responses to the client.

Functionality

The primary responsibilities of database access functions include:

  • Preparing SQL Statements: Crafting the necessary SQL queries to interact with the database.
  • Executing Queries: Running the prepared SQL statements against the database.
  • Mapping Results: Converting the results of the queries into Rust structs for further processing.
  • Error Handling: Managing any errors that occur during database operations and returning appropriate results to the handler functions.

Examples

Retrieving All Courses for a Tutor

An example of a database access function is one that retrieves all courses associated with a specific tutor. This function involves preparing an SQL statement, executing the query, and converting the results into a Rust vector. The function get_courses_for_tutor_db exemplifies this process, although the specific code for this function is not provided here.

Retrieving All Tutors

Below is an example of a database access function designed to retrieve a list of all tutors from the database:

use crate::errors::EzyTutorError;
use crate::models::tutor::{NewTutor, Tutor, UpdateTutor};
use sqlx::postgres::PgPool;
 
pub async fn get_all_tutors_db(pool: &PgPool) ->
Result<Vec<Tutor>, EzyTutorError> {
    // Prepare SQL statement
    let tutor_rows =
        sqlx::query!("SELECT tutor_id, tutor_name, tutor_pic_url,
        tutor_profile FROM ezy_tutor_c6")
            .fetch_all(pool)
            .await?;
    // Extract result
 
    let tutors: Vec<Tutor> = tutor_rows
        .iter()
        .map(|tutor_row| Tutor {
            tutor_id: tutor_row.tutor_id,
            tutor_name: tutor_row.tutor_name.clone(),
            tutor_pic_url: tutor_row.tutor_pic_url.clone(),
            tutor_profile: tutor_row.tutor_profile.clone(),
        })
        .collect();
    match tutors.len() {
        0 => Err(EzyTutorError::NotFound("No tutors found".into())),
        _ => Ok(tutors),
    }
}

In this example, the function get_all_tutors_db prepares an SQL query to select tutor details from the ezy_tutor_c6 table. It then executes the query and maps the results into a vector of Tutor structs. If no tutors are found, it returns an error indicating that no tutors were found. Otherwise, it returns the list of tutors.

FAQ (Frequently asked questions)

Which crate is used by database access functions to construct and execute SQL queries?

What happens if no tutors are found in the get_all_tutors_db function?