Database Access in Rust
Database access in Rust involves writing functions that interact with a database to perform operations such as querying and inserting records. The sqlx crate is a popular choice for constructing and executing SQL queries in Rust, as it allows for seamless conversion of query results into Rust data structures. This approach not only facilitates easier switching between different databases but also helps maintain a clean code architecture.
Overview of Database Access
In the context of tutor APIs, database access functions are designed to handle various operations such as retrieving all tutors, fetching details of a specific tutor, adding a new tutor, updating tutor details, and deleting a tutor. These operations are executed using the sqlx library, which manages the execution of SQL queries and the handling of results.
Retrieving All Courses for a Tutor
The following code demonstrates how to retrieve all courses associated with a specific tutor using the sqlx crate. The function get_courses_for_tutor_db prepares an SQL statement, executes it, and converts the results into a Rust vector of Course structs.
Listing 4.6 Database access code for retrieving all courses for a tutor
use super::models::Course;
use sqlx::postgres::PgPool;
pub async fn get_courses_for_tutor_db(pool: &PgPool, tutor_id: i32) ->
Vec<Course> {
// Prepare SQL statement
let course_rows = sqlx::query!( #1
"SELECT tutor_id, course_id, course_name, posted_time FROM
ezy_course_c4 where tutor_id = $1",
tutor_id
)
.fetch_all(pool) #2
.await
.unwrap();
// Extract result
course_rows #3
.iter()
.map(|course_row| Course {
course_id: course_row.course_id,
tutor_id: course_row.tutor_id,
course_name: course_row.course_name.clone(),
posted_time: Some(chrono::NaiveDateTime::from(
course_row.posted_time.unwrap())),
})
.collect()
}
- The SQL statement is prepared using the
query!macro. - The query is executed with the
fetch_all()method, which retrieves all matching records. - The results are converted into a vector of
Coursestructs.
Retrieving Details for a Single Course
To retrieve details for a single course, the fetch_one() method is used instead of fetch_all(), as it is designed to fetch a single record. The following code snippet illustrates this process:
Listing 4.7 Database access code for retrieving details for a single course
pub async fn get_course_details_db(pool: &PgPool, tutor_id: i32,
course_id: i32) -> Course {
// Prepare SQL statement
let course_row = sqlx::query!( #1
"SELECT tutor_id, course_id, course_name, posted_time FROM
ezy_course_c4 where tutor_id = $1 and course_id = $2",
tutor_id, course_id
)
.fetch_one(pool) #2
.await
.unwrap();
// Execute query
Course { #3
course_id: course_row.course_id,
tutor_id: course_row.tutor_id,
course_name: course_row.course_name.clone(),
posted_time: Some(chrono::NaiveDateTime::from(
course_row.posted_time.unwrap())),
}
}
- The query is prepared for execution.
- The
fetch_one()method is used to execute the query and fetch a single course. - The result is returned as a
Coursestruct.
Posting a New Course
The process of posting a new course involves constructing an SQL insert query, executing it, and then retrieving the inserted course. The following code demonstrates this process:
Listing 4.8 Database access code for posting a new course
pub async fn post_new_course_db(pool: &PgPool, new_course: Course) ->
Course {
let course_row = sqlx::query!("insert into ezy_course_c4 (
course_id,tutor_id, course_name) values ($1,$2,$3) returning
tutor_id, course_id,course_name, posted_time", new_course.course_id,
new_course.tutor_id, new_course.course_name) #1
.fetch_one(pool) #2
.await.unwrap();
//Retrieve result
Course { #3
course_id: course_row.course_id,
tutor_id: course_row.tutor_id,
course_name: course_row.course_name.clone(),
posted_time: Some(chrono::NaiveDateTime::from(
course_row.posted_time.unwrap())),
}
}
- The query is prepared to insert a new course into the database.
- The
fetch_one()method retrieves the inserted course. - The result is returned as a
Coursestruct.
In this implementation, the posted_time is not explicitly passed to the insert query, as it defaults to the system-generated current time. This default behavior is defined in the database schema.
FAQ (Frequently asked questions)
What is involved in writing database access functions?
Which crate is used for constructing and executing SQL queries in Rust?
How are SQL query results handled in Rust?
Why is separating database access functions beneficial?
What operations are included in database access functions for tutor routes?
Which library is used for executing SQL queries in the context of tutor APIs?
What is the purpose of database access functions in tutor APIs?