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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
//! Contains the implementation of `Shading`, `Hydrology` and `SoilTexture`

use chrono::NaiveDate;
use diesel::{
    debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods, QueryDsl, QueryResult,
};
use diesel_async::{AsyncConnection, AsyncPgConnection, RunQueryDsl};
use log::debug;
use uuid::Uuid;

use crate::{
    model::{
        dto::areas::{AreaDto, AreaKind},
        entity::areas::{
            Hydrology, Shading, SoilTexture, UpdateHydrology, UpdateShading, UpdateSoilTexture,
        },
    },
    schema::{hydrologies, shadings, soil_textures},
};

/// Arguments for the database layer find shadings function.
pub struct FindAreaParameters {
    /// Type of area
    pub area_kind: AreaKind,
    /// The id of the layer to find shadings for.
    pub layer_id: Option<Uuid>,
    /// First date in the time frame shadings are searched for.
    pub from: NaiveDate,
    /// Last date in the time frame shadings are searched for.
    pub to: NaiveDate,
}

/// Get all areas from the appropriate table.
///
/// # Errors
/// * Unknown, diesel doesn't say why it might error.
pub async fn find_area(
    search_parameters: FindAreaParameters,
    conn: &mut AsyncPgConnection,
) -> QueryResult<Vec<AreaDto>> {
    match search_parameters.area_kind {
        AreaKind::Shade => {
            let mut query = shadings::table.select(shadings::all_columns).into_boxed();

            if let Some(id) = search_parameters.layer_id {
                query = query.filter(shadings::layer_id.eq(id));
            }

            let added_before_date = shadings::add_date
                .is_null()
                .or(shadings::add_date.lt(search_parameters.to));
            let removed_after_date = shadings::remove_date
                .is_null()
                .or(shadings::remove_date.gt(search_parameters.from));
            query = query.filter(added_before_date.and(removed_after_date));

            debug!("{}", debug_query::<Pg, _>(&query));

            Ok(query
                .load::<Shading>(conn)
                .await?
                .into_iter()
                .map(Into::into)
                .collect())
        }
        AreaKind::Hydrology => {
            let mut query = hydrologies::table
                .select(hydrologies::all_columns)
                .into_boxed();

            if let Some(id) = search_parameters.layer_id {
                query = query.filter(hydrologies::layer_id.eq(id));
            }

            let added_before_date = hydrologies::add_date
                .is_null()
                .or(hydrologies::add_date.lt(search_parameters.to));
            let removed_after_date = hydrologies::remove_date
                .is_null()
                .or(hydrologies::remove_date.gt(search_parameters.from));
            query = query.filter(added_before_date.and(removed_after_date));

            debug!("{}", debug_query::<Pg, _>(&query));

            Ok(query
                .load::<Hydrology>(conn)
                .await?
                .into_iter()
                .map(Into::into)
                .collect())
        }
        AreaKind::SoilTexture => {
            let mut query = soil_textures::table
                .select(soil_textures::all_columns)
                .into_boxed();

            if let Some(id) = search_parameters.layer_id {
                query = query.filter(soil_textures::layer_id.eq(id));
            }

            let added_before_date = soil_textures::add_date
                .is_null()
                .or(soil_textures::add_date.lt(search_parameters.to));
            let removed_after_date = soil_textures::remove_date
                .is_null()
                .or(soil_textures::remove_date.gt(search_parameters.from));
            query = query.filter(added_before_date.and(removed_after_date));

            debug!("{}", debug_query::<Pg, _>(&query));

            Ok(query
                .load::<SoilTexture>(conn)
                .await?
                .into_iter()
                .map(Into::into)
                .collect())
        }
    }
}

/// Save shadings in the database.
///
/// # Errors
/// * Unknown, diesel doesn't say why it might error.
pub async fn create_shadings(
    new_shadings: Vec<Shading>,
    conn: &mut AsyncPgConnection,
) -> QueryResult<Vec<AreaDto>> {
    let query = diesel::insert_into(shadings::table).values(&new_shadings);
    debug!("{}", debug_query::<Pg, _>(&query));
    let shadings = query
        .get_results::<Shading>(conn)
        .await?
        .into_iter()
        .map(Into::into)
        .collect::<Vec<AreaDto>>();
    Ok(shadings)
}

/// Save hydrologies in the database.
///
/// # Errors
/// * Unknown, diesel doesn't say why it might error.
pub async fn create_hydrologies(
    new_hydrologies: Vec<Hydrology>,
    conn: &mut AsyncPgConnection,
) -> QueryResult<Vec<AreaDto>> {
    let query = diesel::insert_into(hydrologies::table).values(&new_hydrologies);
    debug!("{}", debug_query::<Pg, _>(&query));
    let hydrologies = query
        .get_results::<Hydrology>(conn)
        .await?
        .into_iter()
        .map(Into::into)
        .collect::<Vec<AreaDto>>();
    Ok(hydrologies)
}

/// Save soil textures in the database.
///
/// # Errors
/// * Unknown, diesel doesn't say why it might error.
pub async fn create_soil_textures(
    new_soil_textures: Vec<SoilTexture>,
    conn: &mut AsyncPgConnection,
) -> QueryResult<Vec<AreaDto>> {
    let query = diesel::insert_into(soil_textures::table).values(&new_soil_textures);
    debug!("{}", debug_query::<Pg, _>(&query));
    let soil_textures = query
        .get_results::<SoilTexture>(conn)
        .await?
        .into_iter()
        .map(Into::into)
        .collect::<Vec<AreaDto>>();
    Ok(soil_textures)
}

/// Update shading areas in the database.
///
/// # Errors
/// * Unknown, diesel doesn't say why it might error.
pub async fn update_shadings(
    updates: Vec<UpdateShading>,
    conn: &mut AsyncPgConnection,
) -> QueryResult<Vec<AreaDto>> {
    conn.transaction(|transaction| {
        Box::pin(async {
            let mut results = Vec::with_capacity(updates.len());
            for update in updates {
                results.push(AreaDto::from(
                    diesel::update(shadings::table.find(update.id))
                        .set(update)
                        .get_result::<Shading>(transaction)
                        .await?,
                ));
            }
            Ok(results) as QueryResult<Vec<AreaDto>>
        })
    })
    .await
}

/// Update hydrology areas in the database.
///
/// # Errors
/// * Unknown, diesel doesn't say why it might error.
pub async fn update_hydrologies(
    updates: Vec<UpdateHydrology>,
    conn: &mut AsyncPgConnection,
) -> QueryResult<Vec<AreaDto>> {
    conn.transaction(|transaction| {
        Box::pin(async {
            let mut results = Vec::with_capacity(updates.len());
            for update in updates {
                results.push(AreaDto::from(
                    diesel::update(hydrologies::table.find(update.id))
                        .set(update)
                        .get_result::<Hydrology>(transaction)
                        .await?,
                ));
            }
            Ok(results) as QueryResult<Vec<AreaDto>>
        })
    })
    .await
}

/// Update soil texture areas in the database.
///
/// # Errors
/// * Unknown, diesel doesn't say why it might error.
pub async fn update_soil_textures(
    updates: Vec<UpdateSoilTexture>,
    conn: &mut AsyncPgConnection,
) -> QueryResult<Vec<AreaDto>> {
    conn.transaction(|transaction| {
        Box::pin(async {
            let mut results = Vec::with_capacity(updates.len());
            for update in updates {
                results.push(AreaDto::from(
                    diesel::update(soil_textures::table.find(update.id))
                        .set(update)
                        .get_result::<SoilTexture>(transaction)
                        .await?,
                ));
            }
            Ok(results) as QueryResult<Vec<AreaDto>>
        })
    })
    .await
}

/// Delete the shading from the database.
///
/// # Errors
/// * Unknown, diesel doesn't say why it might error.
pub async fn delete_areas_by_ids(
    area_kind: AreaKind,
    ids: Vec<Uuid>,
    conn: &mut AsyncPgConnection,
) -> QueryResult<usize> {
    let result = match area_kind {
        AreaKind::Shade => {
            let query = diesel::delete(shadings::table.filter(shadings::id.eq_any(ids)));
            debug!("{}", debug_query::<Pg, _>(&query));
            query.execute(conn).await?
        }
        AreaKind::Hydrology => {
            let query = diesel::delete(hydrologies::table.filter(hydrologies::id.eq_any(ids)));
            debug!("{}", debug_query::<Pg, _>(&query));
            query.execute(conn).await?
        }
        AreaKind::SoilTexture => {
            let query = diesel::delete(soil_textures::table.filter(soil_textures::id.eq_any(ids)));
            debug!("{}", debug_query::<Pg, _>(&query));
            query.execute(conn).await?
        }
    };
    Ok(result)
}