OXYGENHUB
# 26d0d091deb7 oxygenhub / crates / hub / src / db / repos.rs
12.1 KiB · Rust · last changed Diffusion: turning it on 24 days ago source blame history raw
1
//! The `repositories` and `pushes` tables.
2
3
use super::{now_ms, Pool};
4
use hub_api::Visibility;
5
use sqlx::FromRow;
6
7
#[derive(Clone, Debug, Default, FromRow)]
8
pub struct RepoRow {
9
    pub id: i64,
10
    pub owner: String,
11
    pub name: String,
12
    pub description: String,
13
    pub default_bookmark: String,
14
    pub visibility: String,
15
    pub created_ms: i64,
16
    pub updated_ms: i64,
17
    #[sqlx(default)]
18
    pub git_mirror: bool,
19
    #[sqlx(default)]
20
    pub git_mirror_state: String,
21
    /// The repository this one was forked from (migration 0009).
22
    #[sqlx(default)]
23
    pub forked_from: Option<i64>,
24
    /// Space-separated topics (migration 0010).
25
    #[sqlx(default)]
26
    pub topics: String,
27
    /// OxygenFlow: `on`, `off`, or empty to follow hub.toml (migration 0018).
28
    #[sqlx(default)]
29
    pub flow: String,
30
    /// Diffusion: `off`, `green`, `any`, or empty to follow hub.toml
31
    /// (migration 0058, #148).
32
    #[sqlx(default)]
33
    pub diffusion: String,
34
    /// Read-only, with why (migration 0040, #108).
35
    #[sqlx(default)]
36
    pub archived: bool,
37
    #[sqlx(default)]
38
    pub archived_reason: String,
39
    /// Counts for the tabs; filled by `get` only.
40
    #[sqlx(default)]
41
    pub open_issues: i64,
42
    #[sqlx(default)]
43
    pub open_proposals: i64,
44
}
45
46
impl RepoRow {
47
    pub fn visibility(&self) -> Visibility {
48
        Visibility::parse(&self.visibility).unwrap_or(Visibility::Private)
49
    }
50
51
    pub fn topic_list(&self) -> Vec<&str> {
52
        self.topics.split_whitespace().collect()
53
    }
54
55
    pub fn slug(&self) -> String {
56
        format!("{}/{}", self.owner, self.name)
57
    }
58
}
59
60
#[derive(Clone, Debug, FromRow)]
61
pub struct PushRow {
62
    pub id: i64,
63
    pub at_ms: i64,
64
    pub reference: String,
65
    pub ok: bool,
66
    pub reason: String,
67
    pub old_state: String,
68
    pub new_state: String,
69
    pub heads: i64,
70
    pub changes: i64,
71
    pub pusher: String,
72
}
73
74
/// One reference's outcome in a push, as the protocol backend reports it.
75
#[derive(Clone, Debug)]
76
pub struct PushOutcome {
77
    pub reference: String,
78
    pub ok: bool,
79
    pub reason: String,
80
    pub old_state: String,
81
    pub new_state: String,
82
    pub heads: i64,
83
    pub changes: i64,
84
}
85
86
pub async fn list(pool: &Pool) -> sqlx::Result<Vec<RepoRow>> {
87
    sqlx::query_as("SELECT * FROM repositories ORDER BY updated_ms DESC, owner, name").fetch_all(pool).await
88
}
89
90
pub async fn get_by_id(pool: &Pool, id: i64) -> sqlx::Result<Option<RepoRow>> {
91
    sqlx::query_as("SELECT * FROM repositories WHERE id = ?").bind(id).fetch_optional(pool).await
92
}
93
94
pub async fn list_by_owner(pool: &Pool, owner: &str) -> sqlx::Result<Vec<RepoRow>> {
95
    sqlx::query_as("SELECT * FROM repositories WHERE owner = ? ORDER BY updated_ms DESC, name").bind(owner).fetch_all(pool).await
96
}
97
98
/// One repository, with its open issue and proposal counts for the tabs.
99
pub async fn get(pool: &Pool, owner: &str, name: &str) -> sqlx::Result<Option<RepoRow>> {
100
    sqlx::query_as(
101
        "SELECT r.*, \
102
           (SELECT COUNT(*) FROM issues i WHERE i.repo_id = r.id AND i.state = 'open') AS open_issues, \
103
           (SELECT COUNT(*) FROM proposals p WHERE p.repo_id = r.id AND p.state IN ('open', 'draft')) AS open_proposals \
104
         FROM repositories r WHERE r.owner = ? AND r.name = ?",
105
    )
106
    .bind(owner)
107
    .bind(name)
108
    .fetch_optional(pool)
109
    .await
110
}
111
112
pub async fn create(pool: &Pool, owner: &str, name: &str, description: &str, visibility: Visibility) -> sqlx::Result<RepoRow> {
113
    let now = now_ms();
114
    sqlx::query_as(
115
        "INSERT INTO repositories (owner, name, description, visibility, created_ms, updated_ms) VALUES (?, ?, ?, ?, ?, ?) RETURNING *",
116
    )
117
    .bind(owner)
118
    .bind(name)
119
    .bind(description)
120
    .bind(visibility.as_str())
121
    .bind(now)
122
    .bind(now)
123
    .fetch_one(pool)
124
    .await
125
}
126
127
/// The repository an old name now points at, after a transfer.
128
pub async fn moved_to(pool: &Pool, owner: &str, name: &str) -> sqlx::Result<Option<RepoRow>> {
129
    let id: Option<i64> = sqlx::query_scalar("SELECT repo_id FROM repo_redirects WHERE old_owner = ? AND old_name = ?")
130
        .bind(owner)
131
        .bind(name)
132
        .fetch_optional(pool)
133
        .await?;
134
    match id {
135
        Some(id) => get_by_id(pool, id).await,
136
        None => Ok(None),
137
    }
138
}
139
140
/// Move a repository to another owner, keeping its name: the row, and a
141
/// redirect from the old name. A redirect that pointed at the new name
142
/// goes, so names never loop.
143
pub async fn transfer(pool: &Pool, id: i64, old_owner: &str, name: &str, new_owner: &str) -> sqlx::Result<()> {
144
    sqlx::query("UPDATE repositories SET owner = ?, updated_ms = ? WHERE id = ?")
145
        .bind(new_owner)
146
        .bind(now_ms())
147
        .bind(id)
148
        .execute(pool)
149
        .await?;
150
    sqlx::query("DELETE FROM repo_redirects WHERE old_owner = ? AND old_name = ?").bind(new_owner).bind(name).execute(pool).await?;
151
    sqlx::query("INSERT OR REPLACE INTO repo_redirects (old_owner, old_name, repo_id, moved_ms) VALUES (?, ?, ?, ?)")
152
        .bind(old_owner)
153
        .bind(name)
154
        .bind(id)
155
        .bind(now_ms())
156
        .execute(pool)
157
        .await?;
158
    Ok(())
159
}
160
161
/// Archive (read-only) or bring back a repository.
162
pub async fn set_archived(pool: &Pool, id: i64, archived: bool, reason: &str) -> sqlx::Result<()> {
163
    sqlx::query("UPDATE repositories SET archived = ?, archived_reason = ?, updated_ms = ? WHERE id = ?")
164
        .bind(archived)
165
        .bind(if archived { reason } else { "" })
166
        .bind(now_ms())
167
        .bind(id)
168
        .execute(pool)
169
        .await?;
170
    Ok(())
171
}
172
173
pub async fn delete(pool: &Pool, id: i64) -> sqlx::Result<()> {
174
    sqlx::query("DELETE FROM repositories WHERE id = ?").bind(id).execute(pool).await?;
175
    Ok(())
176
}
177
178
pub async fn set_description(pool: &Pool, id: i64, description: &str) -> sqlx::Result<()> {
179
    sqlx::query("UPDATE repositories SET description = ? WHERE id = ?").bind(description).bind(id).execute(pool).await?;
180
    Ok(())
181
}
182
183
pub async fn set_default_bookmark(pool: &Pool, id: i64, bookmark: &str) -> sqlx::Result<()> {
184
    sqlx::query("UPDATE repositories SET default_bookmark = ? WHERE id = ?").bind(bookmark).bind(id).execute(pool).await?;
185
    Ok(())
186
}
187
188
pub async fn set_visibility(pool: &Pool, id: i64, visibility: Visibility) -> sqlx::Result<()> {
189
    sqlx::query("UPDATE repositories SET visibility = ? WHERE id = ?").bind(visibility.as_str()).bind(id).execute(pool).await?;
190
    Ok(())
191
}
192
193
/// Record a push's per-reference results and bump the repository's activity.
194
pub async fn record_push(pool: &Pool, id: i64, pusher: Option<(i64, &str)>, results: &[PushOutcome]) -> sqlx::Result<()> {
195
    let now = now_ms();
196
    let mut tx = super::begin_write(pool).await?;
197
    for r in results {
198
        sqlx::query("INSERT INTO pushes (repo_id, at_ms, reference, ok, reason, old_state, new_state, heads, changes, account_id, pusher) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
199
            .bind(id)
200
            .bind(now)
201
            .bind(&r.reference)
202
            .bind(r.ok)
203
            .bind(&r.reason)
204
            .bind(&r.old_state)
205
            .bind(&r.new_state)
206
            .bind(r.heads)
207
            .bind(r.changes)
208
            .bind(pusher.map(|p| p.0).filter(|id| *id > 0))
209
            .bind(pusher.map(|p| p.1).unwrap_or(""))
210
            .execute(&mut *tx)
211
            .await?;
212
    }
213
    if results.iter().any(|r| r.ok) {
214
        sqlx::query("UPDATE repositories SET updated_ms = ? WHERE id = ?").bind(now).bind(id).execute(&mut *tx).await?;
215
    }
216
    tx.commit().await
217
}
218
219
pub async fn pushes(pool: &Pool, id: i64, limit: i64) -> sqlx::Result<Vec<PushRow>> {
220
    sqlx::query_as("SELECT id, at_ms, reference, ok, reason, old_state, new_state, heads, changes, pusher FROM pushes WHERE repo_id = ? ORDER BY at_ms DESC, id DESC LIMIT ?")
221
        .bind(id)
222
        .bind(limit)
223
        .fetch_all(pool)
224
        .await
225
}
226
227
/// Topics from user input: comma or space separated, lower-cased,
228
/// letters, digits and dashes, at most 35 characters each and 20 in all.
229
/// Returns the stored form or what is wrong.
230
pub fn parse_topics(input: &str) -> Result<String, String> {
231
    let mut out: Vec<String> = Vec::new();
232
    for t in input.split([',', ' ', '\n', '\t']).map(|t| t.trim().to_ascii_lowercase()).filter(|t| !t.is_empty()) {
233
        if t.len() > 35 || !t.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') || t.starts_with('-') {
234
            return Err(format!("\"{t}\" is not a topic: use letters, digits and dashes, up to 35 characters"));
235
        }
236
        if !out.contains(&t) {
237
            out.push(t);
238
        }
239
    }
240
    if out.len() > 20 {
241
        return Err("At most 20 topics.".into());
242
    }
243
    Ok(out.join(" "))
244
}
245
246
pub async fn set_topics(pool: &Pool, id: i64, topics: &str) -> sqlx::Result<()> {
247
    sqlx::query("UPDATE repositories SET topics = ? WHERE id = ?").bind(topics).bind(id).execute(pool).await?;
248
    Ok(())
249
}
250
251
/// Star or unstar; returns whether it is now starred.
252
pub async fn toggle_star(pool: &Pool, account_id: i64, repo_id: i64) -> sqlx::Result<bool> {
253
    let gone = sqlx::query("DELETE FROM stars WHERE account_id = ? AND repo_id = ?").bind(account_id).bind(repo_id).execute(pool).await?;
254
    if gone.rows_affected() > 0 {
255
        return Ok(false);
256
    }
257
    sqlx::query("INSERT INTO stars (account_id, repo_id, at_ms) VALUES (?, ?, ?)")
258
        .bind(account_id)
259
        .bind(repo_id)
260
        .bind(now_ms())
261
        .execute(pool)
262
        .await?;
263
    Ok(true)
264
}
265
266
pub async fn starred(pool: &Pool, account_id: i64, repo_id: i64) -> sqlx::Result<bool> {
267
    let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM stars WHERE account_id = ? AND repo_id = ?")
268
        .bind(account_id)
269
        .bind(repo_id)
270
        .fetch_one(pool)
271
        .await?;
272
    Ok(n > 0)
273
}
274
275
/// Stars and watchers of one repository.
276
pub async fn counts(pool: &Pool, repo_id: i64) -> sqlx::Result<(i64, i64)> {
277
    let stars: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM stars WHERE repo_id = ?").bind(repo_id).fetch_one(pool).await?;
278
    let watchers: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM watches WHERE repo_id = ?").bind(repo_id).fetch_one(pool).await?;
279
    Ok((stars, watchers))
280
}
281
282
/// Star counts of every starred repository.
283
pub async fn star_counts(pool: &Pool) -> sqlx::Result<std::collections::HashMap<i64, i64>> {
284
    let rows: Vec<(i64, i64)> = sqlx::query_as("SELECT repo_id, COUNT(*) FROM stars GROUP BY repo_id").fetch_all(pool).await?;
285
    Ok(rows.into_iter().collect())
286
}
287
288
/// Record that `id` is a fork of `from`.
289
pub async fn set_forked_from(pool: &Pool, id: i64, from: i64) -> sqlx::Result<()> {
290
    sqlx::query("UPDATE repositories SET forked_from = ? WHERE id = ?").bind(from).bind(id).execute(pool).await?;
291
    Ok(())
292
}
293
294
/// The forks of `id`, newest activity first.
295
pub async fn forks_of(pool: &Pool, id: i64) -> sqlx::Result<Vec<RepoRow>> {
296
    sqlx::query_as("SELECT * FROM repositories WHERE forked_from = ? ORDER BY updated_ms DESC").bind(id).fetch_all(pool).await
297
}
298
299
/// `on`, `off`, or `` (follow hub.toml's `[flow] repos`).
300
pub async fn set_flow(pool: &Pool, id: i64, setting: &str) -> sqlx::Result<()> {
301
    sqlx::query("UPDATE repositories SET flow = ? WHERE id = ?").bind(setting).bind(id).execute(pool).await?;
302
    Ok(())
303
}
304
305
pub async fn set_diffusion(pool: &Pool, id: i64, setting: &str) -> sqlx::Result<()> {
306
    sqlx::query("UPDATE repositories SET diffusion = ? WHERE id = ?").bind(setting).bind(id).execute(pool).await?;
307
    Ok(())
308
}
309
310
pub async fn set_git_mirror(pool: &Pool, id: i64, on: bool) -> sqlx::Result<()> {
311
    sqlx::query("UPDATE repositories SET git_mirror = ? WHERE id = ?").bind(on).bind(id).execute(pool).await?;
312
    Ok(())
313
}
314
315
pub async fn set_git_mirror_state(pool: &Pool, id: i64, state: &str) -> sqlx::Result<()> {
316
    sqlx::query("UPDATE repositories SET git_mirror_state = ? WHERE id = ?").bind(state).bind(id).execute(pool).await?;
317
    Ok(())
318
}
319
320
#[cfg(test)]
321
mod topic_tests {
322
    use super::parse_topics;
323
324
    #[test]
325
    fn topics_are_normalised_and_checked() {
326
        assert_eq!(parse_topics("Rust, vcs  retro-computing,rust").unwrap(), "rust vcs retro-computing");
327
        assert_eq!(parse_topics("").unwrap(), "");
328
        assert!(parse_topics("c++").is_err());
329
        assert!(parse_topics("-lead").is_err());
330
        assert!(parse_topics(&"x".repeat(36)).is_err());
331
        assert!(parse_topics(&(0..21).map(|i| format!("t{i}")).collect::<Vec<_>>().join(" ")).is_err());
332
    }
333
}