backend/model/entity/
map_impl.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
//! Contains the implementation of [`Map`].

use chrono::{Datelike, Months, NaiveDate, NaiveDateTime, Utc};
use diesel::dsl::{exists, sql};
use diesel::pg::Pg;
use diesel::sql_types::Float;
use diesel::{
    debug_query, select, BoolExpressionMethods, ExpressionMethods, PgTextExpressionMethods,
    QueryDsl, QueryResult,
};
use diesel_async::{AsyncPgConnection, RunQueryDsl};
use log::debug;
use uuid::Uuid;

use crate::db::function::{similarity, PgTrgmExpressionMethods};
use crate::db::pagination::Paginate;
use crate::model::dto::{
    MapSearchParameters, Page, PageParameters, UpdateMapDto, UpdateMapGeometryDto,
};
use crate::model::entity::{UpdateMap, UpdateMapGeometry};
use crate::{
    model::dto::{MapDto, NewMapDto},
    schema::maps::{self, all_columns, created_by, deletion_date, is_inactive, name, privacy},
};

use super::{Map, NewMap};

impl Map {
    /// Get the top maps matching the search query.
    ///
    /// Can be filtered by `is_inactive` and `created_by` if provided in `search_parameters`.
    /// This will be done with equals and is additional functionality for maps (when compared to plant search).
    ///
    /// Uses `pg_trgm` to find matches in `name`.
    /// Ranks using the `pg_trgm` function `similarity()`.
    ///
    /// # Errors
    /// * Unknown, diesel doesn't say why it might error.
    pub async fn find(
        search_parameters: MapSearchParameters,
        page_parameters: PageParameters,
        conn: &mut AsyncPgConnection,
    ) -> QueryResult<Page<MapDto>> {
        let mut query = maps::table
            .select((
                similarity(name, search_parameters.name.clone().unwrap_or_default()),
                all_columns,
            ))
            .into_boxed();

        if let Some(search_query) = &search_parameters.name {
            if !search_query.is_empty() {
                query = query.filter(
                    name.fuzzy(search_query)
                        .or(name.ilike(format!("%{search_query}%"))),
                );
            }
        }
        if let Some(is_inactive_search) = search_parameters.is_inactive {
            query = query.filter(is_inactive.eq(is_inactive_search));
        }
        if let Some(privacy_search) = search_parameters.privacy {
            query = query.filter(privacy.eq(privacy_search));
        }
        if let Some(created_by_search) = search_parameters.created_by {
            query = query.filter(created_by.eq(created_by_search));
        }

        let query = query
            .filter(deletion_date.is_null())
            .order(sql::<Float>("1").desc())
            .paginate(page_parameters.page)
            .per_page(page_parameters.per_page);
        debug!("{}", debug_query::<Pg, _>(&query));
        query
            .load_page::<(f32, Self)>(conn)
            .await
            .map(Page::from_entity)
    }

    /// Fetch map by id from the database.
    ///
    /// # Errors
    /// * Unknown, diesel doesn't say why it might error.
    pub async fn find_by_id(id: i32, conn: &mut AsyncPgConnection) -> QueryResult<MapDto> {
        let query = maps::table.find(id).filter(deletion_date.is_null());
        debug!("{}", debug_query::<Pg, _>(&query));
        query.first::<Self>(conn).await.map(Into::into)
    }

    /// Checks if a map with this name already exists in the database.
    ///
    /// # Errors
    /// * Unknown, diesel doesn't say why it might error.
    pub async fn is_name_taken(map_name: &str, conn: &mut AsyncPgConnection) -> QueryResult<bool> {
        let query = select(exists(maps::table.filter(name.eq(map_name))));
        debug!("{}", debug_query::<Pg, _>(&query));
        query.get_result(conn).await
    }

    /// Create a new map in the database.
    ///
    /// # Errors
    /// * Unknown, diesel doesn't say why it might error.
    pub async fn create(
        new_map: NewMapDto,
        user_id: Uuid,
        conn: &mut AsyncPgConnection,
    ) -> QueryResult<MapDto> {
        let new_map = NewMap::from((new_map, user_id));
        let query = diesel::insert_into(maps::table).values(&new_map);
        debug!("{}", debug_query::<Pg, _>(&query));
        query.get_result::<Self>(conn).await.map(Into::into)
    }

    /// Update a map in the database.
    ///
    /// # Errors
    /// * Unknown, diesel doesn't say why it might error.
    pub async fn update(
        map_update: UpdateMapDto,
        id: i32,
        conn: &mut AsyncPgConnection,
    ) -> QueryResult<MapDto> {
        let map_update = UpdateMap::from(map_update);
        let query = diesel::update(maps::table.find(id)).set(&map_update);
        debug!("{}", debug_query::<Pg, _>(&query));
        query.get_result::<Self>(conn).await.map(Into::into)
    }

    /// Marks a map for deletion using the systems current date and time.
    ///
    /// # Errors
    /// * Unknown, diesel doesn't say why it might error.
    pub async fn mark_for_deletion(id: i32, conn: &mut AsyncPgConnection) -> QueryResult<MapDto> {
        let now = Utc::now().naive_utc();
        let in_one_month = now + Months::new(1);
        // Indeed, there is no automatic conversion from NaiveDateTime to NaiveDate for some reason.
        let in_one_month_as_naive_date = NaiveDate::from_ymd_opt(
            in_one_month.year(),
            in_one_month.month(),
            in_one_month.day(),
        );

        let map = Self::find_by_id(id, conn).await?;

        let query = diesel::update(maps::table.find(id)).set((
            deletion_date.eq(in_one_month_as_naive_date),
            // Prevent deleted maps causing issues because their name still exists.
            name.eq(format!("{} __DELETED {}", map.name, now)),
        ));
        debug!("{}", debug_query::<Pg, _>(&query));
        query.get_result::<Self>(conn).await.map(Into::into)
    }

    /// Update a maps bounds in the database.
    ///
    /// # Errors
    /// * Unknown, diesel doesn't say why it might error.
    pub async fn update_geometry(
        map_update_bounds: UpdateMapGeometryDto,
        id: i32,
        conn: &mut AsyncPgConnection,
    ) -> QueryResult<MapDto> {
        let map_update = UpdateMapGeometry::from(map_update_bounds);
        let query = diesel::update(maps::table.find(id)).set(&map_update);
        debug!("{}", debug_query::<Pg, _>(&query));
        query.get_result::<Self>(conn).await.map(Into::into)
    }

    /// Update modified metadata (`modified_at`, `modified_by`) of the map.
    ///
    /// # Errors
    /// * Unknown, diesel doesn't say why it might error.
    pub async fn update_modified_metadata(
        id: i32,
        user_id: Uuid,
        time: NaiveDateTime,
        conn: &mut AsyncPgConnection,
    ) -> QueryResult<()> {
        diesel::update(maps::table.find(id))
            .set((maps::modified_at.eq(time), maps::modified_by.eq(user_id)))
            .execute(conn)
            .await?;
        Ok(())
    }
}