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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
//! Contains the implementation of [`Layer`].

use chrono::Utc;
use diesel::pg::Pg;
use diesel::{debug_query, sql_query, ExpressionMethods, QueryDsl, QueryResult};
use diesel_async::{AsyncConnection, AsyncPgConnection, RunQueryDsl};
use futures::future::try_join_all;
use futures::Future;
use log::debug;
use uuid::Uuid;

use crate::{
    model::{
        dto::layers::{LayerDto, LayerRenameDto, LayerSearchParameters},
        entity::layers::{Layer, UpdateLayerMarkedDeleted, UpdateLayerName, UpdateLayerOrderIndex},
    },
    schema::layers,
};

impl Layer {
    /// Get a page of layers.
    /// Can be filtered by its active status if one is provided in `search_parameters`.
    ///
    /// # Errors
    /// * Unknown, diesel doesn't say why it might error.
    pub async fn find(
        search_parameters: LayerSearchParameters,
        conn: &mut AsyncPgConnection,
    ) -> QueryResult<Vec<LayerDto>> {
        let mut query = layers::table.select(layers::all_columns).into_boxed();

        if let Some(map_id_search) = search_parameters.map_id {
            query = query.filter(layers::map_id.eq(map_id_search));
        }
        if let Some(type_search) = search_parameters.type_ {
            query = query.filter(layers::type_.eq(type_search));
        }
        if let Some(is_alternative_search) = search_parameters.is_alternative {
            query = query.filter(layers::is_alternative.eq(is_alternative_search));
        }

        if search_parameters.only_non_deleted.is_some() {
            query = query.filter(layers::marked_deleted.is_null());
        }

        query = query.order((layers::order_index, layers::marked_deleted.desc()));

        debug!("{}", debug_query::<Pg, _>(&query));
        Ok(query
            .load::<Self>(conn)
            .await?
            .into_iter()
            .map(Into::into)
            .collect())
    }

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

    /// Defer checking of the unique constraint (`map_id`, `order_index`, `marked_deleted`)
    /// until the end of the current transaction.
    ///
    /// # Errors
    /// * Unknown, diesel doesn't say why it might error.
    async fn defer_unique_order_index_constraint(
        transaction: &mut AsyncPgConnection,
    ) -> QueryResult<()> {
        sql_query("SET CONSTRAINTS layers_map_id_order_index_unique DEFERRED")
            .execute(transaction)
            .await?;
        Ok(())
    }

    /// Helper to increment or decrement  all layers with `order_index`
    /// greater or equal the provided index. This is used when layers get
    /// deleted/restored to shift all subsequent layers up/down one place.
    ///
    /// # Errors
    /// * Unknown, diesel doesn't say why it might error.
    async fn shift_order_indices_by(
        map_id: i32,
        order_index: i32,
        increment: bool,
        transaction: &mut AsyncPgConnection,
    ) -> QueryResult<()> {
        let layer_ids = Self::find(
            LayerSearchParameters {
                is_alternative: None,
                map_id: Some(map_id),
                type_: None,
                only_non_deleted: Some(()),
            },
            transaction,
        )
        .await?;
        let updates = layer_ids
            .into_iter()
            .filter(|l| l.order_index >= order_index)
            .map(|l| UpdateLayerOrderIndex {
                id: l.id,
                order_index: l.order_index + if increment { 1 } else { -1 },
            })
            .collect();
        let futures = Self::do_order_update(updates, transaction);
        try_join_all(futures).await?;
        Ok(())
    }

    /// Rename a layer in the database.
    ///
    /// # Errors
    /// * Unknown, diesel doesn't say why it might error.
    pub async fn create(
        map_id: i32,
        new_layer: LayerDto,
        conn: &mut AsyncPgConnection,
    ) -> QueryResult<LayerDto> {
        let new_order_index = new_layer.order_index;
        let new_layer = Self::from((map_id, new_layer));
        let query = diesel::insert_into(layers::table).values(&new_layer);

        let created_layer = conn
            .transaction(|transaction| {
                Box::pin(async move {
                    Self::shift_order_indices_by(map_id, new_order_index, true, transaction)
                        .await?;
                    debug!("{}", debug_query::<Pg, _>(&query));
                    let layer_dto = query.get_result::<Self>(transaction).await?.into();
                    Ok::<LayerDto, diesel::result::Error>(layer_dto)
                })
            })
            .await?;
        Ok(created_layer)
    }

    /// Reorder multiple layers in the database. That means
    /// setting all `order_index` fields.
    ///
    /// # Errors
    /// * Unknown, diesel doesn't say why it might error.
    pub async fn reorder(new_order: Vec<Uuid>, conn: &mut AsyncPgConnection) -> QueryResult<()> {
        let order_updates: Vec<UpdateLayerOrderIndex> = new_order
            .into_iter()
            .zip(0..)
            .map(|(id, order_index)| UpdateLayerOrderIndex { id, order_index })
            .collect();

        conn.transaction(|transaction| {
            Box::pin(async move {
                // During the reordering process, the unique constraint on (map_id, order_index)
                // may be temporarily violated.
                // The constraint will be enforced when the transaction is finalized.
                Self::defer_unique_order_index_constraint(transaction).await?;
                let futures = Self::do_order_update(order_updates, transaction);
                try_join_all(futures).await?;
                Ok::<(), diesel::result::Error>(())
            })
        })
        .await?;

        Ok(())
    }

    /// This helper function is needed, with explicit type annotations.
    fn do_order_update(
        updates: Vec<UpdateLayerOrderIndex>,
        conn: &mut AsyncPgConnection,
    ) -> Vec<impl Future<Output = QueryResult<usize>>> {
        updates
            .into_iter()
            .map(|update| {
                diesel::update(layers::table.find(update.id))
                    .set(update)
                    .execute(conn)
            })
            .collect()
    }

    /// Rename layers in the database.
    ///
    /// # Errors
    /// * Unknown, diesel doesn't say why it might error.
    pub async fn rename(dto: LayerRenameDto, conn: &mut AsyncPgConnection) -> QueryResult<()> {
        let update: UpdateLayerName = dto.into();
        let query = diesel::update(layers::table.find(update.id)).set(&update);
        debug!("{}", debug_query::<Pg, _>(&query));
        query.execute(conn).await?;
        Ok(())
    }

    /// Soft-delete or restoring layers in the database by settings the `marked_deleted` field.
    ///
    /// # Errors
    /// * Unknown, diesel doesn't say why it might error.
    async fn set_marked_deleted(
        drawing_layer_id: Uuid,
        marked_deleted: bool,
        conn: &mut AsyncPgConnection,
    ) -> QueryResult<Self> {
        let marked_deleted_timestamp = marked_deleted.then(|| Utc::now().naive_utc());
        diesel::update(layers::table.find(drawing_layer_id))
            .set(UpdateLayerMarkedDeleted {
                id: drawing_layer_id,
                marked_deleted: marked_deleted_timestamp,
            })
            .get_result::<Self>(conn)
            .await
    }

    /// Soft-delete a layers in the database by settings the `marked_deleted` field to the current date.
    /// All subsequent layers are moved one `order_index` down.
    ///
    /// # Errors
    /// * Unknown, diesel doesn't say why it might error.
    pub async fn delete(
        map_id: i32,
        layer_id: Uuid,
        conn: &mut AsyncPgConnection,
    ) -> QueryResult<()> {
        conn.transaction(|transaction| {
            Box::pin(async move {
                let layer = Self::set_marked_deleted(layer_id, true, transaction).await?;
                Self::shift_order_indices_by(map_id, layer.order_index, false, transaction).await?;
                Ok(())
            })
        })
        .await
    }

    /// Restore a layers that has been marked deleted in the database.
    /// The layer takes on its previous `order_index` and all subsequent
    /// layers are moved one layer down.
    ///
    /// # Errors
    /// * Unknown, diesel doesn't say why it might error.
    pub async fn restore(
        map_id: i32,
        layer_id: Uuid,
        conn: &mut AsyncPgConnection,
    ) -> QueryResult<()> {
        conn.transaction(|transaction| {
            Box::pin(async move {
                Self::defer_unique_order_index_constraint(transaction).await?;
                let layer = Self::find_by_id(layer_id, transaction).await?;
                Self::shift_order_indices_by(map_id, layer.order_index, true, transaction).await?;
                _ = Self::set_marked_deleted(layer_id, false, transaction).await?;
                Ok(())
            })
        })
        .await
    }
}