OXYGENHUB
# c43e4f631d99 oxygenhub / crates / hub / src / db / proposals.rs
13.9 KiB · Rust · last changed Land when checks pass 17 days 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
    /// Who set it to land when its checks pass (#261); empty when off.
34
    #[sqlx(default)]
35
    pub auto_land_by: String,
36
    #[sqlx(default)]
37
    pub auto_land_ms: Option<i64>,
38
}
39
40
impl ProposalRow {
41
    pub fn projected_heads(&self) -> Vec<String> {
42
        self.projected_heads.split(',').filter(|s| !s.is_empty()).map(String::from).collect()
43
    }
44
45
    pub fn projected_changes(&self) -> Vec<String> {
46
        self.projected_changes.split(',').filter(|s| !s.is_empty()).map(String::from).collect()
47
    }
48
49
    pub fn source_changes(&self) -> Vec<String> {
50
        self.source_changes.split(',').filter(|s| !s.is_empty()).map(String::from).collect()
51
    }
52
53
    pub fn is_open(&self) -> bool {
54
        self.state == "open" || self.state == "draft"
55
    }
56
}
57
58
#[derive(Clone, Debug, FromRow)]
59
pub struct CommentRow {
60
    pub id: i64,
61
    pub proposal_id: i64,
62
    pub author_id: Option<i64>,
63
    pub author: String,
64
    pub body: String,
65
    pub path: String,
66
    pub anchor_change: String,
67
    pub anchor_index: i64,
68
    pub resolved: bool,
69
    pub created_ms: i64,
70
    /// The AI assistant that wrote it for the author (migration 0066),
71
    /// empty for the author's own comment.
72
    #[sqlx(default)]
73
    pub via: String,
74
}
75
76
#[derive(Clone, Debug, FromRow)]
77
pub struct ReviewRow {
78
    pub id: i64,
79
    pub proposal_id: i64,
80
    /// `None` once the author's account was deleted (its name stays).
81
    pub author_id: Option<i64>,
82
    pub author: String,
83
    pub verdict: String,
84
    pub body: String,
85
    pub created_ms: i64,
86
    /// The AI assistant that answered for the author (migration 0036),
87
    /// empty for the author's own review.
88
    #[sqlx(default)]
89
    pub via: String,
90
}
91
92
#[derive(Clone, Debug, FromRow)]
93
pub struct EventRow {
94
    pub id: i64,
95
    pub at_ms: i64,
96
    pub actor: String,
97
    pub event: String,
98
    pub detail: String,
99
}
100
101
/// Take the next number of a repository's shared number space.
102
pub async fn next_number(pool: &Pool, repo_id: i64) -> sqlx::Result<i64> {
103
    let mut tx = super::begin_write(pool).await?;
104
    sqlx::query("INSERT INTO numbers (repo_id, next) VALUES ($1, 1) ON CONFLICT DO NOTHING").bind(repo_id).execute(&mut *tx).await?;
105
    let n: i64 = sqlx::query_scalar("SELECT next FROM numbers WHERE repo_id = $1").bind(repo_id).fetch_one(&mut *tx).await?;
106
    sqlx::query("UPDATE numbers SET next = next + 1 WHERE repo_id = $1").bind(repo_id).execute(&mut *tx).await?;
107
    tx.commit().await?;
108
    Ok(n)
109
}
110
111
pub struct NewProposal<'a> {
112
    pub repo_id: i64,
113
    pub title: &'a str,
114
    pub body: &'a str,
115
    pub author_id: Option<i64>,
116
    pub author: &'a str,
117
    pub draft: bool,
118
    pub target: &'a str,
119
    pub source_kind: &'a str,
120
    pub source_repo_id: Option<i64>,
121
    pub source_bookmark: &'a str,
122
    pub source_changes: &'a str,
123
}
124
125
pub async fn create(pool: &Pool, p: NewProposal<'_>) -> sqlx::Result<ProposalRow> {
126
    let number = next_number(pool, p.repo_id).await?;
127
    let now = now_ms();
128
    sqlx::query_as(
129
        "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) \
130
         VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14) RETURNING *",
131
    )
132
    .bind(p.repo_id)
133
    .bind(number)
134
    .bind(p.title)
135
    .bind(p.body)
136
    .bind(p.author_id)
137
    .bind(p.author)
138
    .bind(if p.draft { "draft" } else { "open" })
139
    .bind(p.target)
140
    .bind(p.source_kind)
141
    .bind(p.source_repo_id)
142
    .bind(p.source_bookmark)
143
    .bind(p.source_changes)
144
    .bind(now)
145
    .bind(now)
146
    .fetch_one(pool)
147
    .await
148
}
149
150
pub async fn get(pool: &Pool, repo_id: i64, number: i64) -> sqlx::Result<Option<ProposalRow>> {
151
    sqlx::query_as("SELECT * FROM proposals WHERE repo_id = $1 AND number = $2").bind(repo_id).bind(number).fetch_optional(pool).await
152
}
153
154
pub async fn list(pool: &Pool, repo_id: i64, states: &[&str]) -> sqlx::Result<Vec<ProposalRow>> {
155
    let all: Vec<ProposalRow> =
156
        sqlx::query_as("SELECT * FROM proposals WHERE repo_id = $1 ORDER BY number DESC").bind(repo_id).fetch_all(pool).await?;
157
    Ok(all.into_iter().filter(|p| states.is_empty() || states.contains(&p.state.as_str())).collect())
158
}
159
160
/// Open proposals of every repository, for the front page.
161
pub async fn open_for_author(pool: &Pool, author_id: i64) -> sqlx::Result<Vec<ProposalRow>> {
162
    sqlx::query_as("SELECT * FROM proposals WHERE author_id = $1 AND state IN ('open', 'draft') ORDER BY updated_ms DESC")
163
        .bind(author_id)
164
        .fetch_all(pool)
165
        .await
166
}
167
168
pub async fn set_projection(
169
    pool: &Pool,
170
    id: i64,
171
    state: &str,
172
    heads: &str,
173
    target_state: &str,
174
    changes: &str,
175
    conflicted: bool,
176
) -> sqlx::Result<()> {
177
    sqlx::query("UPDATE proposals SET projected_state = $1, projected_heads = $2, projected_target = $3, projected_changes = $4, conflicted = $5 WHERE id = $6")
178
        .bind(state)
179
        .bind(heads)
180
        .bind(target_state)
181
        .bind(changes)
182
        .bind(conflicted)
183
        .bind(id)
184
        .execute(pool)
185
        .await?;
186
    Ok(())
187
}
188
189
pub async fn set_state(pool: &Pool, id: i64, state: &str, landed_state: &str) -> sqlx::Result<()> {
190
    sqlx::query("UPDATE proposals SET state = $1, landed_state = $2, updated_ms = $3 WHERE id = $4")
191
        .bind(state)
192
        .bind(landed_state)
193
        .bind(now_ms())
194
        .bind(id)
195
        .execute(pool)
196
        .await?;
197
    Ok(())
198
}
199
200
/// Mark a proposal landed, with who landed it and how.
201
pub async fn set_landed(pool: &Pool, id: i64, landed_state: &str, by: &str, via: &str) -> sqlx::Result<()> {
202
    let now = now_ms();
203
    sqlx::query(
204
        "UPDATE proposals SET state = 'landed', landed_state = $1, landed_by = $2, landed_via = $3, landed_ms = $4, updated_ms = $5 WHERE id = $6",
205
    )
206
    .bind(landed_state)
207
    .bind(by)
208
    .bind(via)
209
    .bind(now)
210
    .bind(now)
211
    .bind(id)
212
    .execute(pool)
213
    .await?;
214
    Ok(())
215
}
216
217
pub async fn edit(pool: &Pool, id: i64, title: &str, body: &str, target: &str) -> sqlx::Result<()> {
218
    sqlx::query("UPDATE proposals SET title = $1, body = $2, target = $3, updated_ms = $4 WHERE id = $5")
219
        .bind(title)
220
        .bind(body)
221
        .bind(target)
222
        .bind(now_ms())
223
        .bind(id)
224
        .execute(pool)
225
        .await?;
226
    Ok(())
227
}
228
229
pub async fn touch(pool: &Pool, id: i64) -> sqlx::Result<()> {
230
    sqlx::query("UPDATE proposals SET updated_ms = $1 WHERE id = $2").bind(now_ms()).bind(id).execute(pool).await?;
231
    Ok(())
232
}
233
234
pub async fn comments(pool: &Pool, proposal_id: i64) -> sqlx::Result<Vec<CommentRow>> {
235
    sqlx::query_as("SELECT * FROM proposal_comments WHERE proposal_id = $1 ORDER BY created_ms, id").bind(proposal_id).fetch_all(pool).await
236
}
237
238
pub async fn add_comment(
239
    pool: &Pool,
240
    proposal_id: i64,
241
    author_id: Option<i64>,
242
    author: &str,
243
    body: &str,
244
    path: &str,
245
    anchor: Option<(&str, i64)>,
246
) -> sqlx::Result<CommentRow> {
247
    let row = sqlx::query_as(
248
        "INSERT INTO proposal_comments (proposal_id, author_id, author, body, path, anchor_change, anchor_index, created_ms) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING *",
249
    )
250
    .bind(proposal_id)
251
    .bind(author_id)
252
    .bind(author)
253
    .bind(body)
254
    .bind(path)
255
    .bind(anchor.map(|a| a.0).unwrap_or(""))
256
    .bind(anchor.map(|a| a.1).unwrap_or(0))
257
    .bind(now_ms())
258
    .fetch_one(pool)
259
    .await?;
260
    touch(pool, proposal_id).await?;
261
    Ok(row)
262
}
263
264
/// A conversation comment an AI assistant (`via`) wrote for `author`,
265
/// who asked it.
266
pub async fn add_comment_via(
267
    pool: &Pool,
268
    proposal_id: i64,
269
    author_id: i64,
270
    author: &str,
271
    body: &str,
272
    via: &str,
273
) -> sqlx::Result<CommentRow> {
274
    let row = sqlx::query_as(
275
        "INSERT INTO proposal_comments (proposal_id, author_id, author, body, path, anchor_change, anchor_index, created_ms, via) VALUES ($1, $2, $3, $4, '', '', 0, $5, $6) RETURNING *",
276
    )
277
    .bind(proposal_id)
278
    .bind(author_id)
279
    .bind(author)
280
    .bind(body)
281
    .bind(now_ms())
282
    .bind(via)
283
    .fetch_one(pool)
284
    .await?;
285
    touch(pool, proposal_id).await?;
286
    Ok(row)
287
}
288
289
pub async fn set_comment_resolved(pool: &Pool, id: i64, resolved: bool) -> sqlx::Result<()> {
290
    sqlx::query("UPDATE proposal_comments SET resolved = $1 WHERE id = $2").bind(resolved).bind(id).execute(pool).await?;
291
    Ok(())
292
}
293
294
pub async fn reviews(pool: &Pool, proposal_id: i64) -> sqlx::Result<Vec<ReviewRow>> {
295
    sqlx::query_as("SELECT * FROM proposal_reviews WHERE proposal_id = $1 ORDER BY created_ms, id").bind(proposal_id).fetch_all(pool).await
296
}
297
298
pub async fn add_review(pool: &Pool, proposal_id: i64, author_id: i64, author: &str, verdict: &str, body: &str) -> sqlx::Result<ReviewRow> {
299
    add_review_via(pool, proposal_id, author_id, author, verdict, body, "").await
300
}
301
302
/// A review answered by an AI assistant (`via`) for `author`, who asked.
303
pub async fn add_review_via(
304
    pool: &Pool,
305
    proposal_id: i64,
306
    author_id: i64,
307
    author: &str,
308
    verdict: &str,
309
    body: &str,
310
    via: &str,
311
) -> sqlx::Result<ReviewRow> {
312
    let row = sqlx::query_as(
313
        "INSERT INTO proposal_reviews (proposal_id, author_id, author, verdict, body, created_ms, via) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING *",
314
    )
315
    .bind(proposal_id)
316
    .bind(author_id)
317
    .bind(author)
318
    .bind(verdict)
319
    .bind(body)
320
    .bind(now_ms())
321
    .bind(via)
322
    .fetch_one(pool)
323
    .await?;
324
    touch(pool, proposal_id).await?;
325
    Ok(row)
326
}
327
328
pub async fn events(pool: &Pool, proposal_id: i64) -> sqlx::Result<Vec<EventRow>> {
329
    sqlx::query_as("SELECT id, at_ms, actor, event, detail FROM proposal_events WHERE proposal_id = $1 ORDER BY at_ms, id")
330
        .bind(proposal_id)
331
        .fetch_all(pool)
332
        .await
333
}
334
335
pub async fn add_event(pool: &Pool, proposal_id: i64, actor: &str, event: &str, detail: &str) -> sqlx::Result<()> {
336
    sqlx::query("INSERT INTO proposal_events (proposal_id, at_ms, actor, event, detail) VALUES ($1, $2, $3, $4, $5)")
337
        .bind(proposal_id)
338
        .bind(now_ms())
339
        .bind(actor)
340
        .bind(event)
341
        .bind(detail)
342
        .execute(pool)
343
        .await?;
344
    Ok(())
345
}
346
347
/// Landing requirements of a repository.
348
#[derive(Clone, Copy, Debug, Default, FromRow)]
349
pub struct Requirements {
350
    pub required_approvals: i64,
351
    pub require_owners: bool,
352
    pub allow_conflicts: bool,
353
}
354
355
pub async fn requirements(pool: &Pool, repo_id: i64) -> sqlx::Result<Requirements> {
356
    sqlx::query_as("SELECT required_approvals, require_owners, allow_conflicts FROM repositories WHERE id = $1")
357
        .bind(repo_id)
358
        .fetch_one(pool)
359
        .await
360
}
361
362
pub async fn set_requirements(pool: &Pool, repo_id: i64, r: Requirements) -> sqlx::Result<()> {
363
    sqlx::query("UPDATE repositories SET required_approvals = $1, require_owners = $2, allow_conflicts = $3 WHERE id = $4")
364
        .bind(r.required_approvals)
365
        .bind(r.require_owners)
366
        .bind(r.allow_conflicts)
367
        .bind(repo_id)
368
        .execute(pool)
369
        .await?;
370
    Ok(())
371
}
372
373
// ------------------------------------------------------- review requests
374
375
/// Ask an account to review a proposal; false when it was already asked.
376
pub async fn request_review(pool: &Pool, proposal_id: i64, account_id: i64, by: &str) -> sqlx::Result<bool> {
377
    let r = sqlx::query(
378
        "INSERT INTO proposal_review_requests (proposal_id, account_id, requested_by, requested_ms) VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING",
379
    )
380
    .bind(proposal_id)
381
    .bind(account_id)
382
    .bind(by)
383
    .bind(now_ms())
384
    .execute(pool)
385
    .await?;
386
    Ok(r.rows_affected() == 1)
387
}
388
389
/// Withdraw a request, or mark it answered; false when there was none.
390
pub async fn unrequest_review(pool: &Pool, proposal_id: i64, account_id: i64) -> sqlx::Result<bool> {
391
    let r = sqlx::query("DELETE FROM proposal_review_requests WHERE proposal_id = $1 AND account_id = $2")
392
        .bind(proposal_id)
393
        .bind(account_id)
394
        .execute(pool)
395
        .await?;
396
    Ok(r.rows_affected() == 1)
397
}
398
399
/// The usernames asked to review a proposal and not yet reviewing, in the
400
/// order they were asked.
401
pub async fn review_requests(pool: &Pool, proposal_id: i64) -> sqlx::Result<Vec<String>> {
402
    sqlx::query_scalar(
403
        "SELECT a.username FROM proposal_review_requests r JOIN accounts a ON a.id = r.account_id \
404
         WHERE r.proposal_id = $1 ORDER BY r.requested_ms, a.username",
405
    )
406
    .bind(proposal_id)
407
    .fetch_all(pool)
408
    .await
409
}
410
411
/// Set, or with `by` empty clear, landing when checks pass (#261).
412
pub async fn set_auto_land(pool: &Pool, id: i64, by: &str) -> sqlx::Result<()> {
413
    sqlx::query("UPDATE proposals SET auto_land_by = $1, auto_land_ms = $2 WHERE id = $3")
414
        .bind(by)
415
        .bind((!by.is_empty()).then(now_ms))
416
        .bind(id)
417
        .execute(pool)
418
        .await?;
419
    Ok(())
420
}
421
422
/// A repository's open proposals set to land when their checks pass, on
423
/// projected state `state`.
424
pub async fn auto_landing(pool: &Pool, repo_id: i64, state: &str) -> sqlx::Result<Vec<ProposalRow>> {
425
    sqlx::query_as(
426
        "SELECT * FROM proposals WHERE repo_id = $1 AND state = 'open' AND auto_land_by != '' AND projected_state = $2 ORDER BY number",
427
    )
428
    .bind(repo_id)
429
    .bind(state)
430
    .fetch_all(pool)
431
    .await
432
}