r2_data_persistence/operations/
point.rs

1use crate::entities::Point;
2use crate::models::point::{CreatePointModel, GetPointModel, UpdatePointModel};
3use crate::schema::points::dsl::*;
4use diesel::associations::HasTable;
5use diesel::{PgConnection, QueryDsl, QueryResult, RunQueryDsl, SelectableHelper};
6use uuid::Uuid;
7
8pub fn create_point(connection: &mut PgConnection, model: CreatePointModel) {
9    diesel::insert_into(points::table())
10        .values(to_entity(model))
11        .returning(Point::as_returning())
12        .get_result(connection)
13        .expect("Error saving new points");
14}
15
16pub fn get_point(connection: &mut PgConnection, key: &str) -> Option<GetPointModel> {
17    let result: QueryResult<Point> = points
18        .find(key)
19        .select(Point::as_select())
20        .first(connection);
21
22    if let Ok(entity) = result {
23        return Some(to_model(entity));
24    }
25
26    None
27}
28
29pub fn get_all_points(connection: &mut PgConnection) -> Vec<GetPointModel> {
30    points
31        .select(Point::as_select())
32        .load(connection)
33        .expect("Error loading points")
34        .into_iter()
35        .map(to_model)
36        .collect()
37}
38
39pub fn update_point(connection: &mut PgConnection, key: &str, model: UpdatePointModel) {
40    diesel::update(points.find(key))
41        .set::<UpdatePointModel>(model)
42        .returning(Point::as_returning())
43        .get_result(connection)
44        .expect("Error updating points");
45}
46
47pub fn delete_point(connection: &mut PgConnection, key: &str) {
48    diesel::delete(points.find(key))
49        .execute(connection)
50        .expect("Error deleting points");
51}
52
53fn to_model(entity: Point) -> GetPointModel {
54    GetPointModel {
55        id: entity.id,
56        map_id: entity.map_id,
57        spawn_x: entity.spawn_x,
58        spawn_y: entity.spawn_y,
59        radius: entity.radius,
60        spawn_time: entity.spawn_time,
61        click_x: entity.click_x,
62        click_y: entity.click_y,
63        click_time: entity.click_time,
64        offset: entity.offset,
65    }
66}
67
68fn to_entity(model: CreatePointModel) -> Point {
69    Point {
70        id: Uuid::new_v4().to_string(),
71        map_id: model.map_id,
72        spawn_x: model.spawn_x,
73        spawn_y: model.spawn_y,
74        radius: model.radius,
75        spawn_time: model.spawn_time,
76        click_x: model.click_x,
77        click_y: model.click_y,
78        click_time: model.click_time,
79        offset: model.offset,
80    }
81}