From ad0e585abed7a189b6117e9187c9afff809d1414 Mon Sep 17 00:00:00 2001 From: Harald Eilertsen Date: Mon, 8 Apr 2019 15:55:14 +0200 Subject: Move functions to query/modify db to connection object. Makes tha API a bit nicer by asking the database rather than passing the database on to each model. Reserve models for method/functions that work on the model structs themselves. --- src/db.rs | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) (limited to 'src/db.rs') diff --git a/src/db.rs b/src/db.rs index b299911..53c4ea4 100644 --- a/src/db.rs +++ b/src/db.rs @@ -16,6 +16,13 @@ along with this program. If not, see . */ +use crate::{ + models, + schema::*, +}; + +use diesel::prelude::*; + use rocket_contrib::{ database, databases::diesel, @@ -23,3 +30,58 @@ use rocket_contrib::{ #[database("main")] pub struct Connection(diesel::PgConnection); + +impl Connection { + pub fn create_screening( + &self, + room: &models::room::Room, + film: &models::film::Film, + date: chrono::NaiveDate, + start_time: chrono::NaiveTime, + end_time: chrono::NaiveTime) -> QueryResult + { + let s = models::screening::NewScreening { + room_id: room.id, + film_id: film.id, + date: date, + start_time: start_time, + end_time: end_time, + }; + + diesel::insert_into(screenings::table) + .values(&s) + .execute(&**self) + } + + pub fn get_screenings(&self) -> QueryResult, Option)>> { + use crate::schema::screenings::dsl::*; + screenings + .left_join(films::table) + .left_join(rooms::table) + .get_results(&**self) + } + + pub fn get_rooms(&self) -> QueryResult> { + use crate::schema::rooms::dsl::*; + rooms.load(&**self) + } + + pub fn get_room_by_name(&self, room_name: &str) -> QueryResult { + use crate::schema::rooms::dsl::*; + rooms + .filter(name.eq(&room_name)) + .get_result(&**self) + } + + pub fn get_films(&self) -> QueryResult> { + use crate::schema::films::dsl::*; + films.load(&**self) + } + + pub fn get_film_by_title(&self, film_title: &str) -> QueryResult { + use crate::schema::films::dsl::*; + films + .filter(title.eq(&film_title)) + .get_result(&**self) + } +} -- cgit v1.2.3