r2_data_persistence/operations/
map.rs

1use crate::entities::Map;
2use crate::models::map::{CreateMapModel, GetMapModel, UpdateMapModel};
3use crate::schema::maps::dsl::*;
4use diesel::associations::HasTable;
5use diesel::{PgConnection, QueryDsl, QueryResult, RunQueryDsl, SelectableHelper};
6use uuid::Uuid;
7
8pub fn create_map(connection: &mut PgConnection, model: CreateMapModel) {
9    diesel::insert_into(maps::table())
10        .values(to_entity(model))
11        .returning(Map::as_returning())
12        .get_result(connection)
13        .expect("Error saving new map");
14}
15
16pub fn get_map(connection: &mut PgConnection, key: &str) -> Option<GetMapModel> {
17    let result: QueryResult<Map> = maps.find(key).select(Map::as_select()).first(connection);
18
19    if let Ok(entity) = result {
20        to_model(entity);
21    }
22
23    None
24}
25
26pub fn get_all_maps(connection: &mut PgConnection) -> Vec<GetMapModel> {
27    maps.select(Map::as_select())
28        .load(connection)
29        .expect("Error loading maps")
30        .into_iter()
31        .map(to_model)
32        .collect()
33}
34
35pub fn update_map(connection: &mut PgConnection, key: &str, model: UpdateMapModel) {
36    diesel::update(maps.find(key))
37        .set::<UpdateMapModel>(model)
38        .returning(Map::as_returning())
39        .get_result(connection)
40        .expect("Error updating map");
41}
42
43pub fn delete_map(connection: &mut PgConnection, key: &str) {
44    diesel::delete(maps.find(key))
45        .execute(connection)
46        .expect("Error deleting map");
47}
48
49fn to_model(entity: Map) -> GetMapModel {
50    GetMapModel {
51        id: entity.id,
52        song: entity.song,
53    }
54}
55
56fn to_entity(model: CreateMapModel) -> Map {
57    Map {
58        id: Uuid::new_v4().to_string(),
59        song: model.song,
60    }
61}