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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
use crate::db::TotalCount;
use chrono::Utc;
use primitives::{sentry::Pagination, spender::Spendable, Address, ChannelId};
use super::{DbPool, PoolError};
pub async fn insert_spendable(pool: DbPool, spendable: &Spendable) -> Result<bool, PoolError> {
let client = pool.get().await?;
let stmt = client
.prepare(
"INSERT INTO spendable (spender, channel_id, total, created) values ($1, $2, $3, $4)",
)
.await?;
let row = client
.execute(
&stmt,
&[
&spendable.spender,
&spendable.channel.id(),
&spendable.deposit.total,
&Utc::now(),
],
)
.await?;
let is_inserted = row == 1;
Ok(is_inserted)
}
pub async fn fetch_spendable(
pool: DbPool,
spender: &Address,
channel_id: &ChannelId,
) -> Result<Option<Spendable>, PoolError> {
let client = pool.get().await?;
let statement = client.prepare("SELECT spender, total, spendable.created, channels.leader, channels.follower, channels.guardian, channels.token, channels.nonce FROM spendable INNER JOIN channels ON channels.id = spendable.channel_id WHERE spender = $1 AND channel_id = $2").await?;
let row = client.query_opt(&statement, &[spender, channel_id]).await?;
Ok(row.as_ref().map(Spendable::from))
}
pub async fn get_all_spendables_for_channel(
pool: DbPool,
channel_id: &ChannelId,
skip: u64,
limit: u64,
) -> Result<(Vec<Spendable>, Pagination), PoolError> {
let client = pool.get().await?;
let query = format!("SELECT spender, total, spendable.created, channels.leader, channels.follower, channels.guardian, channels.token, channels.nonce FROM spendable INNER JOIN channels ON channels.id = spendable.channel_id WHERE channel_id = $1 ORDER BY spendable.created ASC LIMIT {} OFFSET {}", limit, skip);
let statement = client.prepare(&query).await?;
let rows = client.query(&statement, &[channel_id]).await?;
let spendables = rows.iter().map(Spendable::from).collect();
let total_count = list_spendable_total_count(&pool, channel_id).await?;
let total_pages = if total_count == 0 {
1
} else {
1 + ((total_count - 1) / limit as u64)
};
let pagination = Pagination {
total_pages,
page: skip / limit as u64,
};
Ok((spendables, pagination))
}
static UPDATE_SPENDABLE_STATEMENT: &str = "WITH inserted_spendable AS (INSERT INTO spendable(spender, channel_id, total, created) VALUES($1, $2, $3, $4) ON CONFLICT ON CONSTRAINT spendable_pkey DO UPDATE SET total = $3 WHERE spendable.spender = $1 AND spendable.channel_id = $2 RETURNING *) SELECT inserted_spendable.*, channels.leader, channels.follower, channels.guardian, channels.token, channels.nonce FROM inserted_spendable INNER JOIN channels ON inserted_spendable.channel_id = channels.id";
pub async fn update_spendable(pool: DbPool, spendable: &Spendable) -> Result<Spendable, PoolError> {
let client = pool.get().await?;
let statement = client.prepare(UPDATE_SPENDABLE_STATEMENT).await?;
let row = client
.query_one(
&statement,
&[
&spendable.spender,
&spendable.channel.id(),
&spendable.deposit.total,
&Utc::now(),
],
)
.await?;
Ok(Spendable::from(&row))
}
async fn list_spendable_total_count<'a>(
pool: &DbPool,
channel_id: &ChannelId,
) -> Result<u64, PoolError> {
let client = pool.get().await?;
let statement = "SELECT COUNT(spendable)::varchar FROM spendable WHERE channel_id = $1";
let stmt = client.prepare(statement).await?;
let row = client.query_one(&stmt, &[&channel_id]).await?;
Ok(row.get::<_, TotalCount>(0).0)
}
#[cfg(test)]
mod test {
use std::collections::HashMap;
use primitives::{
config::GANACHE_CONFIG,
spender::Spendable,
test_util::DUMMY_CAMPAIGN,
test_util::{ADVERTISER, CREATOR, FOLLOWER, GUARDIAN, GUARDIAN_2, PUBLISHER},
Deposit, UnifiedNum,
};
use crate::db::{
insert_channel,
tests_postgres::{setup_test_migrations, DATABASE_POOL},
};
use tokio::time::{sleep, Duration};
use super::*;
#[tokio::test]
async fn it_inserts_and_fetches_and_updates_spendable() {
let database = DATABASE_POOL.get().await.expect("Should get a DB pool");
setup_test_migrations(database.pool.clone())
.await
.expect("Migrations should succeed");
let spendable = Spendable {
spender: *ADVERTISER,
channel: DUMMY_CAMPAIGN.channel,
deposit: Deposit {
total: UnifiedNum::from(100_000_000),
},
};
let channel_chain = GANACHE_CONFIG
.find_chain_of(DUMMY_CAMPAIGN.channel.token)
.expect("Channel token should be whitelisted in config!");
let channel_context = channel_chain.with_channel(spendable.channel);
insert_channel(&database.pool, &channel_context)
.await
.expect("Should insert Channel before creating spendable");
let is_inserted = insert_spendable(database.pool.clone(), &spendable)
.await
.expect("Should succeed");
sleep(Duration::from_millis(100)).await;
assert!(is_inserted);
let fetched_spendable = fetch_spendable(
database.pool.clone(),
&spendable.spender,
&spendable.channel.id(),
)
.await
.expect("Should fetch successfully");
assert_eq!(Some(spendable), fetched_spendable);
}
fn new_spendable_with(spender: &Address) -> Spendable {
Spendable {
spender: *spender,
channel: DUMMY_CAMPAIGN.channel,
deposit: Deposit {
total: UnifiedNum::from(100_000_000),
},
}
}
#[tokio::test]
async fn insert_and_get_single_spendable_for_channel() {
let database = DATABASE_POOL.get().await.expect("Should get a DB pool");
setup_test_migrations(database.pool.clone())
.await
.expect("Migrations should succeed");
let channel = DUMMY_CAMPAIGN.channel;
let channel_chain = GANACHE_CONFIG
.find_chain_of(DUMMY_CAMPAIGN.channel.token)
.expect("Channel token should be whitelisted in config!");
let channel_context = channel_chain.with_channel(channel);
insert_channel(&database, &channel_context)
.await
.expect("Should insert");
let (spendables, pagination) =
get_all_spendables_for_channel(database.clone(), &channel.id(), 0, 2)
.await
.expect("should get result");
assert!(spendables.is_empty());
assert_eq!(pagination.total_pages, 1);
let spendable_user = new_spendable_with(&FOLLOWER);
insert_spendable(database.pool.clone(), &spendable_user)
.await
.expect("should insert spendable");
sleep(Duration::from_millis(100)).await;
let (spendables, pagination) =
get_all_spendables_for_channel(database.clone(), &channel.id(), 0, 2)
.await
.expect("should get result");
let expected_spendables = vec![spendable_user.clone()];
let expected_pagination = Pagination {
page: 0,
total_pages: 1,
};
pretty_assertions::assert_eq!(spendables, expected_spendables);
pretty_assertions::assert_eq!(pagination, expected_pagination);
}
#[tokio::test]
async fn gets_multiple_pages_of_spendables_for_channel() {
let database = DATABASE_POOL.get().await.expect("Should get a DB pool");
setup_test_migrations(database.pool.clone())
.await
.expect("Migrations should succeed");
let channel = DUMMY_CAMPAIGN.channel;
let channel_chain = GANACHE_CONFIG
.find_chain_of(DUMMY_CAMPAIGN.channel.token)
.expect("Channel token should be whitelisted in config!");
let channel_context = channel_chain.with_channel(channel);
insert_channel(&database, &channel_context)
.await
.expect("Should insert");
let create_spendables: Vec<(Address, Spendable)> = vec![
(*PUBLISHER, new_spendable_with(&PUBLISHER)),
(*ADVERTISER, new_spendable_with(&ADVERTISER)),
(*CREATOR, new_spendable_with(&CREATOR)),
(*GUARDIAN, new_spendable_with(&GUARDIAN)),
(*GUARDIAN_2, new_spendable_with(&GUARDIAN_2)),
];
for (address, spendable) in create_spendables.iter() {
insert_spendable(database.pool.clone(), spendable)
.await
.unwrap_or_else(|_| {
panic!(
"Failed to insert spendable for {:?} with Spendable: {:?}",
address, spendable
)
});
sleep(Duration::from_millis(100)).await;
}
let spendables = create_spendables.into_iter().collect::<HashMap<_, _>>();
let expected_pages = vec![
(
vec![&spendables[&PUBLISHER], &spendables[&ADVERTISER]],
Pagination {
page: 0,
total_pages: 3,
},
),
(
vec![&spendables[&CREATOR], &spendables[&GUARDIAN]],
Pagination {
page: 1,
total_pages: 3,
},
),
(
vec![&spendables[&GUARDIAN_2]],
Pagination {
page: 2,
total_pages: 3,
},
),
];
for (expected_spendables, expected_pagination) in expected_pages.iter() {
let limit = 2;
let skip = expected_pagination.page * limit;
let debug_msg = format!(
"{:?} page = {} with skip = {} & limit = {}",
channel.id(),
expected_pagination.page,
skip,
limit
);
let (spendables, pagination) =
get_all_spendables_for_channel(database.clone(), &channel.id(), skip, limit)
.await
.unwrap_or_else(|_| panic!("could not fetch spendables {}", debug_msg));
pretty_assertions::assert_eq!(
&pagination,
expected_pagination,
"Unexpected pagination for {}",
debug_msg
);
pretty_assertions::assert_eq!(&spendables, expected_spendables);
}
}
}