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
|
use serde::{Deserialize, Serialize};
use sqlx::FromRow;
use utoipa::ToSchema;
#[derive(Debug, Serialize, Deserialize, FromRow, Clone, PartialEq, ToSchema)]
pub struct WeatherThreshold {
pub id: i64,
pub user_id: i64,
pub condition_type: String,
pub threshold_value: f64,
pub operator: String,
pub enabled: bool,
pub description: Option<String>,
}
pub struct WeatherThresholdUpdateInput {
pub id: i64,
pub user_id: i64,
pub condition_type: String,
pub threshold_value: f64,
pub operator: String,
pub enabled: bool,
pub description: Option<String>,
}
pub struct WeatherThresholdRepository<'a> {
pub db: &'a sqlx::SqlitePool,
}
impl<'a> WeatherThresholdRepository<'a> {
pub async fn list_thresholds(
&self,
user_id: i64,
) -> Result<Vec<WeatherThreshold>, sqlx::Error> {
sqlx::query_as::<_, WeatherThreshold>(
"SELECT id, user_id, condition_type, threshold_value, operator, enabled, description FROM weather_thresholds WHERE user_id = ?"
)
.bind(user_id)
.fetch_all(self.db)
.await
}
pub async fn get_threshold(
&self,
id: i64,
user_id: i64,
) -> Result<Option<WeatherThreshold>, sqlx::Error> {
sqlx::query_as::<_, WeatherThreshold>(
"SELECT id, user_id, condition_type, threshold_value, operator, enabled, description FROM weather_thresholds WHERE id = ? AND user_id = ?"
)
.bind(id)
.bind(user_id)
.fetch_optional(self.db)
.await
}
pub async fn create_threshold(
&self,
user_id: i64,
condition_type: String,
threshold_value: f64,
operator: String,
enabled: bool,
description: Option<String>,
) -> Result<WeatherThreshold, sqlx::Error> {
sqlx::query_as::<_, WeatherThreshold>(
"INSERT INTO weather_thresholds (user_id, condition_type, threshold_value, operator, enabled, description) VALUES (?, ?, ?, ?, ?, ?) RETURNING id, user_id, condition_type, threshold_value, operator, enabled, description"
)
.bind(user_id)
.bind(condition_type)
.bind(threshold_value)
.bind(operator)
.bind(enabled)
.bind(description)
.fetch_one(self.db)
.await
}
pub async fn update_threshold(
&self,
input: WeatherThresholdUpdateInput,
) -> Result<WeatherThreshold, sqlx::Error> {
sqlx::query_as::<_, WeatherThreshold>(
"UPDATE weather_thresholds SET condition_type = ?, threshold_value = ?, operator = ?, enabled = ?, description = ? WHERE id = ? AND user_id = ? RETURNING id, user_id, condition_type, threshold_value, operator, enabled, description"
)
.bind(input.condition_type)
.bind(input.threshold_value)
.bind(input.operator)
.bind(input.enabled)
.bind(input.description)
.bind(input.id)
.bind(input.user_id)
.fetch_one(self.db)
.await
}
pub async fn delete_threshold(&self, id: i64, user_id: i64) -> Result<(), sqlx::Error> {
sqlx::query("DELETE FROM weather_thresholds WHERE id = ? AND user_id = ?")
.bind(id)
.bind(user_id)
.execute(self.db)
.await?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::users::{UserRepository, UserRole};
use sqlx::{Executor, SqlitePool};
async fn setup_db() -> SqlitePool {
let pool = SqlitePool::connect(":memory:").await.unwrap();
pool.execute(
"CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL UNIQUE,
role TEXT NOT NULL DEFAULT 'user'
);",
)
.await
.unwrap();
pool.execute(
"CREATE TABLE weather_thresholds (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
condition_type TEXT NOT NULL,
threshold_value REAL NOT NULL,
operator TEXT NOT NULL,
enabled BOOLEAN NOT NULL DEFAULT 1,
description TEXT,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);",
)
.await
.unwrap();
pool
}
async fn create_user(pool: &SqlitePool) -> i64 {
let repo = UserRepository { db: pool };
let user = repo.create_user(None, Some(UserRole::User)).await.unwrap();
user.id
}
#[tokio::test]
async fn test_create_and_get_threshold() {
let db = setup_db().await;
let user_id = create_user(&db).await;
let repo = WeatherThresholdRepository { db: &db };
let th = repo
.create_threshold(
user_id,
"wind_speed".to_string(),
10.0,
">".to_string(),
true,
Some("desc".to_string()),
)
.await
.unwrap();
let fetched = repo.get_threshold(th.id, user_id).await.unwrap().unwrap();
assert_eq!(fetched.condition_type, "wind_speed");
assert_eq!(fetched.threshold_value, 10.0);
assert_eq!(fetched.operator, ">");
assert!(fetched.enabled);
assert_eq!(fetched.description, Some("desc".to_string()));
}
#[tokio::test]
async fn test_update_threshold() {
let db = setup_db().await;
let user_id = create_user(&db).await;
let repo = WeatherThresholdRepository { db: &db };
let th = repo
.create_threshold(
user_id,
"wind_speed".to_string(),
10.0,
">".to_string(),
true,
None,
)
.await
.unwrap();
let updated = repo
.update_threshold(WeatherThresholdUpdateInput {
id: th.id,
user_id,
condition_type: "rain".to_string(),
threshold_value: 5.0,
operator: "<".to_string(),
enabled: false,
description: Some("rain desc".to_string()),
})
.await
.unwrap();
assert_eq!(updated.condition_type, "rain");
assert_eq!(updated.threshold_value, 5.0);
assert_eq!(updated.operator, "<");
assert!(!updated.enabled);
assert_eq!(updated.description, Some("rain desc".to_string()));
}
#[tokio::test]
async fn test_delete_threshold() {
let db = setup_db().await;
let user_id = create_user(&db).await;
let repo = WeatherThresholdRepository { db: &db };
let th = repo
.create_threshold(
user_id,
"wind_speed".to_string(),
10.0,
">".to_string(),
true,
None,
)
.await
.unwrap();
repo.delete_threshold(th.id, user_id).await.unwrap();
let fetched = repo.get_threshold(th.id, user_id).await.unwrap();
assert!(fetched.is_none());
}
#[tokio::test]
async fn test_list_thresholds() {
let db = setup_db().await;
let user_id = create_user(&db).await;
let repo = WeatherThresholdRepository { db: &db };
repo.create_threshold(
user_id,
"wind_speed".to_string(),
10.0,
">".to_string(),
true,
None,
)
.await
.unwrap();
repo.create_threshold(
user_id,
"rain".to_string(),
5.0,
"<".to_string(),
false,
None,
)
.await
.unwrap();
let thresholds = repo.list_thresholds(user_id).await.unwrap();
assert_eq!(thresholds.len(), 2);
}
}
|