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
use crate::{
    db::{
        models::snapshot::{Contribution, Snapshot, Voter},
        schema::{contributions, snapshots, voters},
        DbConnection, DbConnectionPool,
    },
    utils::collections::dedup_by_key_keep_last,
    v0::errors::HandleError,
};
use diesel::{
    pg::upsert::excluded, Connection, ExpressionMethods, QueryDsl, QueryResult, RunQueryDsl,
};
use itertools::Itertools;

const BATCH_PUT_CHUNK_SIZE: usize = 1000;

pub async fn query_all_snapshots(pool: &DbConnectionPool) -> Result<Vec<Snapshot>, HandleError> {
    let db_conn = pool.get().map_err(HandleError::DatabaseError)?;
    tokio::task::spawn_blocking(move || {
        snapshots::dsl::snapshots
            .order_by(snapshots::dsl::last_updated.asc())
            .load(&db_conn)
            .map_err(|e| HandleError::InternalError(format!("Error retrieving snapshot: {}", e)))
    })
    .await
    .map_err(|e| HandleError::InternalError(format!("Error executing request: {}", e)))?
}

pub async fn query_snapshot_by_tag(
    tag: String,
    pool: &DbConnectionPool,
) -> Result<Snapshot, HandleError> {
    let db_conn = pool.get().map_err(HandleError::DatabaseError)?;
    tokio::task::spawn_blocking(move || {
        snapshots::dsl::snapshots
            .filter(snapshots::dsl::tag.eq(tag))
            .first(&db_conn)
            .map_err(|e| HandleError::NotFound(format!("Error loading snapshot: {}", e)))
    })
    .await
    .map_err(|e| HandleError::InternalError(format!("Error executing request: {}", e)))?
}

pub fn put_snapshot(snapshot: Snapshot, pool: &DbConnectionPool) -> Result<(), HandleError> {
    let db_conn = pool.get().map_err(HandleError::DatabaseError)?;

    // TODO: Find a better way to do this?
    //
    // This is needed when moving from SQLite to Postgres
    // because it used to be a replace_into call which
    // is actually a delete followed by a insert in SQLite and
    // this triggers the 'ON DELETE CASCADE' of voters and contributions
    // tables.
    db_conn
        .transaction(|| {
            diesel::delete(snapshots::table)
                .filter(snapshots::tag.eq(&snapshot.tag))
                .execute(&db_conn)?;

            diesel::insert_into(snapshots::table)
                .values(snapshot)
                .execute(&db_conn)
        })
        .map_err(|e| HandleError::InternalError(format!("Error executing request: {}", e)))?;
    Ok(())
}

pub async fn query_voters_by_snapshot_tag(
    tag: String,
    pool: &DbConnectionPool,
) -> Result<Vec<Voter>, HandleError> {
    let db_conn = pool.get().map_err(HandleError::DatabaseError)?;
    tokio::task::spawn_blocking(move || {
        voters::dsl::voters
            .filter(voters::dsl::snapshot_tag.eq(tag))
            .load(&db_conn)
            .map_err(|e| HandleError::NotFound(format!("Error loading voters: {}", e)))
    })
    .await
    .map_err(|e| HandleError::InternalError(format!("Error executing voters: {}", e)))?
}

pub async fn query_voters_by_voting_key_and_snapshot_tag(
    voting_key: String,
    tag: String,
    pool: &DbConnectionPool,
) -> Result<Vec<Voter>, HandleError> {
    let db_conn = pool.get().map_err(HandleError::DatabaseError)?;
    tokio::task::spawn_blocking(move || {
        voters::dsl::voters
            .filter(voters::dsl::voting_key.eq(voting_key))
            .filter(voters::dsl::snapshot_tag.eq(tag))
            .load(&db_conn)
            .map_err(|e| HandleError::NotFound(format!("Error loading voters: {}", e)))
    })
    .await
    .map_err(|e| HandleError::InternalError(format!("Error executing voters: {}", e)))?
}

pub async fn query_total_voting_power_by_voting_group_and_snapshot_tag(
    voting_group: String,
    tag: String,
    pool: &DbConnectionPool,
) -> Result<i64, HandleError> {
    let db_conn = pool.get().map_err(HandleError::DatabaseError)?;
    tokio::task::spawn_blocking(move || {
        voters::dsl::voters
            .filter(voters::dsl::voting_group.eq(voting_group))
            .filter(voters::dsl::snapshot_tag.eq(tag))
            .load::<Voter>(&db_conn)
            .map_err(|e| HandleError::NotFound(format!("Error loading voters: {}", e)))
            .map(|voters| voters.iter().map(|voter| voter.voting_power).sum())
    })
    .await
    .map_err(|e| HandleError::InternalError(format!("Error executing voters: {}", e)))?
}

pub fn batch_put_voters(voters: &[Voter], db_conn: &DbConnection) -> Result<(), HandleError> {
    // Postgres will not allow batch inserting if there are any values that would modify the same row twice.
    // SQLite allowed it. Then, for Postgres, we keep only the latest conflicting value.
    let unique_voters = dedup_by_key_keep_last(voters.iter(), |v| {
        (&v.voting_key, &v.voting_group, &v.snapshot_tag)
    });

    db_conn
        .build_transaction()
        .read_write()
        .run(move || {
            for chunk in &unique_voters.into_iter().chunks(BATCH_PUT_CHUNK_SIZE) {
                diesel::insert_into(voters::table)
                    .values(chunk.collect::<Vec<_>>())
                    .on_conflict((
                        voters::voting_key,
                        voters::voting_group,
                        voters::snapshot_tag,
                    ))
                    .do_update()
                    .set((voters::voting_power.eq(excluded(voters::voting_power)),))
                    .execute(db_conn)?;
            }

            QueryResult::Ok(())
        })
        .map_err(|e| HandleError::InternalError(format!("Error executing request: {}", e)))
}

pub async fn query_contributions_by_voting_key_and_voter_group_and_snapshot_tag(
    voting_key: String,
    voting_group: String,
    tag: String,
    pool: &DbConnectionPool,
) -> Result<Vec<Contribution>, HandleError> {
    let db_conn = pool.get().map_err(HandleError::DatabaseError)?;
    tokio::task::spawn_blocking(move || {
        contributions::dsl::contributions
            .filter(contributions::dsl::voting_key.eq(voting_key))
            .filter(contributions::dsl::voting_group.eq(voting_group))
            .filter(contributions::dsl::snapshot_tag.eq(tag))
            .load(&db_conn)
            .map_err(|e| HandleError::NotFound(format!("Error loading contributions: {}", e)))
    })
    .await
    .map_err(|e| HandleError::InternalError(format!("Error executing request: {}", e)))?
}

pub async fn query_contributions_by_snapshot_tag(
    tag: String,
    pool: &DbConnectionPool,
) -> Result<Vec<Contribution>, HandleError> {
    let db_conn = pool.get().map_err(HandleError::DatabaseError)?;
    tokio::task::spawn_blocking(move || {
        contributions::dsl::contributions
            .filter(contributions::dsl::snapshot_tag.eq(tag))
            .load(&db_conn)
            .map_err(|e| HandleError::NotFound(format!("Error loading contributions: {}", e)))
    })
    .await
    .map_err(|e| HandleError::InternalError(format!("Error executing request: {}", e)))?
}

pub async fn query_contributions_by_stake_public_key_and_snapshot_tag(
    stake_public_key: String,
    tag: String,
    pool: &DbConnectionPool,
) -> Result<Vec<Contribution>, HandleError> {
    let db_conn = pool.get().map_err(HandleError::DatabaseError)?;
    tokio::task::spawn_blocking(move || {
        contributions::dsl::contributions
            .filter(contributions::dsl::stake_public_key.eq(stake_public_key))
            .filter(contributions::dsl::snapshot_tag.eq(tag))
            .load(&db_conn)
            .map_err(|e| HandleError::NotFound(format!("Error loading contributions: {}", e)))
    })
    .await
    .map_err(|e| HandleError::InternalError(format!("Error executing request: {}", e)))?
}

pub fn batch_put_contributions(
    contributions: &[Contribution],
    db_conn: &DbConnection,
) -> Result<(), HandleError> {
    // Postgres will not allow batch inserting if there are any values that would modify the same row twice.
    // SQLite allowed it. Then, for Postgres, we keep only the latest conflicting value.
    let unique_contributions = dedup_by_key_keep_last(contributions.iter(), |c| {
        (
            &c.stake_public_key,
            &c.voting_group,
            &c.voting_key,
            &c.snapshot_tag,
        )
    });

    db_conn
        .build_transaction()
        .read_write()
        .run(move || {
            for chunk in &unique_contributions
                .into_iter()
                .chunks(BATCH_PUT_CHUNK_SIZE)
            {
                diesel::insert_into(contributions::table)
                    .values(chunk.collect::<Vec<_>>())
                    .on_conflict((
                        contributions::stake_public_key,
                        contributions::voting_group,
                        contributions::voting_key,
                        contributions::snapshot_tag,
                    ))
                    .do_update()
                    .set((
                        contributions::reward_address.eq(excluded(contributions::reward_address)),
                        contributions::value.eq(excluded(contributions::value)),
                    ))
                    .execute(db_conn)?;
            }

            QueryResult::Ok(())
        })
        .map_err(|e| HandleError::InternalError(format!("Error executing request: {}", e)))
}