steid

@jamesgill /

1//! SQLite repository implementations.
2//!
3//! Rows are reassembled with `from_trusted`: they were validated on the way in, and
4//! re-validating them would make a tightened rule turn old rows unreadable.
5
6use std::time::{Duration, SystemTime};
7
8use sqlx::{AssertSqlSafe, Row, SqlitePool, sqlite::SqliteRow};
9
10use crate::domain::{
11 Email, ImportSource, ImportState, Issue, IssueComment, IssueCommentId, IssueId, IssueNumber,
12 IssueState, Label, LabelColour, LabelId, Membership, MembershipId, ObjectId, OrgId, OrgName,
13 Organization, PasswordHash, PersonalAccessToken, PullRequest, PullRequestComment,
14 PullRequestCommentId, PullRequestId, PullRequestState, PushEvent, PushEventId, RefName, RepoId,
15 RepoName, Repository, Role, Session, SessionTokenHash, TokenHash, TokenId, User, UserId,
16 Visibility, Webhook, WebhookDelivery, WebhookDeliveryId, WebhookId, WebhookSecret, WebhookUrl,
17 repository::{
18 IssueCounts, IssueRepository, LabelRepository, MembershipRepository, OrgRepository,
19 PullRequestCounts, PullRequestRepository, PushEventRepository, RepoRepository,
20 RepositoryError, RepositoryResult, SessionRepository, TokenRepository, UserRepository,
21 WebhookDeliveryRepository, WebhookRepository,
22 },
23};
24
25fn backend(error: sqlx::Error) -> RepositoryError {
26 RepositoryError::backend(error)
27}
28
29#[derive(Debug, Clone)]
30pub struct SqliteUserRepo {
31 pool: SqlitePool,
32}
33
34impl SqliteUserRepo {
35 pub fn new(pool: SqlitePool) -> Self {
36 Self { pool }
37 }
38
39 fn map(row: &SqliteRow) -> User {
40 User::new(
41 UserId::from_trusted(row.get::<String, _>("id")),
42 Email::from_trusted(row.get::<String, _>("email")),
43 PasswordHash::from_trusted(row.get::<String, _>("password_hash")),
44 OrgId::from_trusted(row.get::<String, _>("personal_org_id")),
45 )
46 }
47}
48
49impl UserRepository for SqliteUserRepo {
50 async fn find_by_id(&self, id: &UserId) -> RepositoryResult<Option<User>> {
51 let row = sqlx::query("select * from users where id = ?")
52 .bind(id.as_str())
53 .fetch_optional(&self.pool)
54 .await
55 .map_err(backend)?;
56
57 Ok(row.as_ref().map(Self::map))
58 }
59
60 async fn find_by_email(&self, email: &Email) -> RepositoryResult<Option<User>> {
61 let row = sqlx::query("select * from users where email = ?")
62 .bind(email.as_str())
63 .fetch_optional(&self.pool)
64 .await
65 .map_err(backend)?;
66
67 Ok(row.as_ref().map(Self::map))
68 }
69
70 async fn save(&self, user: &User) -> RepositoryResult<()> {
71 sqlx::query(
72 "insert into users (id, email, password_hash, personal_org_id)
73 values (?, ?, ?, ?)
74 on conflict (id) do update set
75 email = excluded.email,
76 password_hash = excluded.password_hash,
77 personal_org_id = excluded.personal_org_id",
78 )
79 .bind(user.id.as_str())
80 .bind(user.email.as_str())
81 .bind(user.password_hash.as_str())
82 .bind(user.personal_org_id.as_str())
83 .execute(&self.pool)
84 .await
85 .map_err(backend)?;
86
87 Ok(())
88 }
89
90 async fn sole_user(&self) -> RepositoryResult<Option<User>> {
91 // `limit 2`, not `limit 1`: the query has to be able to see a second user in
92 // order to refuse, and `limit 1` would silently pick one.
93 let rows = sqlx::query("select * from users limit 2")
94 .fetch_all(&self.pool)
95 .await
96 .map_err(backend)?;
97
98 match rows.as_slice() {
99 [row] => Ok(Some(Self::map(row))),
100 _ => Ok(None),
101 }
102 }
103
104 async fn any_exist(&self) -> RepositoryResult<bool> {
105 let count: i64 = sqlx::query_scalar("select exists (select 1 from users)")
106 .fetch_one(&self.pool)
107 .await
108 .map_err(backend)?;
109
110 Ok(count != 0)
111 }
112}
113
114#[derive(Debug, Clone)]
115pub struct SqliteOrgRepo {
116 pool: SqlitePool,
117}
118
119impl SqliteOrgRepo {
120 pub fn new(pool: SqlitePool) -> Self {
121 Self { pool }
122 }
123
124 fn map(row: &SqliteRow) -> Organization {
125 Organization::from_trusted(
126 OrgId::from_trusted(row.get::<String, _>("id")),
127 OrgName::from_trusted(row.get::<String, _>("name")),
128 row.get::<Option<String>, _>("display_name"),
129 row.get::<Option<String>, _>("bio"),
130 )
131 }
132}
133
134impl OrgRepository for SqliteOrgRepo {
135 async fn find_by_id(&self, id: &OrgId) -> RepositoryResult<Option<Organization>> {
136 let row = sqlx::query("select * from orgs where id = ?")
137 .bind(id.as_str())
138 .fetch_optional(&self.pool)
139 .await
140 .map_err(backend)?;
141
142 Ok(row.as_ref().map(Self::map))
143 }
144
145 async fn find_by_name(&self, name: &OrgName) -> RepositoryResult<Option<Organization>> {
146 let row = sqlx::query("select * from orgs where name = ?")
147 .bind(name.as_str())
148 .fetch_optional(&self.pool)
149 .await
150 .map_err(backend)?;
151
152 Ok(row.as_ref().map(Self::map))
153 }
154
155 async fn save(&self, org: &Organization) -> RepositoryResult<()> {
156 sqlx::query(
157 "insert into orgs (id, name, display_name, bio)
158 values (?, ?, ?, ?)
159 on conflict (id) do update set
160 name = excluded.name,
161 display_name = excluded.display_name,
162 bio = excluded.bio",
163 )
164 .bind(org.id.as_str())
165 .bind(org.name.as_str())
166 .bind(org.display_name.as_deref())
167 .bind(org.bio.as_deref())
168 .execute(&self.pool)
169 .await
170 .map_err(backend)?;
171
172 Ok(())
173 }
174}
175
176#[derive(Debug, Clone)]
177pub struct SqliteMembershipRepo {
178 pool: SqlitePool,
179}
180
181impl SqliteMembershipRepo {
182 pub fn new(pool: SqlitePool) -> Self {
183 Self { pool }
184 }
185
186 /// An unparseable role is a storage fault, not a missing membership, so it
187 /// surfaces rather than silently downgrading the member's access.
188 fn map(row: &SqliteRow) -> RepositoryResult<Membership> {
189 let raw: String = row.get("role");
190 let role: Role = raw
191 .parse()
192 .map_err(|error| RepositoryError::backend(format!("{error}")))?;
193
194 Ok(Membership::new(
195 MembershipId::from_trusted(row.get::<String, _>("id")),
196 OrgId::from_trusted(row.get::<String, _>("org_id")),
197 UserId::from_trusted(row.get::<String, _>("user_id")),
198 role,
199 ))
200 }
201}
202
203impl MembershipRepository for SqliteMembershipRepo {
204 async fn find(&self, org_id: &OrgId, user_id: &UserId) -> RepositoryResult<Option<Membership>> {
205 let row = sqlx::query("select * from memberships where org_id = ? and user_id = ?")
206 .bind(org_id.as_str())
207 .bind(user_id.as_str())
208 .fetch_optional(&self.pool)
209 .await
210 .map_err(backend)?;
211
212 row.as_ref().map(Self::map).transpose()
213 }
214
215 async fn list_for_user(&self, user_id: &UserId) -> RepositoryResult<Vec<Membership>> {
216 let rows = sqlx::query("select * from memberships where user_id = ?")
217 .bind(user_id.as_str())
218 .fetch_all(&self.pool)
219 .await
220 .map_err(backend)?;
221
222 rows.iter().map(Self::map).collect()
223 }
224
225 async fn save(&self, membership: &Membership) -> RepositoryResult<()> {
226 sqlx::query(
227 "insert into memberships (id, org_id, user_id, role)
228 values (?, ?, ?, ?)
229 on conflict (id) do update set role = excluded.role",
230 )
231 .bind(membership.id.as_str())
232 .bind(membership.org_id.as_str())
233 .bind(membership.user_id.as_str())
234 .bind(membership.role.as_str())
235 .execute(&self.pool)
236 .await
237 .map_err(backend)?;
238
239 Ok(())
240 }
241}
242
243#[derive(Debug, Clone)]
244pub struct SqliteSessionRepo {
245 pool: SqlitePool,
246}
247
248impl SqliteSessionRepo {
249 pub fn new(pool: SqlitePool) -> Self {
250 Self { pool }
251 }
252}
253
254/// Unix seconds. Times before the epoch cannot occur here — sessions always expire in
255/// the future — so saturating at 0 is safe rather than lossy.
256fn to_unix(time: SystemTime) -> i64 {
257 time.duration_since(SystemTime::UNIX_EPOCH)
258 .map(|d| d.as_secs() as i64)
259 .unwrap_or(0)
260}
261
262fn from_unix(seconds: i64) -> SystemTime {
263 SystemTime::UNIX_EPOCH + Duration::from_secs(seconds.max(0) as u64)
264}
265
266impl SessionRepository for SqliteSessionRepo {
267 async fn find(&self, token_hash: &SessionTokenHash) -> RepositoryResult<Option<Session>> {
268 let row = sqlx::query("select * from sessions where token_hash = ?")
269 .bind(token_hash.as_str())
270 .fetch_optional(&self.pool)
271 .await
272 .map_err(backend)?;
273
274 Ok(row.map(|row| {
275 Session::new(
276 SessionTokenHash::from_trusted(row.get::<String, _>("token_hash")),
277 UserId::from_trusted(row.get::<String, _>("user_id")),
278 from_unix(row.get::<i64, _>("expires_at")),
279 )
280 }))
281 }
282
283 async fn save(&self, session: &Session) -> RepositoryResult<()> {
284 sqlx::query(
285 "insert into sessions (token_hash, user_id, expires_at)
286 values (?, ?, ?)
287 on conflict (token_hash) do update set
288 user_id = excluded.user_id,
289 expires_at = excluded.expires_at",
290 )
291 .bind(session.token_hash.as_str())
292 .bind(session.user_id.as_str())
293 .bind(to_unix(session.expires_at))
294 .execute(&self.pool)
295 .await
296 .map_err(backend)?;
297
298 Ok(())
299 }
300
301 async fn delete(&self, token_hash: &SessionTokenHash) -> RepositoryResult<()> {
302 sqlx::query("delete from sessions where token_hash = ?")
303 .bind(token_hash.as_str())
304 .execute(&self.pool)
305 .await
306 .map_err(backend)?;
307
308 Ok(())
309 }
310
311 async fn delete_expired(&self, now: SystemTime) -> RepositoryResult<u64> {
312 let result = sqlx::query("delete from sessions where expires_at <= ?")
313 .bind(to_unix(now))
314 .execute(&self.pool)
315 .await
316 .map_err(backend)?;
317
318 Ok(result.rows_affected())
319 }
320}
321
322#[derive(Debug, Clone)]
323pub struct SqliteRepoRepo {
324 pool: SqlitePool,
325}
326
327impl SqliteRepoRepo {
328 pub fn new(pool: SqlitePool) -> Self {
329 Self { pool }
330 }
331
332 /// An unparseable visibility is a storage fault, not a default.
333 ///
334 /// Falling back to `Public` would publish a repository whose row we cannot read;
335 /// falling back to `Private` would hide a public one. Neither is a guess worth
336 /// making, so the row surfaces as an error.
337 fn map(row: &SqliteRow) -> RepositoryResult<Repository> {
338 let raw: String = row.get("visibility");
339 let visibility: Visibility = raw
340 .parse()
341 .map_err(|error| RepositoryError::backend(format!("{error}")))?;
342
343 // An unparseable import state is a fault for the same reason an unparseable
344 // visibility is: both possible defaults are wrong. `None` would serve a
345 // half-cloned repository as finished; `Failed` would bury a working one.
346 let import_state: Option<ImportState> = row
347 .get::<Option<String>, _>("import_state")
348 .map(|raw| raw.parse())
349 .transpose()
350 .map_err(|error| RepositoryError::backend(format!("{error}")))?;
351
352 Ok(Repository::from_trusted(
353 RepoId::from_trusted(row.get::<String, _>("id")),
354 OrgId::from_trusted(row.get::<String, _>("org_id")),
355 RepoName::from_trusted(row.get::<String, _>("name")),
356 row.get::<Option<String>, _>("description"),
357 visibility,
358 from_unix(row.get::<i64, _>("updated_at")),
359 row.get::<i64, _>("pinned") != 0,
360 row.get::<i64, _>("archived") != 0,
361 )
362 .with_import(
363 import_state,
364 row.get::<Option<String>, _>("import_source")
365 .map(ImportSource::from_trusted),
366 row.get::<Option<String>, _>("import_error"),
367 ))
368 }
369}
370
371impl RepoRepository for SqliteRepoRepo {
372 async fn find_by_id(&self, id: &RepoId) -> RepositoryResult<Option<Repository>> {
373 let row = sqlx::query("select * from repositories where id = ?")
374 .bind(id.as_str())
375 .fetch_optional(&self.pool)
376 .await
377 .map_err(backend)?;
378
379 row.as_ref().map(Self::map).transpose()
380 }
381
382 async fn find_by_org_and_name(
383 &self,
384 org_id: &OrgId,
385 name: &RepoName,
386 ) -> RepositoryResult<Option<Repository>> {
387 let row = sqlx::query("select * from repositories where org_id = ? and name = ?")
388 .bind(org_id.as_str())
389 .bind(name.as_str())
390 .fetch_optional(&self.pool)
391 .await
392 .map_err(backend)?;
393
394 row.as_ref().map(Self::map).transpose()
395 }
396
397 async fn list_by_org(&self, org_id: &OrgId) -> RepositoryResult<Vec<Repository>> {
398 // Newest first, name ascending as the tiebreak — `InMemoryRepoRepo::list_by_org`
399 // sorts identically, deliberately.
400 let rows = sqlx::query(
401 "select * from repositories where org_id = ? order by updated_at desc, name asc",
402 )
403 .bind(org_id.as_str())
404 .fetch_all(&self.pool)
405 .await
406 .map_err(backend)?;
407
408 rows.iter().map(Self::map).collect()
409 }
410
411 async fn save(&self, repo: &Repository) -> RepositoryResult<()> {
412 sqlx::query(
413 "insert into repositories
414 (id, org_id, name, description, visibility, updated_at, pinned, archived,
415 import_state, import_source, import_error)
416 values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
417 on conflict (id) do update set
418 org_id = excluded.org_id,
419 name = excluded.name,
420 description = excluded.description,
421 visibility = excluded.visibility,
422 updated_at = excluded.updated_at,
423 pinned = excluded.pinned,
424 archived = excluded.archived,
425 import_state = excluded.import_state,
426 import_source = excluded.import_source,
427 import_error = excluded.import_error",
428 )
429 .bind(repo.id.as_str())
430 .bind(repo.org_id.as_str())
431 .bind(repo.name.as_str())
432 .bind(repo.description.as_deref())
433 .bind(repo.visibility.as_str())
434 .bind(to_unix(repo.updated_at))
435 .bind(i64::from(repo.pinned))
436 .bind(i64::from(repo.archived))
437 .bind(repo.import_state.map(ImportState::as_str))
438 .bind(repo.import_source.as_ref().map(ImportSource::as_str))
439 .bind(repo.import_error.as_deref())
440 .execute(&self.pool)
441 .await
442 .map_err(backend)?;
443
444 Ok(())
445 }
446
447 async fn touch(&self, id: &RepoId, now: SystemTime) -> RepositoryResult<()> {
448 // A column update rather than a read-modify-write, so two pushes racing each
449 // other cannot restore an older timestamp.
450 sqlx::query("update repositories set updated_at = ? where id = ?")
451 .bind(to_unix(now))
452 .bind(id.as_str())
453 .execute(&self.pool)
454 .await
455 .map_err(backend)?;
456
457 Ok(())
458 }
459
460 async fn fail_interrupted_imports(&self, reason: &str) -> RepositoryResult<u64> {
461 let result = sqlx::query(
462 "update repositories
463 set import_state = ?, import_error = ?
464 where import_state = ?",
465 )
466 .bind(ImportState::Failed.as_str())
467 .bind(reason)
468 .bind(ImportState::Importing.as_str())
469 .execute(&self.pool)
470 .await
471 .map_err(backend)?;
472
473 Ok(result.rows_affected())
474 }
475
476 async fn delete(&self, id: &RepoId) -> RepositoryResult<()> {
477 sqlx::query("delete from repositories where id = ?")
478 .bind(id.as_str())
479 .execute(&self.pool)
480 .await
481 .map_err(backend)?;
482
483 Ok(())
484 }
485}
486
487#[derive(Debug, Clone)]
488pub struct SqliteTokenRepo {
489 pool: SqlitePool,
490}
491
492impl SqliteTokenRepo {
493 pub fn new(pool: SqlitePool) -> Self {
494 Self { pool }
495 }
496
497 /// `from_trusted`, because these values were validated on the way in. Revalidating
498 /// stored rows means a tightened rule turns old rows unreadable.
499 fn hydrate(row: &SqliteRow) -> PersonalAccessToken {
500 PersonalAccessToken::from_trusted(
501 TokenId::from_trusted(row.get::<String, _>("id")),
502 UserId::from_trusted(row.get::<String, _>("user_id")),
503 row.get::<String, _>("name"),
504 row.get::<String, _>("prefix"),
505 TokenHash::from_trusted(row.get::<String, _>("token_hash")),
506 from_unix(row.get::<i64, _>("created_at")),
507 row.get::<Option<i64>, _>("expires_at").map(from_unix),
508 row.get::<Option<i64>, _>("last_used_at").map(from_unix),
509 )
510 }
511}
512
513impl TokenRepository for SqliteTokenRepo {
514 async fn find_by_hash(
515 &self,
516 hash: &TokenHash,
517 ) -> RepositoryResult<Option<PersonalAccessToken>> {
518 // Matched in SQL by the hash, which is safe to compare with `=`: it is a digest,
519 // not the secret. The constant-time comparison guards the value a client
520 // presents, and that never reaches the database.
521 let row = sqlx::query("select * from tokens where token_hash = ?")
522 .bind(hash.as_str())
523 .fetch_optional(&self.pool)
524 .await
525 .map_err(backend)?;
526
527 Ok(row.as_ref().map(Self::hydrate))
528 }
529
530 async fn list_by_user(&self, user_id: &UserId) -> RepositoryResult<Vec<PersonalAccessToken>> {
531 let rows =
532 sqlx::query("select * from tokens where user_id = ? order by created_at desc, id asc")
533 .bind(user_id.as_str())
534 .fetch_all(&self.pool)
535 .await
536 .map_err(backend)?;
537
538 Ok(rows.iter().map(Self::hydrate).collect())
539 }
540
541 async fn save(&self, token: &PersonalAccessToken) -> RepositoryResult<()> {
542 sqlx::query(
543 "insert into tokens
544 (id, user_id, name, prefix, token_hash, created_at, expires_at, last_used_at)
545 values (?, ?, ?, ?, ?, ?, ?, ?)
546 on conflict (id) do update set
547 name = excluded.name,
548 expires_at = excluded.expires_at",
549 )
550 .bind(token.id.as_str())
551 .bind(token.user_id.as_str())
552 .bind(&token.name)
553 .bind(&token.prefix)
554 .bind(token.token_hash.as_str())
555 .bind(to_unix(token.created_at))
556 .bind(token.expires_at.map(to_unix))
557 // Deliberately not in the `do update set`: `touch_last_used` owns this column,
558 // and a save carrying a stale record would otherwise walk the last use
559 // backwards.
560 .bind(token.last_used_at.map(to_unix))
561 .execute(&self.pool)
562 .await
563 .map_err(backend)?;
564
565 Ok(())
566 }
567
568 async fn touch_last_used(&self, id: &TokenId, at: SystemTime) -> RepositoryResult<()> {
569 sqlx::query("update tokens set last_used_at = ? where id = ?")
570 .bind(to_unix(at))
571 .bind(id.as_str())
572 .execute(&self.pool)
573 .await
574 .map_err(backend)?;
575
576 Ok(())
577 }
578
579 async fn delete(&self, id: &TokenId) -> RepositoryResult<()> {
580 sqlx::query("delete from tokens where id = ?")
581 .bind(id.as_str())
582 .execute(&self.pool)
583 .await
584 .map_err(backend)?;
585
586 Ok(())
587 }
588}
589
590// --- Issues ------------------------------------------------------------------------
591
592#[derive(Debug, Clone)]
593pub struct SqliteIssueRepo {
594 pool: SqlitePool,
595}
596
597impl SqliteIssueRepo {
598 pub fn new(pool: SqlitePool) -> Self {
599 Self { pool }
600 }
601
602 /// `from_trusted` throughout, including the state: the value was a valid
603 /// [`IssueState`] on the way in, and parsing it here would turn a tightened rule
604 /// into unreadable rows.
605 fn hydrate(row: &SqliteRow) -> Issue {
606 Issue::from_trusted(
607 IssueId::from_trusted(row.get::<String, _>("id")),
608 RepoId::from_trusted(row.get::<String, _>("repo_id")),
609 IssueNumber::from_trusted(row.get::<i64, _>("number").max(1) as u64),
610 row.get::<String, _>("title"),
611 row.get::<String, _>("body"),
612 // The one place a stored value is parsed rather than trusted, because
613 // `IssueState` has no `from_trusted` to give it — and there is nothing
614 // sensible to reconstruct an unknown state as. An unreadable row would be a
615 // bug in a migration, not in user input.
616 row.get::<String, _>("state")
617 .parse()
618 .unwrap_or(IssueState::Open),
619 UserId::from_trusted(row.get::<String, _>("author_id")),
620 from_unix(row.get::<i64, _>("created_at")),
621 from_unix(row.get::<i64, _>("updated_at")),
622 row.get::<Option<i64>, _>("closed_at").map(from_unix),
623 )
624 }
625
626 fn hydrate_comment(row: &SqliteRow) -> IssueComment {
627 IssueComment::from_trusted(
628 IssueCommentId::from_trusted(row.get::<String, _>("id")),
629 IssueId::from_trusted(row.get::<String, _>("issue_id")),
630 UserId::from_trusted(row.get::<String, _>("author_id")),
631 row.get::<String, _>("body"),
632 from_unix(row.get::<i64, _>("created_at")),
633 )
634 }
635}
636
637impl IssueRepository for SqliteIssueRepo {
638 /// One statement, so the read-modify-write is atomic without an explicit
639 /// transaction: SQLite serialises writers, and `on conflict … do update` sees the
640 /// row it is about to replace.
641 ///
642 /// `next_number` holds the number to hand out *next*, so the returned value is
643 /// always one past the allocation — on the insert branch it is 2 and the allocation
644 /// is 1, on the update branch it is `n + 1` and the allocation is `n`. Subtracting
645 /// one covers both without the statement having to know which branch it took.
646 async fn next_number(&self, repo_id: &RepoId) -> RepositoryResult<IssueNumber> {
647 let row = sqlx::query(
648 "insert into repo_sequences (repo_id, next_number) values (?, 2)
649 on conflict (repo_id) do update set next_number = next_number + 1
650 returning next_number",
651 )
652 .bind(repo_id.as_str())
653 .fetch_one(&self.pool)
654 .await
655 .map_err(backend)?;
656
657 let allocated = row.get::<i64, _>("next_number").saturating_sub(1).max(1);
658
659 Ok(IssueNumber::from_trusted(allocated as u64))
660 }
661
662 async fn find_by_number(
663 &self,
664 repo_id: &RepoId,
665 number: IssueNumber,
666 ) -> RepositoryResult<Option<Issue>> {
667 let row = sqlx::query("select * from issues where repo_id = ? and number = ?")
668 .bind(repo_id.as_str())
669 .bind(number.get() as i64)
670 .fetch_optional(&self.pool)
671 .await
672 .map_err(backend)?;
673
674 Ok(row.as_ref().map(Self::hydrate))
675 }
676
677 async fn list_by_repo(
678 &self,
679 repo_id: &RepoId,
680 state: IssueState,
681 offset: usize,
682 limit: usize,
683 ) -> RepositoryResult<Vec<Issue>> {
684 // Newest first is descending *number*, not descending `created_at`: the
685 // sequence is monotonic, so it orders identically and cannot tie — which also
686 // makes `limit`/`offset` stable, since two rows can never swap places between
687 // one page and the next.
688 //
689 // A `limit` too large for SQLite's signed integer becomes the largest one it
690 // has, which is the same answer: every remaining row.
691 let rows = sqlx::query(
692 "select * from issues where repo_id = ? and state = ?
693 order by number desc
694 limit ? offset ?",
695 )
696 .bind(repo_id.as_str())
697 .bind(state.as_str())
698 .bind(i64::try_from(limit).unwrap_or(i64::MAX))
699 .bind(i64::try_from(offset).unwrap_or(i64::MAX))
700 .fetch_all(&self.pool)
701 .await
702 .map_err(backend)?;
703
704 Ok(rows.iter().map(Self::hydrate).collect())
705 }
706
707 async fn counts(&self, repo_id: &RepoId) -> RepositoryResult<IssueCounts> {
708 let rows = sqlx::query(
709 "select state, count(*) as total from issues where repo_id = ? group by state",
710 )
711 .bind(repo_id.as_str())
712 .fetch_all(&self.pool)
713 .await
714 .map_err(backend)?;
715
716 let mut counts = IssueCounts::default();
717
718 for row in &rows {
719 let total = row.get::<i64, _>("total").max(0) as u64;
720
721 match row.get::<String, _>("state").parse() {
722 Ok(IssueState::Open) => counts.open = total,
723 Ok(IssueState::Closed) => counts.closed = total,
724 // A state neither implementation can name is not counted as either. It
725 // would take a hand-edited row to reach this.
726 Err(_) => {}
727 }
728 }
729
730 Ok(counts)
731 }
732
733 async fn comment_counts(&self, repo_id: &RepoId) -> RepositoryResult<Vec<(IssueId, u64)>> {
734 // A left join so an issue with no comments still gets a row: the caller builds a
735 // lookup out of this, and a missing key and a zero would have to be handled
736 // identically anyway.
737 let rows = sqlx::query(
738 "select issues.id as issue_id, count(issue_comments.id) as total
739 from issues
740 left join issue_comments on issue_comments.issue_id = issues.id
741 where issues.repo_id = ?
742 group by issues.id",
743 )
744 .bind(repo_id.as_str())
745 .fetch_all(&self.pool)
746 .await
747 .map_err(backend)?;
748
749 Ok(rows
750 .iter()
751 .map(|row| {
752 (
753 IssueId::from_trusted(row.get::<String, _>("issue_id")),
754 row.get::<i64, _>("total").max(0) as u64,
755 )
756 })
757 .collect())
758 }
759
760 async fn save(&self, issue: &Issue) -> RepositoryResult<()> {
761 // `number`, `repo_id` and `author_id` are absent from the update list on
762 // purpose: an issue's identity is its number on its repository, and an edit that
763 // could move it would break every link ever written to it.
764 sqlx::query(
765 "insert into issues
766 (id, repo_id, number, title, body, state, author_id, created_at, updated_at, closed_at)
767 values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
768 on conflict (id) do update set
769 title = excluded.title,
770 body = excluded.body,
771 state = excluded.state,
772 updated_at = excluded.updated_at,
773 closed_at = excluded.closed_at",
774 )
775 .bind(issue.id.as_str())
776 .bind(issue.repo_id.as_str())
777 .bind(issue.number.get() as i64)
778 .bind(&issue.title)
779 .bind(&issue.body)
780 .bind(issue.state.as_str())
781 .bind(issue.author_id.as_str())
782 .bind(to_unix(issue.created_at))
783 .bind(to_unix(issue.updated_at))
784 .bind(issue.closed_at.map(to_unix))
785 .execute(&self.pool)
786 .await
787 .map_err(backend)?;
788
789 Ok(())
790 }
791
792 async fn list_comments(&self, issue_id: &IssueId) -> RepositoryResult<Vec<IssueComment>> {
793 // `rowid` breaks a tie, which is insertion order — two comments posted in the
794 // same second read in the order they were written. The id would not do: it is a
795 // random UUID, so a tie would come back in an arbitrary order and a conversation
796 // would occasionally read backwards.
797 let rows = sqlx::query(
798 "select * from issue_comments where issue_id = ? order by created_at asc, rowid asc",
799 )
800 .bind(issue_id.as_str())
801 .fetch_all(&self.pool)
802 .await
803 .map_err(backend)?;
804
805 Ok(rows.iter().map(Self::hydrate_comment).collect())
806 }
807
808 async fn add_comment(&self, comment: &IssueComment) -> RepositoryResult<()> {
809 sqlx::query(
810 "insert into issue_comments (id, issue_id, author_id, body, created_at)
811 values (?, ?, ?, ?, ?)",
812 )
813 .bind(comment.id.as_str())
814 .bind(comment.issue_id.as_str())
815 .bind(comment.author_id.as_str())
816 .bind(&comment.body)
817 .bind(to_unix(comment.created_at))
818 .execute(&self.pool)
819 .await
820 .map_err(backend)?;
821
822 Ok(())
823 }
824}
825
826#[derive(Debug, Clone)]
827pub struct SqlitePushEventRepo {
828 pool: SqlitePool,
829}
830
831impl SqlitePushEventRepo {
832 pub fn new(pool: SqlitePool) -> Self {
833 Self { pool }
834 }
835
836 fn hydrate(row: &SqliteRow) -> PushEvent {
837 PushEvent::from_trusted(
838 PushEventId::from_trusted(row.get::<String, _>("id")),
839 RepoId::from_trusted(row.get::<String, _>("repo_id")),
840 RefName::from_trusted(row.get::<String, _>("ref_name")),
841 ObjectId::from_trusted(row.get::<String, _>("before_id")),
842 ObjectId::from_trusted(row.get::<String, _>("after_id")),
843 row.get::<Option<String>, _>("pusher_id")
844 .map(UserId::from_trusted),
845 from_unix(row.get::<i64, _>("created_at")),
846 )
847 }
848}
849
850impl PushEventRepository for SqlitePushEventRepo {
851 async fn find(&self, id: &PushEventId) -> RepositoryResult<Option<PushEvent>> {
852 let row = sqlx::query("select * from push_events where id = ?")
853 .bind(id.as_str())
854 .fetch_optional(&self.pool)
855 .await
856 .map_err(backend)?;
857
858 Ok(row.as_ref().map(Self::hydrate))
859 }
860
861 async fn list_by_repo(
862 &self,
863 repo_id: &RepoId,
864 limit: usize,
865 ) -> RepositoryResult<Vec<PushEvent>> {
866 // The id breaks the tie, as it does for tokens: a `git push --all` writes every
867 // event in the same second, and without it the order is whatever SQLite felt
868 // like.
869 let rows = sqlx::query(
870 "select * from push_events where repo_id = ?
871 order by created_at desc, id asc
872 limit ?",
873 )
874 .bind(repo_id.as_str())
875 .bind(limit as i64)
876 .fetch_all(&self.pool)
877 .await
878 .map_err(backend)?;
879
880 Ok(rows.iter().map(Self::hydrate).collect())
881 }
882
883 async fn list_recent(
884 &self,
885 repo_ids: &[RepoId],
886 limit: usize,
887 ) -> RepositoryResult<Vec<PushEvent>> {
888 // No repositories means nothing to ask about — and `in ()` is a syntax error in
889 // SQLite, so the empty case has to be answered before the query is built.
890 if repo_ids.is_empty() {
891 return Ok(Vec::new());
892 }
893
894 // The `in` list is built from the *count* and every id is bound, so nothing
895 // from a repository name ever reaches the SQL text. `push_events_repo_id`
896 // covers `(repo_id, created_at desc)`, which is what this walks.
897 let placeholders = vec!["?"; repo_ids.len()].join(", ");
898 let sql = format!(
899 "select * from push_events where repo_id in ({placeholders})
900 order by created_at desc, id asc
901 limit ?"
902 );
903
904 // `AssertSqlSafe` because the string is built here and nowhere else: the only
905 // thing that varies is how many `?` the list has, and every id is bound.
906 let mut query = sqlx::query(AssertSqlSafe(sql));
907 for id in repo_ids {
908 query = query.bind(id.as_str());
909 }
910
911 let rows = query
912 .bind(limit as i64)
913 .fetch_all(&self.pool)
914 .await
915 .map_err(backend)?;
916
917 Ok(rows.iter().map(Self::hydrate).collect())
918 }
919
920 async fn save(&self, event: &PushEvent) -> RepositoryResult<()> {
921 sqlx::query(
922 "insert into push_events
923 (id, repo_id, ref_name, before_id, after_id, pusher_id, created_at)
924 values (?, ?, ?, ?, ?, ?, ?)
925 on conflict (id) do nothing",
926 )
927 .bind(event.id.as_str())
928 .bind(event.repo_id.as_str())
929 .bind(event.ref_name.as_str())
930 .bind(event.before.as_str())
931 .bind(event.after.as_str())
932 .bind(event.pusher.as_ref().map(|id| id.as_str()))
933 .bind(to_unix(event.created_at))
934 .execute(&self.pool)
935 .await
936 .map_err(backend)?;
937
938 Ok(())
939 }
940}
941
942#[derive(Debug, Clone)]
943pub struct SqliteWebhookRepo {
944 pool: SqlitePool,
945}
946
947impl SqliteWebhookRepo {
948 pub fn new(pool: SqlitePool) -> Self {
949 Self { pool }
950 }
951
952 fn hydrate(row: &SqliteRow) -> Webhook {
953 Webhook::from_trusted(
954 WebhookId::from_trusted(row.get::<String, _>("id")),
955 RepoId::from_trusted(row.get::<String, _>("repo_id")),
956 WebhookUrl::from_trusted(row.get::<String, _>("url")),
957 WebhookSecret::from_trusted(row.get::<String, _>("secret")),
958 row.get::<i64, _>("active") != 0,
959 from_unix(row.get::<i64, _>("created_at")),
960 )
961 }
962}
963
964impl WebhookRepository for SqliteWebhookRepo {
965 async fn find(&self, id: &WebhookId) -> RepositoryResult<Option<Webhook>> {
966 let row = sqlx::query("select * from webhooks where id = ?")
967 .bind(id.as_str())
968 .fetch_optional(&self.pool)
969 .await
970 .map_err(backend)?;
971
972 Ok(row.as_ref().map(Self::hydrate))
973 }
974
975 async fn list_by_repo(&self, repo_id: &RepoId) -> RepositoryResult<Vec<Webhook>> {
976 let rows =
977 sqlx::query("select * from webhooks where repo_id = ? order by created_at asc, id asc")
978 .bind(repo_id.as_str())
979 .fetch_all(&self.pool)
980 .await
981 .map_err(backend)?;
982
983 Ok(rows.iter().map(Self::hydrate).collect())
984 }
985
986 async fn save(&self, webhook: &Webhook) -> RepositoryResult<()> {
987 sqlx::query(
988 "insert into webhooks (id, repo_id, url, secret, active, created_at)
989 values (?, ?, ?, ?, ?, ?)
990 on conflict (id) do update set
991 url = excluded.url,
992 active = excluded.active",
993 )
994 .bind(webhook.id.as_str())
995 .bind(webhook.repo_id.as_str())
996 .bind(webhook.url.as_str())
997 .bind(webhook.secret.reveal())
998 .bind(i64::from(webhook.active))
999 .bind(to_unix(webhook.created_at))
1000 .execute(&self.pool)
1001 .await
1002 .map_err(backend)?;
1003
1004 Ok(())
1005 }
1006
1007 async fn delete(&self, id: &WebhookId) -> RepositoryResult<()> {
1008 sqlx::query("delete from webhooks where id = ?")
1009 .bind(id.as_str())
1010 .execute(&self.pool)
1011 .await
1012 .map_err(backend)?;
1013
1014 Ok(())
1015 }
1016}
1017
1018#[derive(Debug, Clone)]
1019pub struct SqliteWebhookDeliveryRepo {
1020 pool: SqlitePool,
1021}
1022
1023impl SqliteWebhookDeliveryRepo {
1024 pub fn new(pool: SqlitePool) -> Self {
1025 Self { pool }
1026 }
1027
1028 fn hydrate(row: &SqliteRow) -> WebhookDelivery {
1029 WebhookDelivery::from_trusted(
1030 WebhookDeliveryId::from_trusted(row.get::<String, _>("id")),
1031 WebhookId::from_trusted(row.get::<String, _>("webhook_id")),
1032 PushEventId::from_trusted(row.get::<String, _>("event_id")),
1033 row.get::<i64, _>("attempt") as u32,
1034 row.get::<Option<i64>, _>("status_code")
1035 .map(|code| code as u16),
1036 row.get::<String, _>("response"),
1037 row.get::<i64, _>("duration_ms").max(0) as u64,
1038 from_unix(row.get::<i64, _>("delivered_at")),
1039 row.get::<i64, _>("ok") != 0,
1040 )
1041 }
1042}
1043
1044impl WebhookDeliveryRepository for SqliteWebhookDeliveryRepo {
1045 async fn list_by_webhook(
1046 &self,
1047 webhook_id: &WebhookId,
1048 offset: usize,
1049 limit: usize,
1050 ) -> RepositoryResult<Vec<WebhookDelivery>> {
1051 // Attempt descending as the tiebreak, not the id: three attempts against a dead
1052 // endpoint can land in the same second only when the failure is instant, and
1053 // when they do the useful order is last-tried-first. The tiebreak is what makes
1054 // `offset` stable — without it two rows could swap between pages.
1055 let rows = sqlx::query(
1056 "select * from webhook_deliveries where webhook_id = ?
1057 order by delivered_at desc, attempt desc
1058 limit ? offset ?",
1059 )
1060 .bind(webhook_id.as_str())
1061 .bind(i64::try_from(limit).unwrap_or(i64::MAX))
1062 .bind(i64::try_from(offset).unwrap_or(i64::MAX))
1063 .fetch_all(&self.pool)
1064 .await
1065 .map_err(backend)?;
1066
1067 Ok(rows.iter().map(Self::hydrate).collect())
1068 }
1069
1070 async fn count_by_webhook(&self, webhook_id: &WebhookId) -> RepositoryResult<usize> {
1071 let row =
1072 sqlx::query("select count(*) as total from webhook_deliveries where webhook_id = ?")
1073 .bind(webhook_id.as_str())
1074 .fetch_one(&self.pool)
1075 .await
1076 .map_err(backend)?;
1077
1078 Ok(row.get::<i64, _>("total").max(0) as usize)
1079 }
1080
1081 async fn latest_by_webhook(
1082 &self,
1083 webhook_id: &WebhookId,
1084 ) -> RepositoryResult<Option<WebhookDelivery>> {
1085 let row = sqlx::query(
1086 "select * from webhook_deliveries where webhook_id = ?
1087 order by delivered_at desc, attempt desc
1088 limit 1",
1089 )
1090 .bind(webhook_id.as_str())
1091 .fetch_optional(&self.pool)
1092 .await
1093 .map_err(backend)?;
1094
1095 Ok(row.as_ref().map(Self::hydrate))
1096 }
1097
1098 async fn save(&self, delivery: &WebhookDelivery) -> RepositoryResult<()> {
1099 sqlx::query(
1100 "insert into webhook_deliveries
1101 (id, webhook_id, event_id, attempt, status_code, response,
1102 duration_ms, delivered_at, ok)
1103 values (?, ?, ?, ?, ?, ?, ?, ?, ?)
1104 on conflict (id) do nothing",
1105 )
1106 .bind(delivery.id.as_str())
1107 .bind(delivery.webhook_id.as_str())
1108 .bind(delivery.event_id.as_str())
1109 .bind(i64::from(delivery.attempt))
1110 .bind(delivery.status.map(i64::from))
1111 .bind(&delivery.response)
1112 .bind(delivery.duration_ms as i64)
1113 .bind(to_unix(delivery.delivered_at))
1114 .bind(i64::from(delivery.ok))
1115 .execute(&self.pool)
1116 .await
1117 .map_err(backend)?;
1118
1119 Ok(())
1120 }
1121}
1122
1123// --- Labels ------------------------------------------------------------------------
1124
1125#[derive(Debug, Clone)]
1126pub struct SqliteLabelRepo {
1127 pool: SqlitePool,
1128}
1129
1130impl SqliteLabelRepo {
1131 pub fn new(pool: SqlitePool) -> Self {
1132 Self { pool }
1133 }
1134
1135 /// `from_trusted` throughout, except the colour — which has no `from_trusted` to
1136 /// give it, exactly like `IssueState`. A value neither name matches would take a
1137 /// hand-edited row, and gray is the one reading that cannot claim a label is more
1138 /// urgent than it is.
1139 fn hydrate(row: &SqliteRow) -> Label {
1140 Label::from_trusted(
1141 LabelId::from_trusted(row.get::<String, _>("id")),
1142 RepoId::from_trusted(row.get::<String, _>("repo_id")),
1143 row.get::<String, _>("name"),
1144 row.get::<String, _>("colour")
1145 .parse()
1146 .unwrap_or(LabelColour::Gray),
1147 row.get::<Option<String>, _>("description"),
1148 from_unix(row.get::<i64, _>("created_at")),
1149 )
1150 }
1151}
1152
1153impl LabelRepository for SqliteLabelRepo {
1154 async fn list_by_repo(&self, repo_id: &RepoId) -> RepositoryResult<Vec<Label>> {
1155 let rows = sqlx::query("select * from labels where repo_id = ? order by name asc")
1156 .bind(repo_id.as_str())
1157 .fetch_all(&self.pool)
1158 .await
1159 .map_err(backend)?;
1160
1161 Ok(rows.iter().map(Self::hydrate).collect())
1162 }
1163
1164 async fn find_by_id(&self, id: &LabelId) -> RepositoryResult<Option<Label>> {
1165 let row = sqlx::query("select * from labels where id = ?")
1166 .bind(id.as_str())
1167 .fetch_optional(&self.pool)
1168 .await
1169 .map_err(backend)?;
1170
1171 Ok(row.as_ref().map(Self::hydrate))
1172 }
1173
1174 async fn find_by_name(&self, repo_id: &RepoId, name: &str) -> RepositoryResult<Option<Label>> {
1175 let row = sqlx::query("select * from labels where repo_id = ? and name = ?")
1176 .bind(repo_id.as_str())
1177 .bind(name)
1178 .fetch_optional(&self.pool)
1179 .await
1180 .map_err(backend)?;
1181
1182 Ok(row.as_ref().map(Self::hydrate))
1183 }
1184
1185 async fn save(&self, label: &Label) -> RepositoryResult<()> {
1186 // `repo_id` is absent from the update list on purpose: a label belongs to the
1187 // repository it was made on, and moving one would take it off every issue that
1188 // wears it without saying so.
1189 sqlx::query(
1190 "insert into labels (id, repo_id, name, colour, description, created_at)
1191 values (?, ?, ?, ?, ?, ?)
1192 on conflict (id) do update set
1193 name = excluded.name,
1194 colour = excluded.colour,
1195 description = excluded.description",
1196 )
1197 .bind(label.id.as_str())
1198 .bind(label.repo_id.as_str())
1199 .bind(&label.name)
1200 .bind(label.colour.as_str())
1201 .bind(label.description.as_deref())
1202 .bind(to_unix(label.created_at))
1203 .execute(&self.pool)
1204 .await
1205 .map_err(backend)?;
1206
1207 Ok(())
1208 }
1209
1210 async fn delete(&self, id: &LabelId) -> RepositoryResult<()> {
1211 // The assignments go with it through both join tables' `on delete cascade`, which
1212 // the connection enables foreign keys for — see `database::connect`.
1213 sqlx::query("delete from labels where id = ?")
1214 .bind(id.as_str())
1215 .execute(&self.pool)
1216 .await
1217 .map_err(backend)?;
1218
1219 Ok(())
1220 }
1221
1222 async fn labels_for_issue(&self, issue_id: &IssueId) -> RepositoryResult<Vec<Label>> {
1223 let rows = sqlx::query(
1224 "select labels.* from labels
1225 join issue_labels on issue_labels.label_id = labels.id
1226 where issue_labels.issue_id = ?
1227 order by labels.name asc",
1228 )
1229 .bind(issue_id.as_str())
1230 .fetch_all(&self.pool)
1231 .await
1232 .map_err(backend)?;
1233
1234 Ok(rows.iter().map(Self::hydrate).collect())
1235 }
1236
1237 async fn labels_for_repo(&self, repo_id: &RepoId) -> RepositoryResult<Vec<(IssueId, Label)>> {
1238 // Every pair on the repository in one statement: the list page renders pills on
1239 // every row, and asking per row is a query per row.
1240 let rows = sqlx::query(
1241 "select issue_labels.issue_id as issue_id, labels.* from labels
1242 join issue_labels on issue_labels.label_id = labels.id
1243 where labels.repo_id = ?
1244 order by issue_labels.issue_id asc, labels.name asc",
1245 )
1246 .bind(repo_id.as_str())
1247 .fetch_all(&self.pool)
1248 .await
1249 .map_err(backend)?;
1250
1251 Ok(rows
1252 .iter()
1253 .map(|row| {
1254 (
1255 IssueId::from_trusted(row.get::<String, _>("issue_id")),
1256 Self::hydrate(row),
1257 )
1258 })
1259 .collect())
1260 }
1261
1262 async fn issue_counts(&self, repo_id: &RepoId) -> RepositoryResult<Vec<(LabelId, u64)>> {
1263 // A left join so an unused label still gets a row, for the same reason
1264 // `comment_counts` uses one: the caller builds a lookup, and a missing key and a
1265 // zero would have to be handled identically anyway.
1266 let rows = sqlx::query(
1267 "select labels.id as label_id, count(issue_labels.issue_id) as total
1268 from labels
1269 left join issue_labels on issue_labels.label_id = labels.id
1270 where labels.repo_id = ?
1271 group by labels.id",
1272 )
1273 .bind(repo_id.as_str())
1274 .fetch_all(&self.pool)
1275 .await
1276 .map_err(backend)?;
1277
1278 Ok(rows
1279 .iter()
1280 .map(|row| {
1281 (
1282 LabelId::from_trusted(row.get::<String, _>("label_id")),
1283 row.get::<i64, _>("total").max(0) as u64,
1284 )
1285 })
1286 .collect())
1287 }
1288
1289 async fn set_issue_labels(
1290 &self,
1291 issue_id: &IssueId,
1292 labels: &[LabelId],
1293 ) -> RepositoryResult<()> {
1294 // One transaction, because the delete and the inserts are one replacement: a
1295 // reader that arrived between them would see an issue with no labels at all.
1296 let mut tx = self.pool.begin().await.map_err(backend)?;
1297
1298 sqlx::query("delete from issue_labels where issue_id = ?")
1299 .bind(issue_id.as_str())
1300 .execute(&mut *tx)
1301 .await
1302 .map_err(backend)?;
1303
1304 for label in labels {
1305 // `or ignore` rather than a plain insert: the same label ticked twice in a
1306 // tampered form is the same assignment, not an error.
1307 sqlx::query("insert or ignore into issue_labels (issue_id, label_id) values (?, ?)")
1308 .bind(issue_id.as_str())
1309 .bind(label.as_str())
1310 .execute(&mut *tx)
1311 .await
1312 .map_err(backend)?;
1313 }
1314
1315 tx.commit().await.map_err(backend)?;
1316
1317 Ok(())
1318 }
1319
1320 async fn labels_for_pull(&self, pull_id: &PullRequestId) -> RepositoryResult<Vec<Label>> {
1321 let rows = sqlx::query(
1322 "select labels.* from labels
1323 join pull_request_labels on pull_request_labels.label_id = labels.id
1324 where pull_request_labels.pull_request_id = ?
1325 order by labels.name asc",
1326 )
1327 .bind(pull_id.as_str())
1328 .fetch_all(&self.pool)
1329 .await
1330 .map_err(backend)?;
1331
1332 Ok(rows.iter().map(Self::hydrate).collect())
1333 }
1334
1335 async fn labels_for_repo_pulls(
1336 &self,
1337 repo_id: &RepoId,
1338 ) -> RepositoryResult<Vec<(PullRequestId, Label)>> {
1339 let rows = sqlx::query(
1340 "select pull_request_labels.pull_request_id as pull_request_id, labels.* from labels
1341 join pull_request_labels on pull_request_labels.label_id = labels.id
1342 where labels.repo_id = ?
1343 order by pull_request_labels.pull_request_id asc, labels.name asc",
1344 )
1345 .bind(repo_id.as_str())
1346 .fetch_all(&self.pool)
1347 .await
1348 .map_err(backend)?;
1349
1350 Ok(rows
1351 .iter()
1352 .map(|row| {
1353 (
1354 PullRequestId::from_trusted(row.get::<String, _>("pull_request_id")),
1355 Self::hydrate(row),
1356 )
1357 })
1358 .collect())
1359 }
1360
1361 async fn pull_counts(&self, repo_id: &RepoId) -> RepositoryResult<Vec<(LabelId, u64)>> {
1362 let rows = sqlx::query(
1363 "select labels.id as label_id,
1364 count(pull_request_labels.pull_request_id) as total
1365 from labels
1366 left join pull_request_labels on pull_request_labels.label_id = labels.id
1367 where labels.repo_id = ?
1368 group by labels.id",
1369 )
1370 .bind(repo_id.as_str())
1371 .fetch_all(&self.pool)
1372 .await
1373 .map_err(backend)?;
1374
1375 Ok(rows
1376 .iter()
1377 .map(|row| {
1378 (
1379 LabelId::from_trusted(row.get::<String, _>("label_id")),
1380 row.get::<i64, _>("total").max(0) as u64,
1381 )
1382 })
1383 .collect())
1384 }
1385
1386 async fn set_pull_labels(
1387 &self,
1388 pull_id: &PullRequestId,
1389 labels: &[LabelId],
1390 ) -> RepositoryResult<()> {
1391 // One transaction, for the reason `set_issue_labels` gives.
1392 let mut tx = self.pool.begin().await.map_err(backend)?;
1393
1394 sqlx::query("delete from pull_request_labels where pull_request_id = ?")
1395 .bind(pull_id.as_str())
1396 .execute(&mut *tx)
1397 .await
1398 .map_err(backend)?;
1399
1400 for label in labels {
1401 sqlx::query(
1402 "insert or ignore into pull_request_labels (pull_request_id, label_id)
1403 values (?, ?)",
1404 )
1405 .bind(pull_id.as_str())
1406 .bind(label.as_str())
1407 .execute(&mut *tx)
1408 .await
1409 .map_err(backend)?;
1410 }
1411
1412 tx.commit().await.map_err(backend)?;
1413
1414 Ok(())
1415 }
1416}
1417
1418#[derive(Debug, Clone)]
1419pub struct SqlitePullRequestRepo {
1420 pool: SqlitePool,
1421}
1422
1423impl SqlitePullRequestRepo {
1424 pub fn new(pool: SqlitePool) -> Self {
1425 Self { pool }
1426 }
1427
1428 /// `from_trusted` throughout, including both branch names: they were valid
1429 /// [`RefName`]s on the way in, and re-validating them here would turn a tightened
1430 /// rule into unreadable rows.
1431 fn hydrate(row: &SqliteRow) -> PullRequest {
1432 PullRequest::from_trusted(
1433 PullRequestId::from_trusted(row.get::<String, _>("id")),
1434 RepoId::from_trusted(row.get::<String, _>("repo_id")),
1435 IssueNumber::from_trusted(row.get::<i64, _>("number").max(1) as u64),
1436 row.get::<String, _>("title"),
1437 row.get::<String, _>("body"),
1438 // The one stored value that is parsed rather than trusted, for the reason
1439 // `SqliteIssueRepo` parses a state: `PullRequestState` has no
1440 // `from_trusted`, and there is nothing sensible to reconstruct an unknown
1441 // state as. Falling back to `Open` and not to `Merged` is deliberate — a
1442 // row that cannot be read must not claim something landed.
1443 row.get::<String, _>("state")
1444 .parse()
1445 .unwrap_or(PullRequestState::Open),
1446 UserId::from_trusted(row.get::<String, _>("author_id")),
1447 RefName::from_trusted(row.get::<String, _>("source_branch")),
1448 RefName::from_trusted(row.get::<String, _>("target_branch")),
1449 from_unix(row.get::<i64, _>("created_at")),
1450 from_unix(row.get::<i64, _>("updated_at")),
1451 row.get::<Option<i64>, _>("closed_at").map(from_unix),
1452 row.get::<Option<i64>, _>("merged_at").map(from_unix),
1453 row.get::<Option<String>, _>("merge_commit")
1454 .map(ObjectId::from_trusted),
1455 )
1456 }
1457
1458 fn hydrate_comment(row: &SqliteRow) -> PullRequestComment {
1459 PullRequestComment::from_trusted(
1460 PullRequestCommentId::from_trusted(row.get::<String, _>("id")),
1461 PullRequestId::from_trusted(row.get::<String, _>("pull_request_id")),
1462 UserId::from_trusted(row.get::<String, _>("author_id")),
1463 row.get::<String, _>("body"),
1464 from_unix(row.get::<i64, _>("created_at")),
1465 )
1466 }
1467}
1468
1469impl PullRequestRepository for SqlitePullRequestRepo {
1470 async fn find_by_number(
1471 &self,
1472 repo_id: &RepoId,
1473 number: IssueNumber,
1474 ) -> RepositoryResult<Option<PullRequest>> {
1475 let row = sqlx::query("select * from pull_requests where repo_id = ? and number = ?")
1476 .bind(repo_id.as_str())
1477 .bind(number.get() as i64)
1478 .fetch_optional(&self.pool)
1479 .await
1480 .map_err(backend)?;
1481
1482 Ok(row.as_ref().map(Self::hydrate))
1483 }
1484
1485 async fn list_by_repo(
1486 &self,
1487 repo_id: &RepoId,
1488 state: PullRequestState,
1489 offset: usize,
1490 limit: usize,
1491 ) -> RepositoryResult<Vec<PullRequest>> {
1492 // Descending number rather than descending `created_at`, exactly as the issue
1493 // list does: the sequence is monotonic, so it orders identically, cannot tie,
1494 // and makes `limit`/`offset` stable across pages.
1495 let rows = sqlx::query(
1496 "select * from pull_requests where repo_id = ? and state = ?
1497 order by number desc
1498 limit ? offset ?",
1499 )
1500 .bind(repo_id.as_str())
1501 .bind(state.as_str())
1502 .bind(i64::try_from(limit).unwrap_or(i64::MAX))
1503 .bind(i64::try_from(offset).unwrap_or(i64::MAX))
1504 .fetch_all(&self.pool)
1505 .await
1506 .map_err(backend)?;
1507
1508 Ok(rows.iter().map(Self::hydrate).collect())
1509 }
1510
1511 async fn counts(&self, repo_id: &RepoId) -> RepositoryResult<PullRequestCounts> {
1512 let rows = sqlx::query(
1513 "select state, count(*) as total from pull_requests where repo_id = ? group by state",
1514 )
1515 .bind(repo_id.as_str())
1516 .fetch_all(&self.pool)
1517 .await
1518 .map_err(backend)?;
1519
1520 let mut counts = PullRequestCounts::default();
1521
1522 for row in &rows {
1523 let total = row.get::<i64, _>("total").max(0) as u64;
1524
1525 match row.get::<String, _>("state").parse() {
1526 Ok(PullRequestState::Open) => counts.open = total,
1527 Ok(PullRequestState::Merged) => counts.merged = total,
1528 Ok(PullRequestState::Closed) => counts.closed = total,
1529 // A state neither implementation can name is counted as none of them.
1530 // It would take a hand-edited row to reach this.
1531 Err(_) => {}
1532 }
1533 }
1534
1535 Ok(counts)
1536 }
1537
1538 async fn comment_counts(
1539 &self,
1540 repo_id: &RepoId,
1541 ) -> RepositoryResult<Vec<(PullRequestId, u64)>> {
1542 // A left join so a request with no comments still gets a row: the caller builds
1543 // a lookup out of this, and a missing key and a zero would be handled alike.
1544 let rows = sqlx::query(
1545 "select pull_requests.id as pull_id, count(pull_request_comments.id) as total
1546 from pull_requests
1547 left join pull_request_comments
1548 on pull_request_comments.pull_request_id = pull_requests.id
1549 where pull_requests.repo_id = ?
1550 group by pull_requests.id",
1551 )
1552 .bind(repo_id.as_str())
1553 .fetch_all(&self.pool)
1554 .await
1555 .map_err(backend)?;
1556
1557 Ok(rows
1558 .iter()
1559 .map(|row| {
1560 (
1561 PullRequestId::from_trusted(row.get::<String, _>("pull_id")),
1562 row.get::<i64, _>("total").max(0) as u64,
1563 )
1564 })
1565 .collect())
1566 }
1567
1568 async fn save(&self, pull: &PullRequest) -> RepositoryResult<()> {
1569 // `number`, `repo_id`, `author_id` and both branches are absent from the update
1570 // list on purpose. The first three for the reason an issue's are — identity is
1571 // the number on the repository — and the branches because changing either would
1572 // make every comment on the request an opinion about a different change.
1573 sqlx::query(
1574 "insert into pull_requests
1575 (id, repo_id, number, title, body, state, author_id, source_branch,
1576 target_branch, created_at, updated_at, closed_at, merged_at, merge_commit)
1577 values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1578 on conflict (id) do update set
1579 title = excluded.title,
1580 body = excluded.body,
1581 state = excluded.state,
1582 updated_at = excluded.updated_at,
1583 closed_at = excluded.closed_at,
1584 merged_at = excluded.merged_at,
1585 merge_commit = excluded.merge_commit",
1586 )
1587 .bind(pull.id.as_str())
1588 .bind(pull.repo_id.as_str())
1589 .bind(pull.number.get() as i64)
1590 .bind(&pull.title)
1591 .bind(&pull.body)
1592 .bind(pull.state.as_str())
1593 .bind(pull.author_id.as_str())
1594 .bind(pull.source_branch.as_str())
1595 .bind(pull.target_branch.as_str())
1596 .bind(to_unix(pull.created_at))
1597 .bind(to_unix(pull.updated_at))
1598 .bind(pull.closed_at.map(to_unix))
1599 .bind(pull.merged_at.map(to_unix))
1600 .bind(pull.merge_commit.as_ref().map(ObjectId::as_str))
1601 .execute(&self.pool)
1602 .await
1603 .map_err(backend)?;
1604
1605 Ok(())
1606 }
1607
1608 async fn list_comments(
1609 &self,
1610 pull_request_id: &PullRequestId,
1611 ) -> RepositoryResult<Vec<PullRequestComment>> {
1612 // `rowid` breaks a tie, which is insertion order — two comments posted in the
1613 // same second read in the order they were written. The id would not do: it is a
1614 // random UUID, so a conversation would occasionally read backwards.
1615 let rows = sqlx::query(
1616 "select * from pull_request_comments where pull_request_id = ?
1617 order by created_at asc, rowid asc",
1618 )
1619 .bind(pull_request_id.as_str())
1620 .fetch_all(&self.pool)
1621 .await
1622 .map_err(backend)?;
1623
1624 Ok(rows.iter().map(Self::hydrate_comment).collect())
1625 }
1626
1627 async fn add_comment(&self, comment: &PullRequestComment) -> RepositoryResult<()> {
1628 sqlx::query(
1629 "insert into pull_request_comments
1630 (id, pull_request_id, author_id, body, created_at)
1631 values (?, ?, ?, ?, ?)",
1632 )
1633 .bind(comment.id.as_str())
1634 .bind(comment.pull_request_id.as_str())
1635 .bind(comment.author_id.as_str())
1636 .bind(&comment.body)
1637 .bind(to_unix(comment.created_at))
1638 .execute(&self.pool)
1639 .await
1640 .map_err(backend)?;
1641
1642 Ok(())
1643 }
1644}
1645
1646#[cfg(test)]
1647mod tests {
1648 use super::*;
1649
1650 fn at(seconds: u64) -> SystemTime {
1651 SystemTime::UNIX_EPOCH + Duration::from_secs(seconds)
1652 }
1653 use crate::{
1654 application::{OwnerSpec, claim_instance, port::PasswordHasher},
1655 domain::{PrivateTargets, SetupToken, TokenLifetime, TokenSecret},
1656 infrastructure::{database::test_support::test_pool, password::StubHasher},
1657 };
1658
1659 struct Repos {
1660 users: SqliteUserRepo,
1661 orgs: SqliteOrgRepo,
1662 memberships: SqliteMembershipRepo,
1663 }
1664
1665 async fn repos() -> Repos {
1666 let pool = test_pool().await;
1667 Repos {
1668 users: SqliteUserRepo::new(pool.clone()),
1669 orgs: SqliteOrgRepo::new(pool.clone()),
1670 memberships: SqliteMembershipRepo::new(pool),
1671 }
1672 }
1673
1674 async fn saved_org(repos: &Repos, name: &str) -> Organization {
1675 let org = Organization::new(OrgId::generate(), name, None).expect("valid org");
1676 repos.orgs.save(&org).await.expect("save org");
1677 org
1678 }
1679
1680 async fn saved_user(repos: &Repos, email: &str, org: &Organization) -> User {
1681 let user = User::new(
1682 UserId::generate(),
1683 Email::new(email).expect("valid email"),
1684 PasswordHash::from_trusted("$argon2id$test"),
1685 org.id.clone(),
1686 );
1687 repos.users.save(&user).await.expect("save user");
1688 user
1689 }
1690
1691 #[tokio::test]
1692 async fn a_saved_user_round_trips() {
1693 let repos = repos().await;
1694 let org = saved_org(&repos, "james").await;
1695 let user = saved_user(&repos, "dev@example.com", &org).await;
1696
1697 let found = repos
1698 .users
1699 .find_by_id(&user.id)
1700 .await
1701 .expect("lookup")
1702 .expect("user should exist");
1703
1704 assert_eq!(found, user);
1705 }
1706
1707 #[tokio::test]
1708 async fn users_are_found_by_email_case_insensitively() {
1709 let repos = repos().await;
1710 let org = saved_org(&repos, "james").await;
1711 saved_user(&repos, "dev@example.com", &org).await;
1712
1713 // Email lowercases on construction, but a row written before that rule would
1714 // still need finding.
1715 let found = repos
1716 .users
1717 .find_by_email(&Email::from_trusted("DEV@EXAMPLE.COM"))
1718 .await
1719 .expect("lookup");
1720
1721 assert!(found.is_some(), "collate nocase should make this match");
1722 }
1723
1724 #[tokio::test]
1725 async fn an_org_round_trips_with_its_display_name() {
1726 let repos = repos().await;
1727 let org = Organization::new(OrgId::generate(), "acme", Some("Acme".to_owned()))
1728 .expect("valid org");
1729 repos.orgs.save(&org).await.expect("save");
1730
1731 let found = repos
1732 .orgs
1733 .find_by_name(&org.name)
1734 .await
1735 .expect("lookup")
1736 .expect("org should exist");
1737
1738 assert_eq!(found, org);
1739 assert_eq!(found.label(), "Acme");
1740 }
1741
1742 #[tokio::test]
1743 async fn a_missing_org_is_none_not_an_error() {
1744 let repos = repos().await;
1745
1746 let found = repos
1747 .orgs
1748 .find_by_name(&OrgName::new("nobody").unwrap())
1749 .await
1750 .expect("lookup");
1751
1752 assert_eq!(found, None);
1753 }
1754
1755 #[tokio::test]
1756 async fn a_membership_round_trips_with_its_role() {
1757 let repos = repos().await;
1758 let org = saved_org(&repos, "james").await;
1759 let user = saved_user(&repos, "dev@example.com", &org).await;
1760 let membership = Membership::new(
1761 MembershipId::generate(),
1762 org.id.clone(),
1763 user.id.clone(),
1764 Role::Owner,
1765 );
1766 repos.memberships.save(&membership).await.expect("save");
1767
1768 let found = repos
1769 .memberships
1770 .find(&org.id, &user.id)
1771 .await
1772 .expect("lookup")
1773 .expect("membership should exist");
1774
1775 assert_eq!(found, membership);
1776 assert!(found.can_write());
1777 }
1778
1779 #[tokio::test]
1780 async fn an_unreadable_role_surfaces_rather_than_downgrading_access() {
1781 let repos = repos().await;
1782 let pool = test_pool().await;
1783 let memberships = SqliteMembershipRepo::new(pool.clone());
1784 let org = Organization::new(OrgId::generate(), "james", None).expect("valid org");
1785 SqliteOrgRepo::new(pool.clone())
1786 .save(&org)
1787 .await
1788 .expect("save org");
1789 let user = User::new(
1790 UserId::generate(),
1791 Email::new("dev@example.com").expect("valid email"),
1792 PasswordHash::from_trusted("$argon2id$test"),
1793 org.id.clone(),
1794 );
1795 SqliteUserRepo::new(pool.clone())
1796 .save(&user)
1797 .await
1798 .expect("save user");
1799
1800 sqlx::query("insert into memberships (id, org_id, user_id, role) values (?, ?, ?, 'wat')")
1801 .bind(MembershipId::generate().as_str())
1802 .bind(org.id.as_str())
1803 .bind(user.id.as_str())
1804 .execute(&pool)
1805 .await
1806 .expect("insert");
1807
1808 let result = memberships.find(&org.id, &user.id).await;
1809
1810 assert!(
1811 result.is_err(),
1812 "a role we can't parse must not read as no membership"
1813 );
1814 drop(repos);
1815 }
1816
1817 #[tokio::test]
1818 async fn saving_a_user_before_its_org_is_refused() {
1819 let repos = repos().await;
1820 let orphan = User::new(
1821 UserId::generate(),
1822 Email::new("dev@example.com").expect("valid email"),
1823 PasswordHash::from_trusted("$argon2id$test"),
1824 OrgId::generate(),
1825 );
1826
1827 let result = repos.users.save(&orphan).await;
1828
1829 assert!(
1830 result.is_err(),
1831 "the foreign key should reject a user whose org doesn't exist"
1832 );
1833 }
1834
1835 #[tokio::test]
1836 async fn a_duplicate_handle_is_refused() {
1837 let repos = repos().await;
1838 saved_org(&repos, "james").await;
1839
1840 let clash = Organization::new(OrgId::generate(), "james", None).expect("valid org");
1841 let result = repos.orgs.save(&clash).await;
1842
1843 assert!(result.is_err(), "orgs.name is unique");
1844 }
1845
1846 #[tokio::test]
1847 async fn a_differently_cased_handle_is_also_refused() {
1848 let repos = repos().await;
1849 saved_org(&repos, "james").await;
1850
1851 // OrgName lowercases, so this can only arrive via from_trusted -- but the
1852 // constraint is what we're testing, not the value object.
1853 let clash = Organization::from_trusted(
1854 OrgId::generate(),
1855 OrgName::from_trusted("JAMES"),
1856 None,
1857 None,
1858 );
1859 let result = repos.orgs.save(&clash).await;
1860
1861 assert!(result.is_err(), "collate nocase should catch this");
1862 }
1863
1864 /// The claim use case checks `is_claimed` and then writes, which is TOCTOU. This
1865 /// asserts the database is what actually stops a second owner being created.
1866 #[tokio::test]
1867 async fn a_second_claim_is_stopped_by_the_database_not_the_check() {
1868 let repos = repos().await;
1869 let token = SetupToken::generate();
1870 let hasher = StubHasher::new();
1871 let spec = OwnerSpec {
1872 handle: "james".to_owned(),
1873 email: "dev@example.com".to_owned(),
1874 password: "hunter2".to_owned(),
1875 };
1876
1877 claim_instance(
1878 token.reveal(),
1879 &token,
1880 &spec,
1881 &repos.users,
1882 &repos.orgs,
1883 &repos.memberships,
1884 &hasher,
1885 )
1886 .await
1887 .expect("first claim");
1888
1889 // Simulate the race: the second claimant passed is_claimed before the first
1890 // committed, so it proceeds straight to the writes.
1891 let intruder_org = Organization::new(OrgId::generate(), "james", None).expect("valid org");
1892 let result = repos.orgs.save(&intruder_org).await;
1893
1894 assert!(
1895 result.is_err(),
1896 "unique(orgs.name) is what actually serialises concurrent claims"
1897 );
1898
1899 let intruder_user = User::new(
1900 UserId::generate(),
1901 Email::new("dev@example.com").expect("valid email"),
1902 hasher.hash("letmein").expect("hash"),
1903 OrgId::generate(),
1904 );
1905 assert!(
1906 repos.users.save(&intruder_user).await.is_err(),
1907 "unique(users.email) closes the other half"
1908 );
1909 }
1910 async fn org_with(orgs: &SqliteOrgRepo, name: &str) -> Organization {
1911 let org = Organization::new(OrgId::generate(), name, None).expect("valid org");
1912 orgs.save(&org).await.expect("save org");
1913 org
1914 }
1915
1916 async fn saved_repo(
1917 repos: &SqliteRepoRepo,
1918 org: &Organization,
1919 name: &str,
1920 visibility: Visibility,
1921 ) -> Repository {
1922 let repo = Repository::new(
1923 RepoId::generate(),
1924 org.id.clone(),
1925 name,
1926 None,
1927 visibility,
1928 at(1_000),
1929 )
1930 .expect("valid repo");
1931 repos.save(&repo).await.expect("save repo");
1932 repo
1933 }
1934
1935 #[tokio::test]
1936 async fn a_repository_round_trips() {
1937 let pool = test_pool().await;
1938 let orgs = SqliteOrgRepo::new(pool.clone());
1939 let repos = SqliteRepoRepo::new(pool);
1940 let org = org_with(&orgs, "acme").await;
1941
1942 let repo = Repository::new(
1943 RepoId::generate(),
1944 org.id.clone(),
1945 "steid",
1946 Some("A gitforge.".to_owned()),
1947 Visibility::Private,
1948 at(1_000),
1949 )
1950 .expect("valid repo");
1951 repos.save(&repo).await.expect("save");
1952
1953 let found = repos
1954 .find_by_id(&repo.id)
1955 .await
1956 .expect("lookup")
1957 .expect("should exist");
1958
1959 assert_eq!(found, repo);
1960 assert_eq!(found.visibility, Visibility::Private);
1961 assert_eq!(found.description.as_deref(), Some("A gitforge."));
1962 }
1963
1964 #[tokio::test]
1965 async fn lookup_by_name_is_case_insensitive() {
1966 let pool = test_pool().await;
1967 let orgs = SqliteOrgRepo::new(pool.clone());
1968 let repos = SqliteRepoRepo::new(pool);
1969 let org = org_with(&orgs, "acme").await;
1970 saved_repo(&repos, &org, "steid", Visibility::Public).await;
1971
1972 let found = repos
1973 .find_by_org_and_name(&org.id, &RepoName::from_trusted("STEID"))
1974 .await
1975 .expect("lookup");
1976
1977 assert!(found.is_some(), "collate nocase should make this match");
1978 }
1979
1980 #[tokio::test]
1981 async fn one_owner_cannot_have_two_repositories_with_the_same_name() {
1982 let pool = test_pool().await;
1983 let orgs = SqliteOrgRepo::new(pool.clone());
1984 let repos = SqliteRepoRepo::new(pool);
1985 let org = org_with(&orgs, "acme").await;
1986 saved_repo(&repos, &org, "steid", Visibility::Public).await;
1987
1988 let clash = Repository::new(
1989 RepoId::generate(),
1990 org.id.clone(),
1991 "steid",
1992 None,
1993 Visibility::Public,
1994 at(1_000),
1995 )
1996 .expect("valid repo");
1997
1998 assert!(repos.save(&clash).await.is_err(), "unique (org_id, name)");
1999 }
2000
2001 #[tokio::test]
2002 async fn two_owners_may_each_have_a_repository_of_the_same_name() {
2003 let pool = test_pool().await;
2004 let orgs = SqliteOrgRepo::new(pool.clone());
2005 let repos = SqliteRepoRepo::new(pool);
2006 let first = org_with(&orgs, "acme").await;
2007 let second = org_with(&orgs, "globex").await;
2008
2009 saved_repo(&repos, &first, "steid", Visibility::Public).await;
2010 saved_repo(&repos, &second, "steid", Visibility::Public).await;
2011
2012 // The constraint is a pair. On `name` alone, repository names would be globally
2013 // unique across the whole installation.
2014 assert_eq!(repos.list_by_org(&first.id).await.expect("list").len(), 1);
2015 assert_eq!(repos.list_by_org(&second.id).await.expect("list").len(), 1);
2016 }
2017
2018 #[tokio::test]
2019 async fn a_repository_owned_by_a_missing_org_is_refused() {
2020 let pool = test_pool().await;
2021 let repos = SqliteRepoRepo::new(pool);
2022 let orphan = Repository::new(
2023 RepoId::generate(),
2024 OrgId::generate(),
2025 "steid",
2026 None,
2027 Visibility::Public,
2028 at(1_000),
2029 )
2030 .expect("valid repo");
2031
2032 assert!(repos.save(&orphan).await.is_err(), "foreign key");
2033 }
2034
2035 #[tokio::test]
2036 async fn repositories_list_newest_first_breaking_ties_by_name() {
2037 // The order the profile renders, and the same order `InMemoryRepoRepo` produces
2038 // — the two are asserted against the same expectation on purpose.
2039 let pool = test_pool().await;
2040 let orgs = SqliteOrgRepo::new(pool.clone());
2041 let repos = SqliteRepoRepo::new(pool);
2042 let org = org_with(&orgs, "acme").await;
2043
2044 for (name, seconds) in [
2045 ("alpha", 3_000),
2046 ("older", 1_000),
2047 ("newer", 2_000),
2048 ("also-older", 1_000),
2049 ] {
2050 let mut repo = saved_repo(&repos, &org, name, Visibility::Public).await;
2051 repo.updated_at = at(seconds);
2052 repos.save(&repo).await.expect("restamp");
2053 }
2054
2055 let listed = repos.list_by_org(&org.id).await.expect("list");
2056
2057 assert_eq!(
2058 listed.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
2059 vec!["alpha", "newer", "also-older", "older"]
2060 );
2061 }
2062
2063 #[tokio::test]
2064 async fn touching_moves_a_repository_to_the_supplied_time() {
2065 let pool = test_pool().await;
2066 let orgs = SqliteOrgRepo::new(pool.clone());
2067 let repos = SqliteRepoRepo::new(pool);
2068 let org = org_with(&orgs, "acme").await;
2069 let repo = saved_repo(&repos, &org, "steid", Visibility::Public).await;
2070
2071 repos.touch(&repo.id, at(5_000)).await.expect("touch");
2072
2073 let found = repos
2074 .find_by_id(&repo.id)
2075 .await
2076 .expect("lookup")
2077 .expect("still there");
2078 assert_eq!(found.updated_at, at(5_000));
2079 assert_eq!(found.name, repo.name, "only the timestamp should move");
2080 }
2081
2082 #[tokio::test]
2083 async fn touching_a_repository_that_is_gone_succeeds() {
2084 let pool = test_pool().await;
2085 let repos = SqliteRepoRepo::new(pool);
2086
2087 assert!(repos.touch(&RepoId::generate(), at(5_000)).await.is_ok());
2088 }
2089
2090 #[tokio::test]
2091 async fn pinning_round_trips_through_an_integer_column() {
2092 // SQLite has no boolean; a column read as anything but 0/1 would silently unpin.
2093 let pool = test_pool().await;
2094 let orgs = SqliteOrgRepo::new(pool.clone());
2095 let repos = SqliteRepoRepo::new(pool);
2096 let org = org_with(&orgs, "acme").await;
2097 let mut repo = saved_repo(&repos, &org, "steid", Visibility::Public).await;
2098
2099 assert!(!repo.pinned, "a repository is not pinned by default");
2100
2101 repo.pinned = true;
2102 repos.save(&repo).await.expect("save");
2103
2104 assert!(
2105 repos
2106 .find_by_id(&repo.id)
2107 .await
2108 .expect("lookup")
2109 .expect("still there")
2110 .pinned
2111 );
2112 }
2113
2114 /// The column migrations, applied to a row that predates all of them.
2115 ///
2116 /// The dev database and any deployed instance already hold repositories, and this is
2117 /// the only chance to check what they look like afterwards: the table is created
2118 /// with the new columns from scratch everywhere else. Every migration that adds a
2119 /// column to `repositories` belongs in the list below.
2120 #[tokio::test]
2121 async fn the_repository_migrations_leave_existing_rows_looking_current() {
2122 let pool = SqlitePool::connect("sqlite::memory:")
2123 .await
2124 .expect("in-memory database should open");
2125
2126 // The table as it stood before this migration, with a repository already in it.
2127 sqlx::query(
2128 "create table repositories (
2129 id text primary key,
2130 org_id text not null,
2131 name text not null collate nocase,
2132 description text,
2133 visibility text not null,
2134 unique (org_id, name)
2135 )",
2136 )
2137 .execute(&pool)
2138 .await
2139 .expect("old schema");
2140 sqlx::query(
2141 "insert into repositories (id, org_id, name, visibility)
2142 values ('r1', 'o1', 'steid', 'public')",
2143 )
2144 .execute(&pool)
2145 .await
2146 .expect("an existing repository");
2147
2148 for migration in [
2149 include_str!("../../../migrations/20260829090000_add_repository_recency.sql"),
2150 include_str!("../../../migrations/20260906120100_add_repository_import.sql"),
2151 include_str!("../../../migrations/20260906120400_add_repository_archived.sql"),
2152 ] {
2153 for statement in migration
2154 .split(';')
2155 .filter(|statement| !statement.trim().is_empty())
2156 {
2157 sqlx::query(statement)
2158 .execute(&pool)
2159 .await
2160 .expect("the migration should apply");
2161 }
2162 }
2163
2164 let repo = SqliteRepoRepo::new(pool)
2165 .find_by_id(&RepoId::from_trusted("r1"))
2166 .await
2167 .expect("lookup")
2168 .expect("the row survives");
2169
2170 assert!(
2171 !repo.pinned,
2172 "nothing becomes the lead without being chosen"
2173 );
2174 assert!(
2175 !repo.archived,
2176 "nothing becomes archived by migrating a database"
2177 );
2178
2179 // Stamped with the migration's own clock, not left at the epoch: an existing
2180 // repository must not read "updated 56 years ago" on the page this column exists
2181 // to order.
2182 let age = SystemTime::now()
2183 .duration_since(repo.updated_at)
2184 .expect("stamped in the past");
2185 assert!(
2186 age < Duration::from_secs(60),
2187 "expected a just-migrated timestamp, got one {age:?} old"
2188 );
2189
2190 // The import migration's columns are nullable and default to null, so every
2191 // repository that existed before importing did stays an ordinary repository.
2192 assert_eq!(repo.import_state, None);
2193 assert_eq!(repo.import_source, None);
2194 assert!(!repo.is_importing());
2195 }
2196
2197 /// The boot sweep, on a table holding one of each kind of row.
2198 #[tokio::test]
2199 async fn the_boot_sweep_fails_only_the_repositories_still_importing() {
2200 let pool = test_pool().await;
2201 let orgs = SqliteOrgRepo::new(pool.clone());
2202 let repos = SqliteRepoRepo::new(pool.clone());
2203 let org = org_with(&orgs, "acme").await;
2204
2205 let named = |name: &str| {
2206 Repository::new(
2207 RepoId::generate(),
2208 org.id.clone(),
2209 name,
2210 None,
2211 Visibility::Public,
2212 at(1_000),
2213 )
2214 .expect("valid repo")
2215 };
2216
2217 let mut ordinary = named("ordinary");
2218 let mut running = named("running");
2219 let mut done = named("done");
2220
2221 running.start_import(ImportSource::new("https://example.com/a.git").expect("valid"));
2222 done.start_import(ImportSource::new("https://example.com/b.git").expect("valid"));
2223 done.finish_import();
2224
2225 for repo in [&ordinary, &running, &done] {
2226 repos.save(repo).await.expect("save");
2227 }
2228
2229 let swept = repos
2230 .fail_interrupted_imports("interrupted by a restart")
2231 .await
2232 .expect("sweep");
2233
2234 assert_eq!(swept, 1, "only the running import is interrupted");
2235
2236 for repo in [&mut ordinary, &mut running, &mut done] {
2237 *repo = repos
2238 .find_by_id(&repo.id)
2239 .await
2240 .expect("lookup")
2241 .expect("still there");
2242 }
2243
2244 assert_eq!(ordinary.import_state, None);
2245 assert_eq!(done.import_state, None);
2246 assert_eq!(running.import_state, Some(ImportState::Failed));
2247 assert_eq!(
2248 running.import_error.as_deref(),
2249 Some("interrupted by a restart")
2250 );
2251 // The source survives the sweep: it is what a retry needs.
2252 assert_eq!(
2253 running.import_source.as_ref().map(ImportSource::as_str),
2254 Some("https://example.com/a.git")
2255 );
2256 }
2257
2258 /// An unreadable import state is a fault for the same reason an unreadable
2259 /// visibility is: both defaults are wrong in a way nobody would notice.
2260 #[tokio::test]
2261 async fn an_unreadable_import_state_surfaces_rather_than_defaulting() {
2262 let pool = test_pool().await;
2263 let orgs = SqliteOrgRepo::new(pool.clone());
2264 let repos = SqliteRepoRepo::new(pool.clone());
2265 let org = org_with(&orgs, "acme").await;
2266
2267 sqlx::query(
2268 "insert into repositories (id, org_id, name, visibility, updated_at, pinned, import_state)
2269 values ('r1', ?, 'half', 'public', 0, 0, 'halfway')",
2270 )
2271 .bind(org.id.as_str())
2272 .execute(&pool)
2273 .await
2274 .expect("a row written behind the repository");
2275
2276 assert!(repos.find_by_id(&RepoId::from_trusted("r1")).await.is_err());
2277 }
2278
2279 #[tokio::test]
2280 async fn an_unreadable_visibility_surfaces_rather_than_defaulting() {
2281 let pool = test_pool().await;
2282 let orgs = SqliteOrgRepo::new(pool.clone());
2283 let repos = SqliteRepoRepo::new(pool.clone());
2284 let org = org_with(&orgs, "acme").await;
2285
2286 sqlx::query(
2287 "insert into repositories (id, org_id, name, visibility)
2288 values ('r1', ?, 'secret', 'internal')",
2289 )
2290 .bind(org.id.as_str())
2291 .execute(&pool)
2292 .await
2293 .expect("insert");
2294
2295 assert!(
2296 repos.find_by_id(&RepoId::from_trusted("r1")).await.is_err(),
2297 "a visibility we cannot parse must not become a guess"
2298 );
2299 }
2300
2301 #[tokio::test]
2302 async fn listing_returns_only_that_org_ordered_by_name() {
2303 let pool = test_pool().await;
2304 let orgs = SqliteOrgRepo::new(pool.clone());
2305 let repos = SqliteRepoRepo::new(pool);
2306 let mine = org_with(&orgs, "acme").await;
2307 let theirs = org_with(&orgs, "globex").await;
2308
2309 for name in ["zebra", "alpha", "middle"] {
2310 saved_repo(&repos, &mine, name, Visibility::Public).await;
2311 }
2312 saved_repo(&repos, &theirs, "not-mine", Visibility::Public).await;
2313
2314 let listed = repos.list_by_org(&mine.id).await.expect("list");
2315
2316 let names: Vec<&str> = listed.iter().map(|repo| repo.name.as_str()).collect();
2317 assert_eq!(names, vec!["alpha", "middle", "zebra"]);
2318 }
2319
2320 #[tokio::test]
2321 async fn listing_includes_private_repositories() {
2322 let pool = test_pool().await;
2323 let orgs = SqliteOrgRepo::new(pool.clone());
2324 let repos = SqliteRepoRepo::new(pool);
2325 let org = org_with(&orgs, "acme").await;
2326 saved_repo(&repos, &org, "secret", Visibility::Private).await;
2327
2328 // The port returns everything; filtering by visibility is the use case's job, so
2329 // the page and /api cannot end up applying different rules.
2330 assert_eq!(repos.list_by_org(&org.id).await.expect("list").len(), 1);
2331 }
2332
2333 #[tokio::test]
2334 async fn a_missing_repository_is_none_not_an_error() {
2335 let pool = test_pool().await;
2336 let repos = SqliteRepoRepo::new(pool);
2337
2338 let found = repos
2339 .find_by_id(&RepoId::generate())
2340 .await
2341 .expect("lookup should not error");
2342
2343 assert_eq!(found, None);
2344 }
2345
2346 #[tokio::test]
2347 async fn a_deleted_repository_is_gone_and_frees_its_name() {
2348 let pool = test_pool().await;
2349 let orgs = SqliteOrgRepo::new(pool.clone());
2350 let repos = SqliteRepoRepo::new(pool);
2351 let org = org_with(&orgs, "acme").await;
2352 let repo = saved_repo(&repos, &org, "steid", Visibility::Public).await;
2353
2354 repos.delete(&repo.id).await.expect("delete");
2355
2356 assert_eq!(repos.find_by_id(&repo.id).await.expect("lookup"), None);
2357 // The unique (org_id, name) pair is what would fail if the row lingered.
2358 saved_repo(&repos, &org, "steid", Visibility::Private).await;
2359 }
2360
2361 #[tokio::test]
2362 async fn deleting_a_repository_that_is_not_there_succeeds() {
2363 // Idempotent, matching the fake: a second click must not become an error.
2364 let pool = test_pool().await;
2365 let repos = SqliteRepoRepo::new(pool);
2366
2367 assert!(repos.delete(&RepoId::generate()).await.is_ok());
2368 }
2369
2370 #[tokio::test]
2371 async fn deleting_one_repository_leaves_the_others() {
2372 let pool = test_pool().await;
2373 let orgs = SqliteOrgRepo::new(pool.clone());
2374 let repos = SqliteRepoRepo::new(pool);
2375 let org = org_with(&orgs, "acme").await;
2376 let doomed = saved_repo(&repos, &org, "alpha", Visibility::Public).await;
2377 saved_repo(&repos, &org, "zebra", Visibility::Public).await;
2378
2379 repos.delete(&doomed.id).await.expect("delete");
2380
2381 let listed = repos.list_by_org(&org.id).await.expect("list");
2382 assert_eq!(
2383 listed.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
2384 vec!["zebra"]
2385 );
2386 }
2387
2388 // --- SqliteTokenRepo ---------------------------------------------------------
2389
2390 /// A pool plus a user to hang tokens off, since the foreign key runs that way.
2391 async fn token_fixture() -> (SqliteTokenRepo, User, User) {
2392 let pool = test_pool().await;
2393 let repos = Repos {
2394 users: SqliteUserRepo::new(pool.clone()),
2395 orgs: SqliteOrgRepo::new(pool.clone()),
2396 memberships: SqliteMembershipRepo::new(pool.clone()),
2397 };
2398
2399 let org = saved_org(&repos, "acme").await;
2400 let owner = saved_user(&repos, "owner@example.com", &org).await;
2401 let other = saved_user(&repos, "other@example.com", &org).await;
2402
2403 (SqliteTokenRepo::new(pool), owner, other)
2404 }
2405
2406 fn issued(user: &User, name: &str, at: u64) -> (PersonalAccessToken, TokenSecret) {
2407 let secret = TokenSecret::generate();
2408 let token = PersonalAccessToken::new(
2409 TokenId::generate(),
2410 user.id.clone(),
2411 name,
2412 &secret,
2413 SystemTime::UNIX_EPOCH + Duration::from_secs(at),
2414 TokenLifetime::default(),
2415 )
2416 .expect("valid token");
2417
2418 (token, secret)
2419 }
2420
2421 #[tokio::test]
2422 async fn a_token_round_trips_through_its_hash() {
2423 let (tokens, owner, _) = token_fixture().await;
2424 let (token, secret) = issued(&owner, "laptop", 1_000);
2425 tokens.save(&token).await.expect("save");
2426
2427 let found = tokens
2428 .find_by_hash(&secret.hash())
2429 .await
2430 .expect("lookup")
2431 .expect("should be found");
2432
2433 assert_eq!(found, token);
2434 assert_eq!(found.name, "laptop");
2435 assert_eq!(found.prefix, secret.display_prefix());
2436 }
2437
2438 #[tokio::test]
2439 async fn an_unknown_hash_finds_nothing() {
2440 let (tokens, owner, _) = token_fixture().await;
2441 let (token, _) = issued(&owner, "laptop", 1_000);
2442 tokens.save(&token).await.expect("save");
2443
2444 let found = tokens
2445 .find_by_hash(&TokenSecret::generate().hash())
2446 .await
2447 .expect("lookup");
2448
2449 assert!(found.is_none());
2450 }
2451
2452 #[tokio::test]
2453 async fn tokens_are_listed_newest_first_and_only_the_users_own() {
2454 let (tokens, owner, other) = token_fixture().await;
2455
2456 for (user, name, at) in [
2457 (&owner, "old", 1_000),
2458 (&owner, "new", 3_000),
2459 (&owner, "middle", 2_000),
2460 (&other, "theirs", 4_000),
2461 ] {
2462 let (token, _) = issued(user, name, at);
2463 tokens.save(&token).await.expect("save");
2464 }
2465
2466 let listed = tokens.list_by_user(&owner.id).await.expect("list");
2467
2468 assert_eq!(
2469 listed
2470 .iter()
2471 .map(|token| token.name.as_str())
2472 .collect::<Vec<_>>(),
2473 vec!["new", "middle", "old"]
2474 );
2475 }
2476
2477 #[tokio::test]
2478 async fn deleting_a_token_stops_it_authenticating() {
2479 // Revocation is a delete, so the credential is gone rather than flagged.
2480 let (tokens, owner, _) = token_fixture().await;
2481 let (token, secret) = issued(&owner, "laptop", 1_000);
2482 tokens.save(&token).await.expect("save");
2483
2484 tokens.delete(&token.id).await.expect("delete");
2485
2486 assert!(
2487 tokens
2488 .find_by_hash(&secret.hash())
2489 .await
2490 .expect("lookup")
2491 .is_none()
2492 );
2493 }
2494
2495 #[tokio::test]
2496 async fn deleting_a_token_that_is_not_there_succeeds() {
2497 let (tokens, _, _) = token_fixture().await;
2498
2499 tokens
2500 .delete(&TokenId::generate())
2501 .await
2502 .expect("deleting nothing should not fail");
2503 }
2504
2505 #[tokio::test]
2506 async fn a_second_token_with_the_same_hash_is_refused() {
2507 // The unique constraint. Two rows answering one credential would make which
2508 // user a token authenticates depend on row order.
2509 let (tokens, owner, other) = token_fixture().await;
2510 let (first, secret) = issued(&owner, "laptop", 1_000);
2511 tokens.save(&first).await.expect("save");
2512
2513 let clash = PersonalAccessToken::new(
2514 TokenId::generate(),
2515 other.id.clone(),
2516 "clash",
2517 &secret,
2518 SystemTime::UNIX_EPOCH,
2519 TokenLifetime::default(),
2520 )
2521 .expect("valid token");
2522
2523 assert!(tokens.save(&clash).await.is_err());
2524 }
2525
2526 #[tokio::test]
2527 async fn a_token_belonging_to_no_user_is_refused() {
2528 // The foreign key. Without `foreign_keys(true)` per connection SQLite ignores it.
2529 let (tokens, _, _) = token_fixture().await;
2530 let secret = TokenSecret::generate();
2531 let orphan = PersonalAccessToken::new(
2532 TokenId::generate(),
2533 UserId::generate(),
2534 "orphan",
2535 &secret,
2536 SystemTime::UNIX_EPOCH,
2537 TokenLifetime::default(),
2538 )
2539 .expect("valid token");
2540
2541 assert!(tokens.save(&orphan).await.is_err());
2542 }
2543
2544 // --- sole_user ----------------------------------------------------------------
2545
2546 #[tokio::test]
2547 async fn there_is_no_sole_user_before_the_instance_is_claimed() {
2548 let repos = repos().await;
2549
2550 assert!(repos.users.sole_user().await.expect("lookup").is_none());
2551 }
2552
2553 #[tokio::test]
2554 async fn the_only_user_is_the_sole_user() {
2555 let repos = repos().await;
2556 let org = saved_org(&repos, "acme").await;
2557 let user = saved_user(&repos, "owner@example.com", &org).await;
2558
2559 let found = repos
2560 .users
2561 .sole_user()
2562 .await
2563 .expect("lookup")
2564 .expect("one user");
2565
2566 assert_eq!(found.id, user.id);
2567 }
2568
2569 #[tokio::test]
2570 async fn a_second_user_makes_the_owner_undefined_rather_than_arbitrary() {
2571 // The root redirects an anonymous visitor to "the owner". With two users that
2572 // question has no answer, and picking whichever row came back first would send
2573 // strangers to a person chosen by storage order.
2574 let repos = repos().await;
2575 let first = saved_org(&repos, "acme").await;
2576 let second = saved_org(&repos, "other").await;
2577 saved_user(&repos, "one@example.com", &first).await;
2578 saved_user(&repos, "two@example.com", &second).await;
2579
2580 assert!(repos.users.sole_user().await.expect("lookup").is_none());
2581 }
2582
2583 // --- SqliteIssueRepo ------------------------------------------------------------
2584
2585 struct IssueFixture {
2586 issues: SqliteIssueRepo,
2587 repo: Repository,
2588 other: Repository,
2589 author: User,
2590 }
2591
2592 /// A pool with two repositories and a user, since every foreign key runs that way.
2593 async fn issue_fixture() -> IssueFixture {
2594 let pool = test_pool().await;
2595 let repos = Repos {
2596 users: SqliteUserRepo::new(pool.clone()),
2597 orgs: SqliteOrgRepo::new(pool.clone()),
2598 memberships: SqliteMembershipRepo::new(pool.clone()),
2599 };
2600 let repo_repo = SqliteRepoRepo::new(pool.clone());
2601
2602 let org = saved_org(&repos, "acme").await;
2603 let author = saved_user(&repos, "owner@example.com", &org).await;
2604
2605 IssueFixture {
2606 issues: SqliteIssueRepo::new(pool),
2607 repo: saved_repo(&repo_repo, &org, "steid", Visibility::Public).await,
2608 other: saved_repo(&repo_repo, &org, "other", Visibility::Public).await,
2609 author,
2610 }
2611 }
2612
2613 fn issue_of(f: &IssueFixture, repo: &Repository, number: u64, title: &str) -> Issue {
2614 Issue::new(
2615 IssueId::generate(),
2616 repo.id.clone(),
2617 IssueNumber::from_trusted(number),
2618 title,
2619 "body",
2620 f.author.id.clone(),
2621 at(1_000),
2622 )
2623 .expect("valid issue")
2624 }
2625
2626 #[tokio::test]
2627 async fn numbering_starts_at_one_and_never_repeats() {
2628 let f = issue_fixture().await;
2629
2630 let first = f.issues.next_number(&f.repo.id).await.expect("allocate");
2631 let second = f.issues.next_number(&f.repo.id).await.expect("allocate");
2632 let third = f.issues.next_number(&f.repo.id).await.expect("allocate");
2633
2634 assert_eq!(
2635 [first.get(), second.get(), third.get()],
2636 [1, 2, 3],
2637 "the sequence starts at 1 and steps by one"
2638 );
2639 }
2640
2641 #[tokio::test]
2642 async fn each_repository_has_its_own_sequence() {
2643 // The number is part of a URL, so `#1` on two repositories has to be two things.
2644 let f = issue_fixture().await;
2645
2646 f.issues.next_number(&f.repo.id).await.expect("allocate");
2647 f.issues.next_number(&f.repo.id).await.expect("allocate");
2648
2649 assert_eq!(
2650 f.issues
2651 .next_number(&f.other.id)
2652 .await
2653 .expect("allocate")
2654 .get(),
2655 1
2656 );
2657 }
2658
2659 #[tokio::test]
2660 async fn an_issue_round_trips_with_every_field() {
2661 let f = issue_fixture().await;
2662 let mut issue = issue_of(&f, &f.repo, 1, "Blame is slow");
2663 issue.close(at(2_000));
2664 f.issues.save(&issue).await.expect("save");
2665
2666 let found = f
2667 .issues
2668 .find_by_number(&f.repo.id, IssueNumber::from_trusted(1))
2669 .await
2670 .expect("lookup")
2671 .expect("the issue is there");
2672
2673 assert_eq!(found, issue);
2674 }
2675
2676 #[tokio::test]
2677 async fn an_issue_is_found_only_under_its_own_repository() {
2678 let f = issue_fixture().await;
2679 f.issues
2680 .save(&issue_of(&f, &f.repo, 1, "Blame is slow"))
2681 .await
2682 .expect("save");
2683
2684 assert!(
2685 f.issues
2686 .find_by_number(&f.other.id, IssueNumber::from_trusted(1))
2687 .await
2688 .expect("lookup")
2689 .is_none()
2690 );
2691 }
2692
2693 #[tokio::test]
2694 async fn two_issues_cannot_share_a_number_on_one_repository() {
2695 // The constraint that makes the sequence load-bearing rather than decorative.
2696 let f = issue_fixture().await;
2697 f.issues
2698 .save(&issue_of(&f, &f.repo, 1, "first"))
2699 .await
2700 .expect("save");
2701
2702 assert!(
2703 f.issues
2704 .save(&issue_of(&f, &f.repo, 1, "second"))
2705 .await
2706 .is_err()
2707 );
2708 }
2709
2710 #[tokio::test]
2711 async fn saving_an_existing_issue_updates_it_rather_than_duplicating_it() {
2712 let f = issue_fixture().await;
2713 let mut issue = issue_of(&f, &f.repo, 1, "Blame is slow");
2714 f.issues.save(&issue).await.expect("save");
2715
2716 issue
2717 .edit("Blame is very slow", "more", at(3_000))
2718 .expect("edit");
2719 issue.close(at(4_000));
2720 f.issues.save(&issue).await.expect("update");
2721
2722 let found = f
2723 .issues
2724 .find_by_number(&f.repo.id, IssueNumber::from_trusted(1))
2725 .await
2726 .expect("lookup")
2727 .expect("still one issue");
2728
2729 assert_eq!(found.title, "Blame is very slow");
2730 assert_eq!(found.state, IssueState::Closed);
2731 assert_eq!(found.closed_at, Some(at(4_000)));
2732 }
2733
2734 #[tokio::test]
2735 async fn the_second_page_of_issues_starts_where_the_first_ended() {
2736 let f = issue_fixture().await;
2737
2738 for number in 1..=5 {
2739 f.issues
2740 .save(&issue_of(&f, &f.repo, number, &format!("issue {number}")))
2741 .await
2742 .expect("save");
2743 }
2744
2745 let first = f
2746 .issues
2747 .list_by_repo(&f.repo.id, IssueState::Open, 0, 2)
2748 .await
2749 .expect("list");
2750 let second = f
2751 .issues
2752 .list_by_repo(&f.repo.id, IssueState::Open, 2, 2)
2753 .await
2754 .expect("list");
2755
2756 assert_eq!(
2757 first.iter().map(|i| i.number.get()).collect::<Vec<_>>(),
2758 vec![5, 4]
2759 );
2760 assert_eq!(
2761 second.iter().map(|i| i.number.get()).collect::<Vec<_>>(),
2762 vec![3, 2]
2763 );
2764 assert!(
2765 f.issues
2766 .list_by_repo(&f.repo.id, IssueState::Open, 500, 2)
2767 .await
2768 .expect("list")
2769 .is_empty(),
2770 "an offset past the end is an empty page, not an error"
2771 );
2772 }
2773
2774 #[tokio::test]
2775 async fn a_listing_is_filtered_by_state_and_newest_first() {
2776 let f = issue_fixture().await;
2777 let mut second = issue_of(&f, &f.repo, 2, "issue 2");
2778 for issue in [
2779 issue_of(&f, &f.repo, 1, "issue 1"),
2780 second.clone(),
2781 issue_of(&f, &f.repo, 3, "issue 3"),
2782 ] {
2783 f.issues.save(&issue).await.expect("save");
2784 }
2785
2786 second.close(at(2_000));
2787 f.issues.save(&second).await.expect("close");
2788
2789 let open = f
2790 .issues
2791 .list_by_repo(&f.repo.id, IssueState::Open, 0, 50)
2792 .await
2793 .expect("list");
2794 let shut = f
2795 .issues
2796 .list_by_repo(&f.repo.id, IssueState::Closed, 0, 50)
2797 .await
2798 .expect("list");
2799
2800 assert_eq!(
2801 open.iter().map(|i| i.number.get()).collect::<Vec<_>>(),
2802 vec![3, 1]
2803 );
2804 assert_eq!(
2805 shut.iter().map(|i| i.number.get()).collect::<Vec<_>>(),
2806 vec![2]
2807 );
2808 }
2809
2810 #[tokio::test]
2811 async fn counts_cover_both_states_and_only_this_repository() {
2812 let f = issue_fixture().await;
2813 f.issues
2814 .save(&issue_of(&f, &f.repo, 1, "open one"))
2815 .await
2816 .expect("save");
2817 let mut closed = issue_of(&f, &f.repo, 2, "closed one");
2818 closed.close(at(2_000));
2819 f.issues.save(&closed).await.expect("save");
2820 f.issues
2821 .save(&issue_of(&f, &f.other, 1, "elsewhere"))
2822 .await
2823 .expect("save");
2824
2825 assert_eq!(
2826 f.issues.counts(&f.repo.id).await.expect("counts"),
2827 IssueCounts { open: 1, closed: 1 }
2828 );
2829 }
2830
2831 #[tokio::test]
2832 async fn comments_read_forwards_and_are_counted_per_issue() {
2833 let f = issue_fixture().await;
2834 let issue = issue_of(&f, &f.repo, 1, "Blame is slow");
2835 let quiet = issue_of(&f, &f.repo, 2, "Nobody replied");
2836 f.issues.save(&issue).await.expect("save");
2837 f.issues.save(&quiet).await.expect("save");
2838
2839 for (seconds, body) in [(3_000, "second"), (2_000, "first")] {
2840 f.issues
2841 .add_comment(
2842 &IssueComment::new(
2843 IssueCommentId::generate(),
2844 issue.id.clone(),
2845 f.author.id.clone(),
2846 body,
2847 at(seconds),
2848 )
2849 .expect("valid comment"),
2850 )
2851 .await
2852 .expect("comment");
2853 }
2854
2855 let comments = f.issues.list_comments(&issue.id).await.expect("list");
2856 assert_eq!(
2857 comments.iter().map(|c| c.body.as_str()).collect::<Vec<_>>(),
2858 vec!["first", "second"],
2859 "a conversation reads forwards"
2860 );
2861
2862 let mut counts = f.issues.comment_counts(&f.repo.id).await.expect("counts");
2863 counts.sort_by_key(|(id, _)| id.as_str().to_owned());
2864 let mut expected = vec![(issue.id.clone(), 2), (quiet.id.clone(), 0)];
2865 expected.sort_by_key(|(id, _)| id.as_str().to_owned());
2866
2867 assert_eq!(
2868 counts, expected,
2869 "an issue with no comments still gets a row"
2870 );
2871 }
2872
2873 #[tokio::test]
2874 async fn deleting_a_repository_takes_its_issues_and_their_comments() {
2875 // `on delete cascade`, which is the whole of a comment's lifecycle.
2876 let f = issue_fixture().await;
2877 let issue = issue_of(&f, &f.repo, 1, "Blame is slow");
2878 f.issues.save(&issue).await.expect("save");
2879 f.issues
2880 .add_comment(
2881 &IssueComment::new(
2882 IssueCommentId::generate(),
2883 issue.id.clone(),
2884 f.author.id.clone(),
2885 "looks fixed",
2886 at(2_000),
2887 )
2888 .expect("valid comment"),
2889 )
2890 .await
2891 .expect("comment");
2892
2893 SqliteRepoRepo::new(f.issues.pool.clone())
2894 .delete(&f.repo.id)
2895 .await
2896 .expect("delete");
2897
2898 assert!(
2899 f.issues
2900 .find_by_number(&f.repo.id, IssueNumber::from_trusted(1))
2901 .await
2902 .expect("lookup")
2903 .is_none()
2904 );
2905 assert!(
2906 f.issues
2907 .list_comments(&issue.id)
2908 .await
2909 .expect("list")
2910 .is_empty()
2911 );
2912 }
2913
2914 #[tokio::test]
2915 async fn an_issue_cannot_hang_off_a_repository_that_is_not_there() {
2916 let f = issue_fixture().await;
2917 let orphan = Issue::new(
2918 IssueId::generate(),
2919 RepoId::generate(),
2920 IssueNumber::from_trusted(1),
2921 "nowhere",
2922 "",
2923 f.author.id.clone(),
2924 at(1_000),
2925 )
2926 .expect("valid issue");
2927
2928 assert!(f.issues.save(&orphan).await.is_err());
2929 }
2930
2931 // --- push events, webhooks and their deliveries ---------------------------------
2932
2933 /// A repository with an owner, which is what every row below hangs off.
2934 async fn hooked_repo() -> (sqlx::SqlitePool, Repository, User) {
2935 let pool = test_pool().await;
2936 let orgs = SqliteOrgRepo::new(pool.clone());
2937 let users = SqliteUserRepo::new(pool.clone());
2938 let repos = SqliteRepoRepo::new(pool.clone());
2939
2940 let org = org_with(&orgs, "acme").await;
2941 let user = User::new(
2942 UserId::generate(),
2943 Email::new("dev@example.com").expect("valid email"),
2944 PasswordHash::from_trusted("$argon2id$test"),
2945 org.id.clone(),
2946 );
2947 users.save(&user).await.expect("save user");
2948
2949 let repo = saved_repo(&repos, &org, "steid", Visibility::Public).await;
2950
2951 (pool, repo, user)
2952 }
2953
2954 fn oid(prefix: &str) -> ObjectId {
2955 ObjectId::new(format!("{prefix:0>40}")).expect("valid id")
2956 }
2957
2958 #[tokio::test]
2959 async fn a_push_event_round_trips_with_its_pusher() {
2960 let (pool, repo, user) = hooked_repo().await;
2961 let events = SqlitePushEventRepo::new(pool);
2962
2963 let event = PushEvent::new(
2964 PushEventId::generate(),
2965 repo.id.clone(),
2966 RefName::from_trusted("refs/heads/main"),
2967 oid("a"),
2968 oid("b"),
2969 Some(user.id.clone()),
2970 at(2_000),
2971 )
2972 .expect("valid event");
2973 events.save(&event).await.expect("save");
2974
2975 assert_eq!(
2976 events.find(&event.id).await.expect("lookup"),
2977 Some(event.clone())
2978 );
2979 assert_eq!(
2980 events.list_by_repo(&repo.id, 10).await.expect("list"),
2981 vec![event]
2982 );
2983 }
2984
2985 #[tokio::test]
2986 async fn push_events_come_back_newest_first_and_capped() {
2987 let (pool, repo, user) = hooked_repo().await;
2988 let events = SqlitePushEventRepo::new(pool);
2989
2990 for (seconds, name) in [(1_000, "one"), (3_000, "three"), (2_000, "two")] {
2991 let event = PushEvent::new(
2992 PushEventId::generate(),
2993 repo.id.clone(),
2994 RefName::from_trusted(format!("refs/heads/{name}")),
2995 oid("a"),
2996 oid("b"),
2997 Some(user.id.clone()),
2998 at(seconds),
2999 )
3000 .expect("valid event");
3001 events.save(&event).await.expect("save");
3002 }
3003
3004 let listed = events.list_by_repo(&repo.id, 2).await.expect("list");
3005
3006 assert_eq!(listed.len(), 2);
3007 assert_eq!(listed[0].short_ref(), "three");
3008 assert_eq!(listed[1].short_ref(), "two");
3009 }
3010
3011 #[tokio::test]
3012 async fn recent_push_events_span_the_repositories_asked_for_and_no_others() {
3013 let (pool, first, user) = hooked_repo().await;
3014 let repos = SqliteRepoRepo::new(pool.clone());
3015 let orgs = SqliteOrgRepo::new(pool.clone());
3016 let org = orgs
3017 .find_by_id(&first.org_id)
3018 .await
3019 .expect("lookup")
3020 .expect("the fixture's org");
3021 let second = saved_repo(&repos, &org, "other", Visibility::Public).await;
3022 let unseen = saved_repo(&repos, &org, "private", Visibility::Private).await;
3023 let events = SqlitePushEventRepo::new(pool);
3024
3025 for (repo, seconds, name) in [
3026 (&first, 1_000, "one"),
3027 (&second, 3_000, "three"),
3028 (&first, 2_000, "two"),
3029 (&unseen, 4_000, "hidden"),
3030 ] {
3031 let event = PushEvent::new(
3032 PushEventId::generate(),
3033 repo.id.clone(),
3034 RefName::from_trusted(format!("refs/heads/{name}")),
3035 oid("a"),
3036 oid("b"),
3037 Some(user.id.clone()),
3038 at(seconds),
3039 )
3040 .expect("valid event");
3041 events.save(&event).await.expect("save");
3042 }
3043
3044 let listed = events
3045 .list_recent(&[first.id.clone(), second.id.clone()], 10)
3046 .await
3047 .expect("list");
3048
3049 assert_eq!(
3050 listed.iter().map(PushEvent::short_ref).collect::<Vec<_>>(),
3051 vec!["three", "two", "one"],
3052 "newest first, across both repositories, and never the one not asked for"
3053 );
3054
3055 assert_eq!(
3056 events
3057 .list_recent(&[first.id.clone(), second.id.clone()], 1)
3058 .await
3059 .expect("list")
3060 .len(),
3061 1,
3062 "the limit applies to the merged list, not to each repository"
3063 );
3064
3065 assert!(
3066 events.list_recent(&[], 10).await.expect("list").is_empty(),
3067 "no repositories means nothing to report, not everything"
3068 );
3069 }
3070
3071 #[tokio::test]
3072 async fn a_webhook_round_trips_with_its_secret_and_deliveries_follow_it_out() {
3073 // The cascade is the point: a hook's deliveries are that hook's history and
3074 // mean nothing without it.
3075 let (pool, repo, user) = hooked_repo().await;
3076 let events = SqlitePushEventRepo::new(pool.clone());
3077 let webhooks = SqliteWebhookRepo::new(pool.clone());
3078 let deliveries = SqliteWebhookDeliveryRepo::new(pool);
3079
3080 let hook = Webhook::new(
3081 WebhookId::generate(),
3082 repo.id.clone(),
3083 "https://example.com/hook",
3084 WebhookSecret::generate(),
3085 at(1_000),
3086 PrivateTargets::Refused,
3087 )
3088 .expect("valid hook");
3089 webhooks.save(&hook).await.expect("save");
3090
3091 let found = webhooks
3092 .find(&hook.id)
3093 .await
3094 .expect("lookup")
3095 .expect("hook should exist");
3096 assert_eq!(found.secret.reveal(), hook.secret.reveal());
3097 assert_eq!(found, hook);
3098
3099 let event = PushEvent::new(
3100 PushEventId::generate(),
3101 repo.id.clone(),
3102 RefName::from_trusted("refs/heads/main"),
3103 oid("a"),
3104 oid("b"),
3105 Some(user.id),
3106 at(2_000),
3107 )
3108 .expect("valid event");
3109 events.save(&event).await.expect("save");
3110
3111 for attempt in 1..=2u32 {
3112 deliveries
3113 .save(&WebhookDelivery::record(
3114 WebhookDeliveryId::generate(),
3115 hook.id.clone(),
3116 event.id.clone(),
3117 attempt,
3118 if attempt == 2 { Some(200) } else { None },
3119 "boom",
3120 12,
3121 at(2_000 + u64::from(attempt)),
3122 ))
3123 .await
3124 .expect("save");
3125 }
3126
3127 let listed = deliveries
3128 .list_by_webhook(&hook.id, 0, 10)
3129 .await
3130 .expect("list");
3131 assert_eq!(listed.len(), 2);
3132 assert_eq!(listed[0].attempt, 2, "newest attempt first");
3133 assert!(listed[0].ok);
3134 assert_eq!(listed[1].status, None);
3135 assert_eq!(listed[1].response, "boom");
3136
3137 // Paging: the second page starts where the first ended, and the count is what
3138 // the deliveries page numbers itself from.
3139 let first = deliveries
3140 .list_by_webhook(&hook.id, 0, 1)
3141 .await
3142 .expect("list");
3143 let second = deliveries
3144 .list_by_webhook(&hook.id, 1, 1)
3145 .await
3146 .expect("list");
3147
3148 assert_eq!(first.len(), 1);
3149 assert_eq!(first[0].attempt, 2);
3150 assert_eq!(second.len(), 1);
3151 assert_eq!(second[0].attempt, 1);
3152 assert_eq!(
3153 deliveries.count_by_webhook(&hook.id).await.expect("count"),
3154 2
3155 );
3156 assert!(
3157 deliveries
3158 .list_by_webhook(&hook.id, 500, 1)
3159 .await
3160 .expect("list")
3161 .is_empty(),
3162 "an offset past the end is an empty page"
3163 );
3164
3165 assert_eq!(
3166 deliveries
3167 .latest_by_webhook(&hook.id)
3168 .await
3169 .expect("lookup")
3170 .map(|delivery| delivery.attempt),
3171 Some(2)
3172 );
3173
3174 webhooks.delete(&hook.id).await.expect("delete");
3175
3176 assert!(webhooks.find(&hook.id).await.expect("lookup").is_none());
3177 assert!(
3178 deliveries
3179 .list_by_webhook(&hook.id, 0, 10)
3180 .await
3181 .expect("list")
3182 .is_empty(),
3183 "deliveries should go with the hook"
3184 );
3185 assert!(
3186 events.find(&event.id).await.expect("lookup").is_some(),
3187 "the event outlives the hook that was told about it"
3188 );
3189 }
3190
3191 #[tokio::test]
3192 async fn a_hook_can_be_turned_off_and_stays_listed() {
3193 let (pool, repo, _) = hooked_repo().await;
3194 let webhooks = SqliteWebhookRepo::new(pool);
3195
3196 let mut hook = Webhook::new(
3197 WebhookId::generate(),
3198 repo.id.clone(),
3199 "https://example.com/hook",
3200 WebhookSecret::generate(),
3201 at(1_000),
3202 PrivateTargets::Refused,
3203 )
3204 .expect("valid hook");
3205 webhooks.save(&hook).await.expect("save");
3206
3207 hook.active = false;
3208 webhooks.save(&hook).await.expect("save again");
3209
3210 let listed = webhooks.list_by_repo(&repo.id).await.expect("list");
3211
3212 assert_eq!(listed.len(), 1);
3213 assert!(!listed[0].active);
3214 }
3215
3216 // --- SqliteTokenRepo, lifecycle ------------------------------------------------
3217
3218 #[tokio::test]
3219 async fn an_expiry_survives_a_round_trip_through_the_table() {
3220 let (tokens, owner, _) = token_fixture().await;
3221 let (mut token, secret) = issued(&owner, "laptop", 1_000);
3222 token.expires_at = Some(SystemTime::UNIX_EPOCH + Duration::from_secs(90_000));
3223 tokens.save(&token).await.expect("save");
3224
3225 let found = tokens
3226 .find_by_hash(&secret.hash())
3227 .await
3228 .expect("lookup")
3229 .expect("present");
3230
3231 assert_eq!(found.expires_at, token.expires_at);
3232 assert_eq!(found.last_used_at, None);
3233 }
3234
3235 #[tokio::test]
3236 async fn a_token_with_no_expiry_reads_back_with_none() {
3237 // The column is nullable and null is the answer, not the epoch — every token
3238 // issued before the lifecycle migration is exactly this row.
3239 let (tokens, owner, _) = token_fixture().await;
3240 let (mut token, secret) = issued(&owner, "mirror", 1_000);
3241 token.expires_at = None;
3242 tokens.save(&token).await.expect("save");
3243
3244 assert_eq!(
3245 tokens
3246 .find_by_hash(&secret.hash())
3247 .await
3248 .expect("lookup")
3249 .expect("present")
3250 .expires_at,
3251 None
3252 );
3253 }
3254
3255 #[tokio::test]
3256 async fn recording_a_use_moves_only_that_column() {
3257 let (tokens, owner, _) = token_fixture().await;
3258 let (token, secret) = issued(&owner, "laptop", 1_000);
3259 tokens.save(&token).await.expect("save");
3260
3261 let used_at = SystemTime::UNIX_EPOCH + Duration::from_secs(5_000);
3262 tokens
3263 .touch_last_used(&token.id, used_at)
3264 .await
3265 .expect("touch");
3266
3267 let found = tokens
3268 .find_by_hash(&secret.hash())
3269 .await
3270 .expect("lookup")
3271 .expect("present");
3272
3273 assert_eq!(found.last_used_at, Some(used_at));
3274 assert_eq!(found.name, token.name);
3275 assert_eq!(found.created_at, token.created_at);
3276 assert_eq!(found.expires_at, token.expires_at);
3277 }
3278
3279 #[tokio::test]
3280 async fn saving_a_stale_record_does_not_walk_the_last_use_backwards() {
3281 // `save` upserts, and the record a caller holds may predate a use recorded since.
3282 // Only `touch_last_used` owns that column.
3283 let (tokens, owner, _) = token_fixture().await;
3284 let (mut token, secret) = issued(&owner, "laptop", 1_000);
3285 tokens.save(&token).await.expect("save");
3286
3287 let used_at = SystemTime::UNIX_EPOCH + Duration::from_secs(5_000);
3288 tokens
3289 .touch_last_used(&token.id, used_at)
3290 .await
3291 .expect("touch");
3292
3293 token.name = "renamed".to_owned();
3294 tokens.save(&token).await.expect("save again");
3295
3296 let found = tokens
3297 .find_by_hash(&secret.hash())
3298 .await
3299 .expect("lookup")
3300 .expect("present");
3301
3302 assert_eq!(found.name, "renamed");
3303 assert_eq!(found.last_used_at, Some(used_at));
3304 }
3305
3306 #[tokio::test]
3307 async fn recording_a_use_of_a_revoked_token_succeeds() {
3308 let (tokens, _, _) = token_fixture().await;
3309
3310 assert!(
3311 tokens
3312 .touch_last_used(&TokenId::generate(), SystemTime::UNIX_EPOCH)
3313 .await
3314 .is_ok()
3315 );
3316 }
3317
3318 // --- SqliteLabelRepo --------------------------------------------------------------
3319
3320 struct LabelFixture {
3321 pool: SqlitePool,
3322 labels: SqliteLabelRepo,
3323 issues: SqliteIssueRepo,
3324 repo: Repository,
3325 other: Repository,
3326 author: User,
3327 }
3328
3329 /// The issue fixture plus a label repository on the same pool — labels hang off
3330 /// repositories and assignments off issues, so both foreign keys need somewhere to
3331 /// land.
3332 async fn label_fixture() -> LabelFixture {
3333 let pool = test_pool().await;
3334 let repos = Repos {
3335 users: SqliteUserRepo::new(pool.clone()),
3336 orgs: SqliteOrgRepo::new(pool.clone()),
3337 memberships: SqliteMembershipRepo::new(pool.clone()),
3338 };
3339 let repo_repo = SqliteRepoRepo::new(pool.clone());
3340
3341 let org = saved_org(&repos, "acme").await;
3342 let author = saved_user(&repos, "owner@example.com", &org).await;
3343
3344 LabelFixture {
3345 labels: SqliteLabelRepo::new(pool.clone()),
3346 issues: SqliteIssueRepo::new(pool.clone()),
3347 pool,
3348 repo: saved_repo(&repo_repo, &org, "steid", Visibility::Public).await,
3349 other: saved_repo(&repo_repo, &org, "other", Visibility::Public).await,
3350 author,
3351 }
3352 }
3353
3354 async fn saved_label(f: &LabelFixture, repo: &Repository, name: &str) -> Label {
3355 let label = Label::new(
3356 LabelId::generate(),
3357 repo.id.clone(),
3358 name,
3359 LabelColour::Blue,
3360 None,
3361 at(1_000),
3362 )
3363 .expect("valid label");
3364
3365 f.labels.save(&label).await.expect("save label");
3366
3367 label
3368 }
3369
3370 async fn saved_issue(f: &LabelFixture, number: u64, title: &str) -> Issue {
3371 let issue = Issue::new(
3372 IssueId::generate(),
3373 f.repo.id.clone(),
3374 IssueNumber::from_trusted(number),
3375 title,
3376 "body",
3377 f.author.id.clone(),
3378 at(1_000),
3379 )
3380 .expect("valid issue");
3381
3382 f.issues.save(&issue).await.expect("save issue");
3383
3384 issue
3385 }
3386
3387 #[tokio::test]
3388 async fn labels_are_listed_by_name_and_scoped_to_their_repository() {
3389 let f = label_fixture().await;
3390
3391 for name in ["docs", "bug"] {
3392 saved_label(&f, &f.repo, name).await;
3393 }
3394 saved_label(&f, &f.other, "bug").await;
3395
3396 let names: Vec<String> = f
3397 .labels
3398 .list_by_repo(&f.repo.id)
3399 .await
3400 .expect("list")
3401 .into_iter()
3402 .map(|label| label.name)
3403 .collect();
3404
3405 assert_eq!(names, ["bug", "docs"]);
3406 assert_eq!(
3407 f.labels
3408 .list_by_repo(&f.other.id)
3409 .await
3410 .expect("list")
3411 .len(),
3412 1
3413 );
3414 }
3415
3416 #[tokio::test]
3417 async fn a_name_is_unique_within_a_repository() {
3418 let f = label_fixture().await;
3419
3420 saved_label(&f, &f.repo, "bug").await;
3421
3422 // The index is the backstop under the use case's own check: a second row with
3423 // the same name on the same repository must not be storable at all.
3424 let duplicate = Label::new(
3425 LabelId::generate(),
3426 f.repo.id.clone(),
3427 "bug",
3428 LabelColour::Red,
3429 None,
3430 at(2_000),
3431 )
3432 .expect("valid label");
3433
3434 assert!(f.labels.save(&duplicate).await.is_err());
3435 // The same name on another repository is a different label.
3436 saved_label(&f, &f.other, "bug").await;
3437 }
3438
3439 #[tokio::test]
3440 async fn saving_an_existing_label_renames_and_recolours_it() {
3441 let f = label_fixture().await;
3442 let mut label = saved_label(&f, &f.repo, "bug").await;
3443
3444 label
3445 .edit("defect", LabelColour::Purple, Some("broken".to_owned()))
3446 .expect("valid edit");
3447 f.labels.save(&label).await.expect("save again");
3448
3449 let stored = f
3450 .labels
3451 .find_by_id(&label.id)
3452 .await
3453 .expect("lookup")
3454 .expect("still there");
3455
3456 assert_eq!(stored.name, "defect");
3457 assert_eq!(stored.colour, LabelColour::Purple);
3458 assert_eq!(stored.description.as_deref(), Some("broken"));
3459 assert_eq!(
3460 stored.created_at,
3461 at(1_000),
3462 "creation is not moved by an edit"
3463 );
3464 }
3465
3466 #[tokio::test]
3467 async fn a_label_is_found_by_its_name_on_its_own_repository_only() {
3468 let f = label_fixture().await;
3469 saved_label(&f, &f.other, "bug").await;
3470
3471 assert!(
3472 f.labels
3473 .find_by_name(&f.repo.id, "bug")
3474 .await
3475 .expect("lookup")
3476 .is_none()
3477 );
3478 assert!(
3479 f.labels
3480 .find_by_name(&f.other.id, "bug")
3481 .await
3482 .expect("lookup")
3483 .is_some()
3484 );
3485 }
3486
3487 #[tokio::test]
3488 async fn setting_the_full_set_replaces_what_was_there() {
3489 let f = label_fixture().await;
3490 let issue = saved_issue(&f, 1, "Blame is slow").await;
3491
3492 let bug = saved_label(&f, &f.repo, "bug").await;
3493 let docs = saved_label(&f, &f.repo, "docs").await;
3494
3495 f.labels
3496 .set_issue_labels(&issue.id, &[bug.id.clone(), docs.id.clone()])
3497 .await
3498 .expect("assign");
3499 assert_eq!(carried(&f, &issue).await, ["bug", "docs"]);
3500
3501 // Applying the same set again is a no-op rather than a duplicate-key failure.
3502 f.labels
3503 .set_issue_labels(&issue.id, &[bug.id.clone(), docs.id.clone()])
3504 .await
3505 .expect("assign again");
3506 assert_eq!(carried(&f, &issue).await, ["bug", "docs"]);
3507
3508 f.labels
3509 .set_issue_labels(&issue.id, std::slice::from_ref(&docs.id))
3510 .await
3511 .expect("replace");
3512 assert_eq!(carried(&f, &issue).await, ["docs"]);
3513
3514 f.labels
3515 .set_issue_labels(&issue.id, &[])
3516 .await
3517 .expect("clear");
3518 assert!(carried(&f, &issue).await.is_empty());
3519 }
3520
3521 #[tokio::test]
3522 async fn the_repository_wide_read_groups_every_pair_and_counts_them() {
3523 let f = label_fixture().await;
3524 let first = saved_issue(&f, 1, "Blame is slow").await;
3525 let second = saved_issue(&f, 2, "Docs are thin").await;
3526
3527 let bug = saved_label(&f, &f.repo, "bug").await;
3528 let docs = saved_label(&f, &f.repo, "docs").await;
3529 let unused = saved_label(&f, &f.repo, "chore").await;
3530
3531 f.labels
3532 .set_issue_labels(&first.id, &[bug.id.clone(), docs.id.clone()])
3533 .await
3534 .expect("assign");
3535 f.labels
3536 .set_issue_labels(&second.id, std::slice::from_ref(&bug.id))
3537 .await
3538 .expect("assign");
3539
3540 let pairs = f.labels.labels_for_repo(&f.repo.id).await.expect("pairs");
3541 assert_eq!(pairs.len(), 3);
3542 assert_eq!(
3543 pairs
3544 .iter()
3545 .filter(|(issue, _)| issue == &first.id)
3546 .map(|(_, label)| label.name.as_str())
3547 .collect::<Vec<_>>(),
3548 ["bug", "docs"]
3549 );
3550
3551 let mut counts = f.labels.issue_counts(&f.repo.id).await.expect("counts");
3552 counts.sort_by(|left, right| left.0.cmp(&right.0));
3553
3554 let count_of = |id: &LabelId| {
3555 counts
3556 .iter()
3557 .find(|(label, _)| label == id)
3558 .map(|(_, total)| *total)
3559 };
3560
3561 assert_eq!(count_of(&bug.id), Some(2));
3562 assert_eq!(count_of(&docs.id), Some(1));
3563 // An unused label still gets a row rather than being absent from the lookup.
3564 assert_eq!(count_of(&unused.id), Some(0));
3565 }
3566
3567 #[tokio::test]
3568 async fn deleting_a_label_takes_it_off_every_issue_and_leaves_them_there() {
3569 let f = label_fixture().await;
3570 let issue = saved_issue(&f, 1, "Blame is slow").await;
3571
3572 let bug = saved_label(&f, &f.repo, "bug").await;
3573 let docs = saved_label(&f, &f.repo, "docs").await;
3574
3575 f.labels
3576 .set_issue_labels(&issue.id, &[bug.id.clone(), docs.id.clone()])
3577 .await
3578 .expect("assign");
3579
3580 f.labels.delete(&bug.id).await.expect("delete");
3581
3582 assert_eq!(carried(&f, &issue).await, ["docs"]);
3583 assert!(
3584 f.issues
3585 .find_by_number(&f.repo.id, IssueNumber::from_trusted(1))
3586 .await
3587 .expect("lookup")
3588 .is_some(),
3589 "the issue survives its label"
3590 );
3591 }
3592
3593 #[tokio::test]
3594 async fn deleting_an_issue_takes_its_assignments_with_it() {
3595 let f = label_fixture().await;
3596 let issue = saved_issue(&f, 1, "Blame is slow").await;
3597 let bug = saved_label(&f, &f.repo, "bug").await;
3598
3599 f.labels
3600 .set_issue_labels(&issue.id, std::slice::from_ref(&bug.id))
3601 .await
3602 .expect("assign");
3603
3604 sqlx::query("delete from issues where id = ?")
3605 .bind(issue.id.as_str())
3606 .execute(&f.pool)
3607 .await
3608 .expect("delete issue");
3609
3610 assert!(
3611 f.labels
3612 .labels_for_repo(&f.repo.id)
3613 .await
3614 .expect("pairs")
3615 .is_empty()
3616 );
3617 assert!(
3618 f.labels
3619 .find_by_id(&bug.id)
3620 .await
3621 .expect("lookup")
3622 .is_some(),
3623 "the label survives the issue"
3624 );
3625 }
3626
3627 #[tokio::test]
3628 async fn a_pull_request_wears_the_same_labels_and_is_counted_apart_from_the_issues() {
3629 let f = label_fixture().await;
3630 let issue = saved_issue(&f, 1, "Blame is slow").await;
3631 let pull = saved_pull(&f, 2, "Speed blame up").await;
3632
3633 let bug = saved_label(&f, &f.repo, "bug").await;
3634 let docs = saved_label(&f, &f.repo, "docs").await;
3635
3636 f.labels
3637 .set_issue_labels(&issue.id, std::slice::from_ref(&bug.id))
3638 .await
3639 .expect("assign issue");
3640 f.labels
3641 .set_pull_labels(&pull.id, &[bug.id.clone(), docs.id.clone()])
3642 .await
3643 .expect("assign pull");
3644
3645 assert_eq!(
3646 f.labels
3647 .labels_for_pull(&pull.id)
3648 .await
3649 .expect("labels")
3650 .into_iter()
3651 .map(|label| label.name)
3652 .collect::<Vec<_>>(),
3653 ["bug", "docs"]
3654 );
3655
3656 // The two join tables are two answers: the issue's assignment must not show up
3657 // in the pull request's pairs, nor in its counts.
3658 let pairs = f
3659 .labels
3660 .labels_for_repo_pulls(&f.repo.id)
3661 .await
3662 .expect("pairs");
3663 assert_eq!(pairs.len(), 2);
3664 assert!(pairs.iter().all(|(id, _)| id == &pull.id));
3665
3666 let counts = f.labels.pull_counts(&f.repo.id).await.expect("counts");
3667 let count_of = |id: &LabelId| {
3668 counts
3669 .iter()
3670 .find(|(label, _)| label == id)
3671 .map(|(_, total)| *total)
3672 };
3673
3674 assert_eq!(count_of(&bug.id), Some(1));
3675 assert_eq!(count_of(&docs.id), Some(1));
3676 assert_eq!(
3677 f.labels
3678 .issue_counts(&f.repo.id)
3679 .await
3680 .expect("counts")
3681 .iter()
3682 .find(|(label, _)| label == &docs.id)
3683 .map(|(_, total)| *total),
3684 Some(0),
3685 "an issue count must not pick up a pull request's assignment"
3686 );
3687 }
3688
3689 #[tokio::test]
3690 async fn deleting_a_pull_request_takes_its_assignments_with_it() {
3691 let f = label_fixture().await;
3692 let pull = saved_pull(&f, 1, "Speed blame up").await;
3693 let bug = saved_label(&f, &f.repo, "bug").await;
3694
3695 f.labels
3696 .set_pull_labels(&pull.id, std::slice::from_ref(&bug.id))
3697 .await
3698 .expect("assign");
3699
3700 sqlx::query("delete from pull_requests where id = ?")
3701 .bind(pull.id.as_str())
3702 .execute(&f.pool)
3703 .await
3704 .expect("delete pull request");
3705
3706 assert!(
3707 f.labels
3708 .labels_for_repo_pulls(&f.repo.id)
3709 .await
3710 .expect("pairs")
3711 .is_empty()
3712 );
3713 assert!(
3714 f.labels
3715 .find_by_id(&bug.id)
3716 .await
3717 .expect("lookup")
3718 .is_some(),
3719 "the label survives the pull request"
3720 );
3721 }
3722
3723 async fn saved_pull(f: &LabelFixture, number: u64, title: &str) -> PullRequest {
3724 let pull = PullRequest::new(
3725 PullRequestId::generate(),
3726 f.repo.id.clone(),
3727 IssueNumber::from_trusted(number),
3728 title,
3729 "body",
3730 f.author.id.clone(),
3731 RefName::from_trusted("spike"),
3732 RefName::from_trusted("main"),
3733 at(1_000),
3734 )
3735 .expect("valid pull request");
3736
3737 SqlitePullRequestRepo::new(f.pool.clone())
3738 .save(&pull)
3739 .await
3740 .expect("save pull request");
3741
3742 pull
3743 }
3744
3745 /// The names of the labels on one issue.
3746 async fn carried(f: &LabelFixture, issue: &Issue) -> Vec<String> {
3747 f.labels
3748 .labels_for_issue(&issue.id)
3749 .await
3750 .expect("labels")
3751 .into_iter()
3752 .map(|label| label.name)
3753 .collect()
3754 }
3755}