OXYGENHUB
# 4f37afcc3583 oxygenhub / crates / hub / src / db / proposals.rs
11.4 KiB · Rust · last changed Admins disable, enable and delete accounts 1 month ago source blame history raw
1
//! The `proposals`, `proposal_comments`, `proposal_reviews` and
2
//! `proposal_events` tables, and the per-repository number space.
3
4
use super::{now_ms, Pool};
5
use sqlx::FromRow;
6
7
#[derive(Clone, Debug, FromRow)]
8
pub struct ProposalRow {
9
    pub id: i64,
10
    pub repo_id: i64,
11
    pub number: i64,
12
    pub title: String,
13
    pub body: String,
14
    pub author_id: Option<i64>,
15
    pub author: String,
16
    pub state: String,
17
    pub target: String,
18
    pub source_kind: String,
19
    pub source_repo_id: Option<i64>,
20
    pub source_bookmark: String,
21
    pub source_changes: String,
22
    pub projected_state: String,
23
    pub projected_heads: String,
24
    pub projected_target: String,
25
    pub projected_changes: String,
26
    pub conflicted: bool,
27
    pub landed_state: String,
28
    pub landed_by: String,
29
    pub landed_via: String,
30
    pub landed_ms: i64,
31
    pub created_ms: i64,
32
    pub updated_ms: i64,
33
}
34
35
impl ProposalRow {
36
    pub fn projected_heads(&self) -> Vec<String> {
37
        self.projected_heads.split(',').filter(|s| !s.is_empty()).map(String::from).collect()
38
    }
39
40
    pub fn projected_changes(&self) -> Vec<String> {
41
        self.projected_changes.split(',').filter(|s| !s.is_empty()).map(String::from).collect()
42
    }
43
44
    pub fn source_changes(&self) -> Vec<String> {
45
        self.source_changes.split(',').filter(|s| !s.is_empty()).map(String::from).collect()
46
    }
47
48
    pub fn is_open(&self) -> bool {
49
        self.state == "open" || self.state == "draft"
50
    }
51
}
52
53
#[derive(Clone, Debug, FromRow)]
54
pub struct CommentRow {
55
    pub id: i64,
56
    pub proposal_id: i64,
57
    pub author_id: Option<i64>,
58
    pub author: String,
59
    pub body: String,
60
    pub path: String,
61
    pub anchor_change: String,
62
    pub anchor_index: i64,
63
    pub resolved: bool,
64
    pub created_ms: i64,
65
}
66
67
#[derive(Clone, Debug, FromRow)]
68
pub struct ReviewRow {
69
    pub id: i64,
70
    pub proposal_id: i64,
71
    /// `None` once the author's account was deleted (its name stays).
72
    pub author_id: Option<i64>,
73
    pub author: String,
74
    pub verdict: String,
75
    pub body: String,
76
    pub created_ms: i64,
77
}
78
79
#[derive(Clone, Debug, FromRow)]
80
pub struct EventRow {
81
    pub id: i64,
82
    pub at_ms: i64,
83
    pub actor: String,
84
    pub event: String,
85
    pub detail: String,
86
}
87
88
/// Take the next number of a repository's shared number space.
89
pub async fn next_number(pool: &Pool, repo_id: i64) -> sqlx::Result<i64> {
90
    let mut tx = super::begin_write(pool).await?;
91
    sqlx::query("INSERT OR IGNORE INTO numbers (repo_id, next) VALUES (?, 1)").bind(repo_id).execute(&mut *tx).await?;
92
    let n: i64 = sqlx::query_scalar("SELECT next FROM numbers WHERE repo_id = ?").bind(repo_id).fetch_one(&mut *tx).await?;
93
    sqlx::query("UPDATE numbers SET next = next + 1 WHERE repo_id = ?").bind(repo_id).execute(&mut *tx).await?;
94
    tx.commit().await?;
95
    Ok(n)
96
}
97
98
pub struct NewProposal<'a> {
99
    pub repo_id: i64,
100
    pub title: &'a str,
101
    pub body: &'a str,
102
    pub author_id: Option<i64>,
103
    pub author: &'a str,
104
    pub draft: bool,
105
    pub target: &'a str,
106
    pub source_kind: &'a str,
107
    pub source_repo_id: Option<i64>,
108
    pub source_bookmark: &'a str,
109
    pub source_changes: &'a str,
110
}
111
112
pub async fn create(pool: &Pool, p: NewProposal<'_>) -> sqlx::Result<ProposalRow> {
113
    let number = next_number(pool, p.repo_id).await?;
114
    let now = now_ms();
115
    sqlx::query_as(
116
        "INSERT INTO proposals (repo_id, number, title, body, author_id, author, state, target, source_kind, source_repo_id, source_bookmark, source_changes, created_ms, updated_ms) \
117
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *",
118
    )
119
    .bind(p.repo_id)
120
    .bind(number)
121
    .bind(p.title)
122
    .bind(p.body)
123
    .bind(p.author_id)
124
    .bind(p.author)
125
    .bind(if p.draft { "draft" } else { "open" })
126
    .bind(p.target)
127
    .bind(p.source_kind)
128
    .bind(p.source_repo_id)
129
    .bind(p.source_bookmark)
130
    .bind(p.source_changes)
131
    .bind(now)
132
    .bind(now)
133
    .fetch_one(pool)
134
    .await
135
}
136
137
pub async fn get(pool: &Pool, repo_id: i64, number: i64) -> sqlx::Result<Option<ProposalRow>> {
138
    sqlx::query_as("SELECT * FROM proposals WHERE repo_id = ? AND number = ?").bind(repo_id).bind(number).fetch_optional(pool).await
139
}
140
141
pub async fn list(pool: &Pool, repo_id: i64, states: &[&str]) -> sqlx::Result<Vec<ProposalRow>> {
142
    let all: Vec<ProposalRow> =
143
        sqlx::query_as("SELECT * FROM proposals WHERE repo_id = ? ORDER BY number DESC").bind(repo_id).fetch_all(pool).await?;
144
    Ok(all.into_iter().filter(|p| states.is_empty() || states.contains(&p.state.as_str())).collect())
145
}
146
147
/// Open proposals of every repository, for the front page.
148
pub async fn open_for_author(pool: &Pool, author_id: i64) -> sqlx::Result<Vec<ProposalRow>> {
149
    sqlx::query_as("SELECT * FROM proposals WHERE author_id = ? AND state IN ('open', 'draft') ORDER BY updated_ms DESC")
150
        .bind(author_id)
151
        .fetch_all(pool)
152
        .await
153
}
154
155
pub async fn set_projection(
156
    pool: &Pool,
157
    id: i64,
158
    state: &str,
159
    heads: &str,
160
    target_state: &str,
161
    changes: &str,
162
    conflicted: bool,
163
) -> sqlx::Result<()> {
164
    sqlx::query("UPDATE proposals SET projected_state = ?, projected_heads = ?, projected_target = ?, projected_changes = ?, conflicted = ? WHERE id = ?")
165
        .bind(state)
166
        .bind(heads)
167
        .bind(target_state)
168
        .bind(changes)
169
        .bind(conflicted)
170
        .bind(id)
171
        .execute(pool)
172
        .await?;
173
    Ok(())
174
}
175
176
pub async fn set_state(pool: &Pool, id: i64, state: &str, landed_state: &str) -> sqlx::Result<()> {
177
    sqlx::query("UPDATE proposals SET state = ?, landed_state = ?, updated_ms = ? WHERE id = ?")
178
        .bind(state)
179
        .bind(landed_state)
180
        .bind(now_ms())
181
        .bind(id)
182
        .execute(pool)
183
        .await?;
184
    Ok(())
185
}
186
187
/// Mark a proposal landed, with who landed it and how.
188
pub async fn set_landed(pool: &Pool, id: i64, landed_state: &str, by: &str, via: &str) -> sqlx::Result<()> {
189
    let now = now_ms();
190
    sqlx::query(
191
        "UPDATE proposals SET state = 'landed', landed_state = ?, landed_by = ?, landed_via = ?, landed_ms = ?, updated_ms = ? WHERE id = ?",
192
    )
193
    .bind(landed_state)
194
    .bind(by)
195
    .bind(via)
196
    .bind(now)
197
    .bind(now)
198
    .bind(id)
199
    .execute(pool)
200
    .await?;
201
    Ok(())
202
}
203
204
pub async fn edit(pool: &Pool, id: i64, title: &str, body: &str, target: &str) -> sqlx::Result<()> {
205
    sqlx::query("UPDATE proposals SET title = ?, body = ?, target = ?, updated_ms = ? WHERE id = ?")
206
        .bind(title)
207
        .bind(body)
208
        .bind(target)
209
        .bind(now_ms())
210
        .bind(id)
211
        .execute(pool)
212
        .await?;
213
    Ok(())
214
}
215
216
pub async fn touch(pool: &Pool, id: i64) -> sqlx::Result<()> {
217
    sqlx::query("UPDATE proposals SET updated_ms = ? WHERE id = ?").bind(now_ms()).bind(id).execute(pool).await?;
218
    Ok(())
219
}
220
221
pub async fn comments(pool: &Pool, proposal_id: i64) -> sqlx::Result<Vec<CommentRow>> {
222
    sqlx::query_as("SELECT * FROM proposal_comments WHERE proposal_id = ? ORDER BY created_ms, id").bind(proposal_id).fetch_all(pool).await
223
}
224
225
pub async fn add_comment(
226
    pool: &Pool,
227
    proposal_id: i64,
228
    author_id: Option<i64>,
229
    author: &str,
230
    body: &str,
231
    path: &str,
232
    anchor: Option<(&str, i64)>,
233
) -> sqlx::Result<CommentRow> {
234
    let row = sqlx::query_as(
235
        "INSERT INTO proposal_comments (proposal_id, author_id, author, body, path, anchor_change, anchor_index, created_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING *",
236
    )
237
    .bind(proposal_id)
238
    .bind(author_id)
239
    .bind(author)
240
    .bind(body)
241
    .bind(path)
242
    .bind(anchor.map(|a| a.0).unwrap_or(""))
243
    .bind(anchor.map(|a| a.1).unwrap_or(0))
244
    .bind(now_ms())
245
    .fetch_one(pool)
246
    .await?;
247
    touch(pool, proposal_id).await?;
248
    Ok(row)
249
}
250
251
pub async fn set_comment_resolved(pool: &Pool, id: i64, resolved: bool) -> sqlx::Result<()> {
252
    sqlx::query("UPDATE proposal_comments SET resolved = ? WHERE id = ?").bind(resolved).bind(id).execute(pool).await?;
253
    Ok(())
254
}
255
256
pub async fn reviews(pool: &Pool, proposal_id: i64) -> sqlx::Result<Vec<ReviewRow>> {
257
    sqlx::query_as("SELECT * FROM proposal_reviews WHERE proposal_id = ? ORDER BY created_ms, id").bind(proposal_id).fetch_all(pool).await
258
}
259
260
pub async fn add_review(pool: &Pool, proposal_id: i64, author_id: i64, author: &str, verdict: &str, body: &str) -> sqlx::Result<ReviewRow> {
261
    let row = sqlx::query_as(
262
        "INSERT INTO proposal_reviews (proposal_id, author_id, author, verdict, body, created_ms) VALUES (?, ?, ?, ?, ?, ?) RETURNING *",
263
    )
264
    .bind(proposal_id)
265
    .bind(author_id)
266
    .bind(author)
267
    .bind(verdict)
268
    .bind(body)
269
    .bind(now_ms())
270
    .fetch_one(pool)
271
    .await?;
272
    touch(pool, proposal_id).await?;
273
    Ok(row)
274
}
275
276
pub async fn events(pool: &Pool, proposal_id: i64) -> sqlx::Result<Vec<EventRow>> {
277
    sqlx::query_as("SELECT id, at_ms, actor, event, detail FROM proposal_events WHERE proposal_id = ? ORDER BY at_ms, id")
278
        .bind(proposal_id)
279
        .fetch_all(pool)
280
        .await
281
}
282
283
pub async fn add_event(pool: &Pool, proposal_id: i64, actor: &str, event: &str, detail: &str) -> sqlx::Result<()> {
284
    sqlx::query("INSERT INTO proposal_events (proposal_id, at_ms, actor, event, detail) VALUES (?, ?, ?, ?, ?)")
285
        .bind(proposal_id)
286
        .bind(now_ms())
287
        .bind(actor)
288
        .bind(event)
289
        .bind(detail)
290
        .execute(pool)
291
        .await?;
292
    Ok(())
293
}
294
295
/// Landing requirements of a repository.
296
#[derive(Clone, Copy, Debug, Default, FromRow)]
297
pub struct Requirements {
298
    pub required_approvals: i64,
299
    pub require_owners: bool,
300
    pub allow_conflicts: bool,
301
}
302
303
pub async fn requirements(pool: &Pool, repo_id: i64) -> sqlx::Result<Requirements> {
304
    sqlx::query_as("SELECT required_approvals, require_owners, allow_conflicts FROM repositories WHERE id = ?")
305
        .bind(repo_id)
306
        .fetch_one(pool)
307
        .await
308
}
309
310
pub async fn set_requirements(pool: &Pool, repo_id: i64, r: Requirements) -> sqlx::Result<()> {
311
    sqlx::query("UPDATE repositories SET required_approvals = ?, require_owners = ?, allow_conflicts = ? WHERE id = ?")
312
        .bind(r.required_approvals)
313
        .bind(r.require_owners)
314
        .bind(r.allow_conflicts)
315
        .bind(repo_id)
316
        .execute(pool)
317
        .await?;
318
    Ok(())
319
}
320
321
// ------------------------------------------------------- review requests
322
323
/// Ask an account to review a proposal; false when it was already asked.
324
pub async fn request_review(pool: &Pool, proposal_id: i64, account_id: i64, by: &str) -> sqlx::Result<bool> {
325
    let r = sqlx::query(
326
        "INSERT OR IGNORE INTO proposal_review_requests (proposal_id, account_id, requested_by, requested_ms) VALUES (?, ?, ?, ?)",
327
    )
328
    .bind(proposal_id)
329
    .bind(account_id)
330
    .bind(by)
331
    .bind(now_ms())
332
    .execute(pool)
333
    .await?;
334
    Ok(r.rows_affected() == 1)
335
}
336
337
/// Withdraw a request, or mark it answered; false when there was none.
338
pub async fn unrequest_review(pool: &Pool, proposal_id: i64, account_id: i64) -> sqlx::Result<bool> {
339
    let r = sqlx::query("DELETE FROM proposal_review_requests WHERE proposal_id = ? AND account_id = ?")
340
        .bind(proposal_id)
341
        .bind(account_id)
342
        .execute(pool)
343
        .await?;
344
    Ok(r.rows_affected() == 1)
345
}
346
347
/// The usernames asked to review a proposal and not yet reviewing, in the
348
/// order they were asked.
349
pub async fn review_requests(pool: &Pool, proposal_id: i64) -> sqlx::Result<Vec<String>> {
350
    sqlx::query_scalar(
351
        "SELECT a.username FROM proposal_review_requests r JOIN accounts a ON a.id = r.account_id \
352
         WHERE r.proposal_id = ? ORDER BY r.requested_ms, a.username",
353
    )
354
    .bind(proposal_id)
355
    .fetch_all(pool)
356
    .await
357
}