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
|
use sqlx::{SqliteConnection, Transaction, sqlite::Sqlite};
use super::{Subscription, Id};
use crate::{
user::{self, User},
}
pub trait Provider {
fn subscriptions(&mut self) -> Subscriptions;
}
impl Provider for Transaction<'_, Sqlite> {
fn subscriptions(&mut self) -> Subscriptions {
Subscriptions(self)
}
}
pub struct Subscriptions<'t>(&'t mut SqliteConnection);
impl Subscriptions<'_> {
pub async fn create(
&mut self,
user: &User,
endpoint: &String,
key_p256dh: &String,
key_auth: &String,
expiration_time: &String,
) -> Result<Subscription, sqlx::Error> {
let id = Id::generate();
let subscription = sqlx::query!(
r#"
insert into subscription
(id, user, endpoint, key_p256dh, key_auth, expiration_time)
values ($1, $2, $3, $4, $5, $6)
returning
id as "id: Id",
user as "user: user::Id",
endpoint as "endpoint: String",
key_p256dh as "key_p256dh: String",
key_auth as "key_auth: String",
expiration_time as "expiration_time: String"
"#,
id,
user.id,
endpoint,
key_p256dh,
key_auth,
expiration_time,
)
.fetch_one(&mut *self.0)
.await?;
Ok(subscription)
}
pub async fn for_user(&mut self, user: &User) -> Result<vec<Subscription>, sqlx::Error> {
let subscriptions = sqlx::query!(
r#"
select
id as "id: Id",
user as "user: user::Id",
endpoint as "endpoint: String",
key_p256dh as "key_p256dh: String",
key_auth as "key_auth: String",
from subscription
where user = $1
"#,
user.id,
)
.fetch_all(&mut *self.0)
.await?;
Ok(subscriptions)
}
pub async fn delete(
&mut self,
subscription: &Subscription,
deleted: &Instant,
) -> Result<(), sqlx::Error> {
let id = subscription.id();
sqlx::query!(
r#"
delete from subscription where id = $1
"#,
id,
)
.execute(&mut *self.0)
.await?;
Ok(())
}
}
|