OXYGENHUB
# 93501da2a162 oxygenhub / crates / hub / src / db / proposals.rs
12.0 KiB · Rust · last changed AI assistants review proposals and draft their descriptions 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
    /// The AI assistant that answered for the author (migration 0036),
78
    /// empty for the author's own review.
79
    #[sqlx(default)]
80
    pub via: String,
81
}
82
83
#[derive(Clone, Debug, FromRow)]
84
pub struct EventRow {
85
    pub id: i64,
86
    pub at_ms: i64,
87
    pub actor: String,
88
    pub event: String,
89
    pub detail: String,
90
}
91
92
/// Take the next number of a repository's shared number space.
93
pub async fn next_number(pool: &Pool, repo_id: i64) -> sqlx::Result<i64> {
94
    let mut tx = super::begin_write(pool).await?;
95
    sqlx::query("INSERT OR IGNORE INTO numbers (repo_id, next) VALUES (?, 1)").bind(repo_id).execute(&mut *tx).await?;
96
    let n: i64 = sqlx::query_scalar("SELECT next FROM numbers WHERE repo_id = ?").bind(repo_id).fetch_one(&mut *tx).await?;
97
    sqlx::query("UPDATE numbers SET next = next + 1 WHERE repo_id = ?").bind(repo_id).execute(&mut *tx).await?;
98
    tx.commit().await?;
99
    Ok(n)
100
}
101
102
pub struct NewProposal<'a> {
103
    pub repo_id: i64,
104
    pub title: &'a str,
105
    pub body: &'a str,
106
    pub author_id: Option<i64>,
107
    pub author: &'a str,
108
    pub draft: bool,
109
    pub target: &'a str,
110
    pub source_kind: &'a str,
111
    pub source_repo_id: Option<i64>,
112
    pub source_bookmark: &'a str,
113
    pub source_changes: &'a str,
114
}
115
116
pub async fn create(pool: &Pool, p: NewProposal<'_>) -> sqlx::Result<ProposalRow> {
117
    let number = next_number(pool, p.repo_id).await?;
118
    let now = now_ms();
119
    sqlx::query_as(
120
        "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) \
121
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *",
122
    )
123
    .bind(p.repo_id)
124
    .bind(number)
125
    .bind(p.title)
126
    .bind(p.body)
127
    .bind(p.author_id)
128
    .bind(p.author)
129
    .bind(if p.draft { "draft" } else { "open" })
130
    .bind(p.target)
131
    .bind(p.source_kind)
132
    .bind(p.source_repo_id)
133
    .bind(p.source_bookmark)
134
    .bind(p.source_changes)
135
    .bind(now)
136
    .bind(now)
137
    .fetch_one(pool)
138
    .await
139
}
140
141
pub async fn get(pool: &Pool, repo_id: i64, number: i64) -> sqlx::Result<Option<ProposalRow>> {
142
    sqlx::query_as("SELECT * FROM proposals WHERE repo_id = ? AND number = ?").bind(repo_id).bind(number).fetch_optional(pool).await
143
}
144
145
pub async fn list(pool: &Pool, repo_id: i64, states: &[&str]) -> sqlx::Result<Vec<ProposalRow>> {
146
    let all: Vec<ProposalRow> =
147
        sqlx::query_as("SELECT * FROM proposals WHERE repo_id = ? ORDER BY number DESC").bind(repo_id).fetch_all(pool).await?;
148
    Ok(all.into_iter().filter(|p| states.is_empty() || states.contains(&p.state.as_str())).collect())
149
}
150
151
/// Open proposals of every repository, for the front page.
152
pub async fn open_for_author(pool: &Pool, author_id: i64) -> sqlx::Result<Vec<ProposalRow>> {
153
    sqlx::query_as("SELECT * FROM proposals WHERE author_id = ? AND state IN ('open', 'draft') ORDER BY updated_ms DESC")
154
        .bind(author_id)
155
        .fetch_all(pool)
156
        .await
157
}
158
159
pub async fn set_projection(
160
    pool: &Pool,
161
    id: i64,
162
    state: &str,
163
    heads: &str,
164
    target_state: &str,
165
    changes: &str,
166
    conflicted: bool,
167
) -> sqlx::Result<()> {
168
    sqlx::query("UPDATE proposals SET projected_state = ?, projected_heads = ?, projected_target = ?, projected_changes = ?, conflicted = ? WHERE id = ?")
169
        .bind(state)
170
        .bind(heads)
171
        .bind(target_state)
172
        .bind(changes)
173
        .bind(conflicted)
174
        .bind(id)
175
        .execute(pool)
176
        .await?;
177
    Ok(())
178
}
179
180
pub async fn set_state(pool: &Pool, id: i64, state: &str, landed_state: &str) -> sqlx::Result<()> {
181
    sqlx::query("UPDATE proposals SET state = ?, landed_state = ?, updated_ms = ? WHERE id = ?")
182
        .bind(state)
183
        .bind(landed_state)
184
        .bind(now_ms())
185
        .bind(id)
186
        .execute(pool)
187
        .await?;
188
    Ok(())
189
}
190
191
/// Mark a proposal landed, with who landed it and how.
192
pub async fn set_landed(pool: &Pool, id: i64, landed_state: &str, by: &str, via: &str) -> sqlx::Result<()> {
193
    let now = now_ms();
194
    sqlx::query(
195
        "UPDATE proposals SET state = 'landed', landed_state = ?, landed_by = ?, landed_via = ?, landed_ms = ?, updated_ms = ? WHERE id = ?",
196
    )
197
    .bind(landed_state)
198
    .bind(by)
199
    .bind(via)
200
    .bind(now)
201
    .bind(now)
202
    .bind(id)
203
    .execute(pool)
204
    .await?;
205
    Ok(())
206
}
207
208
pub async fn edit(pool: &Pool, id: i64, title: &str, body: &str, target: &str) -> sqlx::Result<()> {
209
    sqlx::query("UPDATE proposals SET title = ?, body = ?, target = ?, updated_ms = ? WHERE id = ?")
210
        .bind(title)
211
        .bind(body)
212
        .bind(target)
213
        .bind(now_ms())
214
        .bind(id)
215
        .execute(pool)
216
        .await?;
217
    Ok(())
218
}
219
220
pub async fn touch(pool: &Pool, id: i64) -> sqlx::Result<()> {
221
    sqlx::query("UPDATE proposals SET updated_ms = ? WHERE id = ?").bind(now_ms()).bind(id).execute(pool).await?;
222
    Ok(())
223
}
224
225
pub async fn comments(pool: &Pool, proposal_id: i64) -> sqlx::Result<Vec<CommentRow>> {
226
    sqlx::query_as("SELECT * FROM proposal_comments WHERE proposal_id = ? ORDER BY created_ms, id").bind(proposal_id).fetch_all(pool).await
227
}
228
229
pub async fn add_comment(
230
    pool: &Pool,
231
    proposal_id: i64,
232
    author_id: Option<i64>,
233
    author: &str,
234
    body: &str,
235
    path: &str,
236
    anchor: Option<(&str, i64)>,
237
) -> sqlx::Result<CommentRow> {
238
    let row = sqlx::query_as(
239
        "INSERT INTO proposal_comments (proposal_id, author_id, author, body, path, anchor_change, anchor_index, created_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING *",
240
    )
241
    .bind(proposal_id)
242
    .bind(author_id)
243
    .bind(author)
244
    .bind(body)
245
    .bind(path)
246
    .bind(anchor.map(|a| a.0).unwrap_or(""))
247
    .bind(anchor.map(|a| a.1).unwrap_or(0))
248
    .bind(now_ms())
249
    .fetch_one(pool)
250
    .await?;
251
    touch(pool, proposal_id).await?;
252
    Ok(row)
253
}
254
255
pub async fn set_comment_resolved(pool: &Pool, id: i64, resolved: bool) -> sqlx::Result<()> {
256
    sqlx::query("UPDATE proposal_comments SET resolved = ? WHERE id = ?").bind(resolved).bind(id).execute(pool).await?;
257
    Ok(())
258
}
259
260
pub async fn reviews(pool: &Pool, proposal_id: i64) -> sqlx::Result<Vec<ReviewRow>> {
261
    sqlx::query_as("SELECT * FROM proposal_reviews WHERE proposal_id = ? ORDER BY created_ms, id").bind(proposal_id).fetch_all(pool).await
262
}
263
264
pub async fn add_review(pool: &Pool, proposal_id: i64, author_id: i64, author: &str, verdict: &str, body: &str) -> sqlx::Result<ReviewRow> {
265
    add_review_via(pool, proposal_id, author_id, author, verdict, body, "").await
266
}
267
268
/// A review answered by an AI assistant (`via`) for `author`, who asked.
269
pub async fn add_review_via(
270
    pool: &Pool,
271
    proposal_id: i64,
272
    author_id: i64,
273
    author: &str,
274
    verdict: &str,
275
    body: &str,
276
    via: &str,
277
) -> sqlx::Result<ReviewRow> {
278
    let row = sqlx::query_as(
279
        "INSERT INTO proposal_reviews (proposal_id, author_id, author, verdict, body, created_ms, via) VALUES (?, ?, ?, ?, ?, ?, ?) RETURNING *",
280
    )
281
    .bind(proposal_id)
282
    .bind(author_id)
283
    .bind(author)
284
    .bind(verdict)
285
    .bind(body)
286
    .bind(now_ms())
287
    .bind(via)
288
    .fetch_one(pool)
289
    .await?;
290
    touch(pool, proposal_id).await?;
291
    Ok(row)
292
}
293
294
pub async fn events(pool: &Pool, proposal_id: i64) -> sqlx::Result<Vec<EventRow>> {
295
    sqlx::query_as("SELECT id, at_ms, actor, event, detail FROM proposal_events WHERE proposal_id = ? ORDER BY at_ms, id")
296
        .bind(proposal_id)
297
        .fetch_all(pool)
298
        .await
299
}
300
301
pub async fn add_event(pool: &Pool, proposal_id: i64, actor: &str, event: &str, detail: &str) -> sqlx::Result<()> {
302
    sqlx::query("INSERT INTO proposal_events (proposal_id, at_ms, actor, event, detail) VALUES (?, ?, ?, ?, ?)")
303
        .bind(proposal_id)
304
        .bind(now_ms())
305
        .bind(actor)
306
        .bind(event)
307
        .bind(detail)
308
        .execute(pool)
309
        .await?;
310
    Ok(())
311
}
312
313
/// Landing requirements of a repository.
314
#[derive(Clone, Copy, Debug, Default, FromRow)]
315
pub struct Requirements {
316
    pub required_approvals: i64,
317
    pub require_owners: bool,
318
    pub allow_conflicts: bool,
319
}
320
321
pub async fn requirements(pool: &Pool, repo_id: i64) -> sqlx::Result<Requirements> {
322
    sqlx::query_as("SELECT required_approvals, require_owners, allow_conflicts FROM repositories WHERE id = ?")
323
        .bind(repo_id)
324
        .fetch_one(pool)
325
        .await
326
}
327
328
pub async fn set_requirements(pool: &Pool, repo_id: i64, r: Requirements) -> sqlx::Result<()> {
329
    sqlx::query("UPDATE repositories SET required_approvals = ?, require_owners = ?, allow_conflicts = ? WHERE id = ?")
330
        .bind(r.required_approvals)
331
        .bind(r.require_owners)
332
        .bind(r.allow_conflicts)
333
        .bind(repo_id)
334
        .execute(pool)
335
        .await?;
336
    Ok(())
337
}
338
339
// ------------------------------------------------------- review requests
340
341
/// Ask an account to review a proposal; false when it was already asked.
342
pub async fn request_review(pool: &Pool, proposal_id: i64, account_id: i64, by: &str) -> sqlx::Result<bool> {
343
    let r = sqlx::query(
344
        "INSERT OR IGNORE INTO proposal_review_requests (proposal_id, account_id, requested_by, requested_ms) VALUES (?, ?, ?, ?)",
345
    )
346
    .bind(proposal_id)
347
    .bind(account_id)
348
    .bind(by)
349
    .bind(now_ms())
350
    .execute(pool)
351
    .await?;
352
    Ok(r.rows_affected() == 1)
353
}
354
355
/// Withdraw a request, or mark it answered; false when there was none.
356
pub async fn unrequest_review(pool: &Pool, proposal_id: i64, account_id: i64) -> sqlx::Result<bool> {
357
    let r = sqlx::query("DELETE FROM proposal_review_requests WHERE proposal_id = ? AND account_id = ?")
358
        .bind(proposal_id)
359
        .bind(account_id)
360
        .execute(pool)
361
        .await?;
362
    Ok(r.rows_affected() == 1)
363
}
364
365
/// The usernames asked to review a proposal and not yet reviewing, in the
366
/// order they were asked.
367
pub async fn review_requests(pool: &Pool, proposal_id: i64) -> sqlx::Result<Vec<String>> {
368
    sqlx::query_scalar(
369
        "SELECT a.username FROM proposal_review_requests r JOIN accounts a ON a.id = r.account_id \
370
         WHERE r.proposal_id = ? ORDER BY r.requested_ms, a.username",
371
    )
372
    .bind(proposal_id)
373
    .fetch_all(pool)
374
    .await
375
}