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, PasswordReset, PersonalAccessToken, PullRequest,
14 PullRequestComment, PullRequestCommentId, PullRequestId, PullRequestState, PushEvent,
15 PushEventId, RefName, RepoId, RepoName, Repository, ResetHash, ResetId, Role, Session,
16 SessionTokenHash, TokenHash, TokenId, User, UserId, Visibility, Webhook, WebhookDelivery,
17 WebhookDeliveryId, WebhookId, WebhookSecret, WebhookUrl,
18 repository::{
19 IssueCounts, IssueRepository, LabelRepository, MembershipRepository, OrgRepository,
20 PasswordResetRepository, PullRequestCounts, PullRequestRepository, PushEventRepository,
21 RepoRepository, RepositoryError, RepositoryResult, SessionRepository, TokenRepository,
22 UserRepository, WebhookDeliveryRepository, WebhookRepository,
23 },
24};
25
26fn backend(error: sqlx::Error) -> RepositoryError {
27 RepositoryError::backend(error)
28}
29
30#[derive(Debug, Clone)]
31pub struct SqliteUserRepo {
32 pool: SqlitePool,
33}
34
35impl SqliteUserRepo {
36 pub fn new(pool: SqlitePool) -> Self {
37 Self { pool }
38 }
39
40 fn map(row: &SqliteRow) -> User {
41 User::new(
42 UserId::from_trusted(row.get::<String, _>("id")),
43 Email::from_trusted(row.get::<String, _>("email")),
44 PasswordHash::from_trusted(row.get::<String, _>("password_hash")),
45 OrgId::from_trusted(row.get::<String, _>("personal_org_id")),
46 )
47 }
48}
49
50impl UserRepository for SqliteUserRepo {
51 async fn find_by_id(&self, id: &UserId) -> RepositoryResult<Option<User>> {
52 let row = sqlx::query("select * from users where id = ?")
53 .bind(id.as_str())
54 .fetch_optional(&self.pool)
55 .await
56 .map_err(backend)?;
57
58 Ok(row.as_ref().map(Self::map))
59 }
60
61 async fn find_by_email(&self, email: &Email) -> RepositoryResult<Option<User>> {
62 let row = sqlx::query("select * from users where email = ?")
63 .bind(email.as_str())
64 .fetch_optional(&self.pool)
65 .await
66 .map_err(backend)?;
67
68 Ok(row.as_ref().map(Self::map))
69 }
70
71 async fn find_by_personal_org(&self, org_id: &OrgId) -> RepositoryResult<Option<User>> {
72 let row = sqlx::query("select * from users where personal_org_id = ?")
73 .bind(org_id.as_str())
74 .fetch_optional(&self.pool)
75 .await
76 .map_err(backend)?;
77
78 Ok(row.as_ref().map(Self::map))
79 }
80
81 async fn save(&self, user: &User) -> RepositoryResult<()> {
82 sqlx::query(
83 "insert into users (id, email, password_hash, personal_org_id)
84 values (?, ?, ?, ?)
85 on conflict (id) do update set
86 email = excluded.email,
87 password_hash = excluded.password_hash,
88 personal_org_id = excluded.personal_org_id",
89 )
90 .bind(user.id.as_str())
91 .bind(user.email.as_str())
92 .bind(user.password_hash.as_str())
93 .bind(user.personal_org_id.as_str())
94 .execute(&self.pool)
95 .await
96 .map_err(backend)?;
97
98 Ok(())
99 }
100
101 async fn sole_user(&self) -> RepositoryResult<Option<User>> {
102 // `limit 2`, not `limit 1`: the query has to be able to see a second user in
103 // order to refuse, and `limit 1` would silently pick one.
104 let rows = sqlx::query("select * from users limit 2")
105 .fetch_all(&self.pool)
106 .await
107 .map_err(backend)?;
108
109 match rows.as_slice() {
110 [row] => Ok(Some(Self::map(row))),
111 _ => Ok(None),
112 }
113 }
114
115 async fn any_exist(&self) -> RepositoryResult<bool> {
116 let count: i64 = sqlx::query_scalar("select exists (select 1 from users)")
117 .fetch_one(&self.pool)
118 .await
119 .map_err(backend)?;
120
121 Ok(count != 0)
122 }
123
124 async fn count(&self) -> RepositoryResult<u64> {
125 let count: i64 = sqlx::query_scalar("select count(*) from users")
126 .fetch_one(&self.pool)
127 .await
128 .map_err(backend)?;
129
130 Ok(count.max(0).unsigned_abs())
131 }
132}
133
134#[derive(Debug, Clone)]
135pub struct SqliteOrgRepo {
136 pool: SqlitePool,
137}
138
139impl SqliteOrgRepo {
140 pub fn new(pool: SqlitePool) -> Self {
141 Self { pool }
142 }
143
144 fn map(row: &SqliteRow) -> Organization {
145 Organization::from_trusted(
146 OrgId::from_trusted(row.get::<String, _>("id")),
147 OrgName::from_trusted(row.get::<String, _>("name")),
148 row.get::<Option<String>, _>("display_name"),
149 row.get::<Option<String>, _>("bio"),
150 )
151 }
152}
153
154impl OrgRepository for SqliteOrgRepo {
155 async fn find_by_id(&self, id: &OrgId) -> RepositoryResult<Option<Organization>> {
156 let row = sqlx::query("select * from orgs where id = ?")
157 .bind(id.as_str())
158 .fetch_optional(&self.pool)
159 .await
160 .map_err(backend)?;
161
162 Ok(row.as_ref().map(Self::map))
163 }
164
165 async fn find_by_name(&self, name: &OrgName) -> RepositoryResult<Option<Organization>> {
166 let row = sqlx::query("select * from orgs where name = ?")
167 .bind(name.as_str())
168 .fetch_optional(&self.pool)
169 .await
170 .map_err(backend)?;
171
172 Ok(row.as_ref().map(Self::map))
173 }
174
175 async fn save(&self, org: &Organization) -> RepositoryResult<()> {
176 sqlx::query(
177 "insert into orgs (id, name, display_name, bio)
178 values (?, ?, ?, ?)
179 on conflict (id) do update set
180 name = excluded.name,
181 display_name = excluded.display_name,
182 bio = excluded.bio",
183 )
184 .bind(org.id.as_str())
185 .bind(org.name.as_str())
186 .bind(org.display_name.as_deref())
187 .bind(org.bio.as_deref())
188 .execute(&self.pool)
189 .await
190 .map_err(backend)?;
191
192 Ok(())
193 }
194
195 async fn count(&self) -> RepositoryResult<u64> {
196 let count: i64 = sqlx::query_scalar("select count(*) from orgs")
197 .fetch_one(&self.pool)
198 .await
199 .map_err(backend)?;
200
201 Ok(count.max(0) as u64)
202 }
203}
204
205#[derive(Debug, Clone)]
206pub struct SqliteMembershipRepo {
207 pool: SqlitePool,
208}
209
210impl SqliteMembershipRepo {
211 pub fn new(pool: SqlitePool) -> Self {
212 Self { pool }
213 }
214
215 /// An unparseable role is a storage fault, not a missing membership, so it
216 /// surfaces rather than silently downgrading the member's access.
217 fn map(row: &SqliteRow) -> RepositoryResult<Membership> {
218 let raw: String = row.get("role");
219 let role: Role = raw
220 .parse()
221 .map_err(|error| RepositoryError::backend(format!("{error}")))?;
222
223 Ok(Membership::new(
224 MembershipId::from_trusted(row.get::<String, _>("id")),
225 OrgId::from_trusted(row.get::<String, _>("org_id")),
226 UserId::from_trusted(row.get::<String, _>("user_id")),
227 role,
228 ))
229 }
230}
231
232impl MembershipRepository for SqliteMembershipRepo {
233 async fn find(&self, org_id: &OrgId, user_id: &UserId) -> RepositoryResult<Option<Membership>> {
234 let row = sqlx::query("select * from memberships where org_id = ? and user_id = ?")
235 .bind(org_id.as_str())
236 .bind(user_id.as_str())
237 .fetch_optional(&self.pool)
238 .await
239 .map_err(backend)?;
240
241 row.as_ref().map(Self::map).transpose()
242 }
243
244 async fn list_for_user(&self, user_id: &UserId) -> RepositoryResult<Vec<Membership>> {
245 let rows = sqlx::query("select * from memberships where user_id = ?")
246 .bind(user_id.as_str())
247 .fetch_all(&self.pool)
248 .await
249 .map_err(backend)?;
250
251 rows.iter().map(Self::map).collect()
252 }
253
254 async fn save(&self, membership: &Membership) -> RepositoryResult<()> {
255 sqlx::query(
256 "insert into memberships (id, org_id, user_id, role)
257 values (?, ?, ?, ?)
258 on conflict (id) do update set role = excluded.role",
259 )
260 .bind(membership.id.as_str())
261 .bind(membership.org_id.as_str())
262 .bind(membership.user_id.as_str())
263 .bind(membership.role.as_str())
264 .execute(&self.pool)
265 .await
266 .map_err(backend)?;
267
268 Ok(())
269 }
270}
271
272#[derive(Debug, Clone)]
273pub struct SqliteSessionRepo {
274 pool: SqlitePool,
275}
276
277impl SqliteSessionRepo {
278 pub fn new(pool: SqlitePool) -> Self {
279 Self { pool }
280 }
281}
282
283/// Unix seconds. Times before the epoch cannot occur here — sessions always expire in
284/// the future — so saturating at 0 is safe rather than lossy.
285fn to_unix(time: SystemTime) -> i64 {
286 time.duration_since(SystemTime::UNIX_EPOCH)
287 .map(|d| d.as_secs() as i64)
288 .unwrap_or(0)
289}
290
291fn from_unix(seconds: i64) -> SystemTime {
292 SystemTime::UNIX_EPOCH + Duration::from_secs(seconds.max(0) as u64)
293}
294
295impl SessionRepository for SqliteSessionRepo {
296 async fn find(&self, token_hash: &SessionTokenHash) -> RepositoryResult<Option<Session>> {
297 let row = sqlx::query("select * from sessions where token_hash = ?")
298 .bind(token_hash.as_str())
299 .fetch_optional(&self.pool)
300 .await
301 .map_err(backend)?;
302
303 Ok(row.map(|row| {
304 Session::new(
305 SessionTokenHash::from_trusted(row.get::<String, _>("token_hash")),
306 UserId::from_trusted(row.get::<String, _>("user_id")),
307 from_unix(row.get::<i64, _>("expires_at")),
308 )
309 }))
310 }
311
312 async fn save(&self, session: &Session) -> RepositoryResult<()> {
313 sqlx::query(
314 "insert into sessions (token_hash, user_id, expires_at)
315 values (?, ?, ?)
316 on conflict (token_hash) do update set
317 user_id = excluded.user_id,
318 expires_at = excluded.expires_at",
319 )
320 .bind(session.token_hash.as_str())
321 .bind(session.user_id.as_str())
322 .bind(to_unix(session.expires_at))
323 .execute(&self.pool)
324 .await
325 .map_err(backend)?;
326
327 Ok(())
328 }
329
330 async fn delete(&self, token_hash: &SessionTokenHash) -> RepositoryResult<()> {
331 sqlx::query("delete from sessions where token_hash = ?")
332 .bind(token_hash.as_str())
333 .execute(&self.pool)
334 .await
335 .map_err(backend)?;
336
337 Ok(())
338 }
339
340 async fn delete_by_user(
341 &self,
342 user_id: &UserId,
343 except: Option<&SessionTokenHash>,
344 ) -> RepositoryResult<u64> {
345 // One statement rather than a read and a loop: signing every other device out is
346 // the security half of a password change, and it must not be able to half-happen.
347 // `?` binds the empty string when nothing is kept, which matches no row — a token
348 // hash is 64 hex characters.
349 let result = sqlx::query("delete from sessions where user_id = ? and token_hash <> ?")
350 .bind(user_id.as_str())
351 .bind(except.map_or("", SessionTokenHash::as_str))
352 .execute(&self.pool)
353 .await
354 .map_err(backend)?;
355
356 Ok(result.rows_affected())
357 }
358
359 async fn delete_expired(&self, now: SystemTime) -> RepositoryResult<u64> {
360 let result = sqlx::query("delete from sessions where expires_at <= ?")
361 .bind(to_unix(now))
362 .execute(&self.pool)
363 .await
364 .map_err(backend)?;
365
366 Ok(result.rows_affected())
367 }
368}
369
370#[derive(Debug, Clone)]
371pub struct SqliteRepoRepo {
372 pool: SqlitePool,
373}
374
375impl SqliteRepoRepo {
376 pub fn new(pool: SqlitePool) -> Self {
377 Self { pool }
378 }
379
380 /// An unparseable visibility is a storage fault, not a default.
381 ///
382 /// Falling back to `Public` would publish a repository whose row we cannot read;
383 /// falling back to `Private` would hide a public one. Neither is a guess worth
384 /// making, so the row surfaces as an error.
385 fn map(row: &SqliteRow) -> RepositoryResult<Repository> {
386 let raw: String = row.get("visibility");
387 let visibility: Visibility = raw
388 .parse()
389 .map_err(|error| RepositoryError::backend(format!("{error}")))?;
390
391 // An unparseable import state is a fault for the same reason an unparseable
392 // visibility is: both possible defaults are wrong. `None` would serve a
393 // half-cloned repository as finished; `Failed` would bury a working one.
394 let import_state: Option<ImportState> = row
395 .get::<Option<String>, _>("import_state")
396 .map(|raw| raw.parse())
397 .transpose()
398 .map_err(|error| RepositoryError::backend(format!("{error}")))?;
399
400 Ok(Repository::from_trusted(
401 RepoId::from_trusted(row.get::<String, _>("id")),
402 OrgId::from_trusted(row.get::<String, _>("org_id")),
403 RepoName::from_trusted(row.get::<String, _>("name")),
404 row.get::<Option<String>, _>("description"),
405 visibility,
406 from_unix(row.get::<i64, _>("updated_at")),
407 row.get::<i64, _>("pinned") != 0,
408 row.get::<i64, _>("archived") != 0,
409 )
410 .with_import(
411 import_state,
412 row.get::<Option<String>, _>("import_source")
413 .map(ImportSource::from_trusted),
414 row.get::<Option<String>, _>("import_error"),
415 ))
416 }
417}
418
419impl RepoRepository for SqliteRepoRepo {
420 /// One statement, so the read-modify-write is atomic without an explicit
421 /// transaction: SQLite serialises writers, and `on conflict … do update` sees the
422 /// row it is about to replace.
423 ///
424 /// `next_number` holds the number to hand out *next*, so the returned value is
425 /// always one past the allocation — on the insert branch it is 2 and the allocation
426 /// is 1, on the update branch it is `n + 1` and the allocation is `n`. Subtracting
427 /// one covers both without the statement having to know which branch it took.
428 async fn next_number(&self, repo_id: &RepoId) -> RepositoryResult<IssueNumber> {
429 let row = sqlx::query(
430 "insert into repo_sequences (repo_id, next_number) values (?, 2)
431 on conflict (repo_id) do update set next_number = next_number + 1
432 returning next_number",
433 )
434 .bind(repo_id.as_str())
435 .fetch_one(&self.pool)
436 .await
437 .map_err(backend)?;
438
439 let allocated = row.get::<i64, _>("next_number").saturating_sub(1).max(1);
440
441 Ok(IssueNumber::from_trusted(allocated as u64))
442 }
443
444 async fn find_by_id(&self, id: &RepoId) -> RepositoryResult<Option<Repository>> {
445 let row = sqlx::query("select * from repositories where id = ?")
446 .bind(id.as_str())
447 .fetch_optional(&self.pool)
448 .await
449 .map_err(backend)?;
450
451 row.as_ref().map(Self::map).transpose()
452 }
453
454 async fn find_by_org_and_name(
455 &self,
456 org_id: &OrgId,
457 name: &RepoName,
458 ) -> RepositoryResult<Option<Repository>> {
459 let row = sqlx::query("select * from repositories where org_id = ? and name = ?")
460 .bind(org_id.as_str())
461 .bind(name.as_str())
462 .fetch_optional(&self.pool)
463 .await
464 .map_err(backend)?;
465
466 row.as_ref().map(Self::map).transpose()
467 }
468
469 async fn list_by_org(&self, org_id: &OrgId) -> RepositoryResult<Vec<Repository>> {
470 // Newest first, name ascending as the tiebreak — `InMemoryRepoRepo::list_by_org`
471 // sorts identically, deliberately.
472 let rows = sqlx::query(
473 "select * from repositories where org_id = ? order by updated_at desc, name asc",
474 )
475 .bind(org_id.as_str())
476 .fetch_all(&self.pool)
477 .await
478 .map_err(backend)?;
479
480 rows.iter().map(Self::map).collect()
481 }
482
483 async fn save(&self, repo: &Repository) -> RepositoryResult<()> {
484 sqlx::query(
485 "insert into repositories
486 (id, org_id, name, description, visibility, updated_at, pinned, archived,
487 import_state, import_source, import_error)
488 values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
489 on conflict (id) do update set
490 org_id = excluded.org_id,
491 name = excluded.name,
492 description = excluded.description,
493 visibility = excluded.visibility,
494 updated_at = excluded.updated_at,
495 pinned = excluded.pinned,
496 archived = excluded.archived,
497 import_state = excluded.import_state,
498 import_source = excluded.import_source,
499 import_error = excluded.import_error",
500 )
501 .bind(repo.id.as_str())
502 .bind(repo.org_id.as_str())
503 .bind(repo.name.as_str())
504 .bind(repo.description.as_deref())
505 .bind(repo.visibility.as_str())
506 .bind(to_unix(repo.updated_at))
507 .bind(i64::from(repo.pinned))
508 .bind(i64::from(repo.archived))
509 .bind(repo.import_state.map(ImportState::as_str))
510 .bind(repo.import_source.as_ref().map(ImportSource::as_str))
511 .bind(repo.import_error.as_deref())
512 .execute(&self.pool)
513 .await
514 .map_err(backend)?;
515
516 Ok(())
517 }
518
519 async fn touch(&self, id: &RepoId, now: SystemTime) -> RepositoryResult<()> {
520 // A column update rather than a read-modify-write, so two pushes racing each
521 // other cannot restore an older timestamp.
522 sqlx::query("update repositories set updated_at = ? where id = ?")
523 .bind(to_unix(now))
524 .bind(id.as_str())
525 .execute(&self.pool)
526 .await
527 .map_err(backend)?;
528
529 Ok(())
530 }
531
532 async fn fail_interrupted_imports(&self, reason: &str) -> RepositoryResult<u64> {
533 let result = sqlx::query(
534 "update repositories
535 set import_state = ?, import_error = ?
536 where import_state = ?",
537 )
538 .bind(ImportState::Failed.as_str())
539 .bind(reason)
540 .bind(ImportState::Importing.as_str())
541 .execute(&self.pool)
542 .await
543 .map_err(backend)?;
544
545 Ok(result.rows_affected())
546 }
547
548 async fn delete(&self, id: &RepoId) -> RepositoryResult<()> {
549 sqlx::query("delete from repositories where id = ?")
550 .bind(id.as_str())
551 .execute(&self.pool)
552 .await
553 .map_err(backend)?;
554
555 Ok(())
556 }
557
558 async fn count(&self) -> RepositoryResult<u64> {
559 let count: i64 = sqlx::query_scalar("select count(*) from repositories")
560 .fetch_one(&self.pool)
561 .await
562 .map_err(backend)?;
563
564 Ok(count.max(0).unsigned_abs())
565 }
566}
567
568#[derive(Debug, Clone)]
569pub struct SqliteTokenRepo {
570 pool: SqlitePool,
571}
572
573impl SqliteTokenRepo {
574 pub fn new(pool: SqlitePool) -> Self {
575 Self { pool }
576 }
577
578 /// `from_trusted`, because these values were validated on the way in. Revalidating
579 /// stored rows means a tightened rule turns old rows unreadable.
580 fn hydrate(row: &SqliteRow) -> PersonalAccessToken {
581 PersonalAccessToken::from_trusted(
582 TokenId::from_trusted(row.get::<String, _>("id")),
583 UserId::from_trusted(row.get::<String, _>("user_id")),
584 row.get::<String, _>("name"),
585 row.get::<String, _>("prefix"),
586 TokenHash::from_trusted(row.get::<String, _>("token_hash")),
587 from_unix(row.get::<i64, _>("created_at")),
588 row.get::<Option<i64>, _>("expires_at").map(from_unix),
589 row.get::<Option<i64>, _>("last_used_at").map(from_unix),
590 )
591 }
592}
593
594impl TokenRepository for SqliteTokenRepo {
595 async fn find_by_hash(
596 &self,
597 hash: &TokenHash,
598 ) -> RepositoryResult<Option<PersonalAccessToken>> {
599 // Matched in SQL by the hash, which is safe to compare with `=`: it is a digest,
600 // not the secret. The constant-time comparison guards the value a client
601 // presents, and that never reaches the database.
602 let row = sqlx::query("select * from tokens where token_hash = ?")
603 .bind(hash.as_str())
604 .fetch_optional(&self.pool)
605 .await
606 .map_err(backend)?;
607
608 Ok(row.as_ref().map(Self::hydrate))
609 }
610
611 async fn list_by_user(&self, user_id: &UserId) -> RepositoryResult<Vec<PersonalAccessToken>> {
612 let rows =
613 sqlx::query("select * from tokens where user_id = ? order by created_at desc, id asc")
614 .bind(user_id.as_str())
615 .fetch_all(&self.pool)
616 .await
617 .map_err(backend)?;
618
619 Ok(rows.iter().map(Self::hydrate).collect())
620 }
621
622 async fn save(&self, token: &PersonalAccessToken) -> RepositoryResult<()> {
623 sqlx::query(
624 "insert into tokens
625 (id, user_id, name, prefix, token_hash, created_at, expires_at, last_used_at)
626 values (?, ?, ?, ?, ?, ?, ?, ?)
627 on conflict (id) do update set
628 name = excluded.name,
629 expires_at = excluded.expires_at",
630 )
631 .bind(token.id.as_str())
632 .bind(token.user_id.as_str())
633 .bind(&token.name)
634 .bind(&token.prefix)
635 .bind(token.token_hash.as_str())
636 .bind(to_unix(token.created_at))
637 .bind(token.expires_at.map(to_unix))
638 // Deliberately not in the `do update set`: `touch_last_used` owns this column,
639 // and a save carrying a stale record would otherwise walk the last use
640 // backwards.
641 .bind(token.last_used_at.map(to_unix))
642 .execute(&self.pool)
643 .await
644 .map_err(backend)?;
645
646 Ok(())
647 }
648
649 async fn touch_last_used(&self, id: &TokenId, at: SystemTime) -> RepositoryResult<()> {
650 sqlx::query("update tokens set last_used_at = ? where id = ?")
651 .bind(to_unix(at))
652 .bind(id.as_str())
653 .execute(&self.pool)
654 .await
655 .map_err(backend)?;
656
657 Ok(())
658 }
659
660 async fn delete(&self, id: &TokenId) -> RepositoryResult<()> {
661 sqlx::query("delete from tokens where id = ?")
662 .bind(id.as_str())
663 .execute(&self.pool)
664 .await
665 .map_err(backend)?;
666
667 Ok(())
668 }
669}
670
671// --- Issues ------------------------------------------------------------------------
672
673#[derive(Debug, Clone)]
674pub struct SqliteIssueRepo {
675 pool: SqlitePool,
676}
677
678impl SqliteIssueRepo {
679 pub fn new(pool: SqlitePool) -> Self {
680 Self { pool }
681 }
682
683 /// `from_trusted` throughout, including the state: the value was a valid
684 /// [`IssueState`] on the way in, and parsing it here would turn a tightened rule
685 /// into unreadable rows.
686 fn hydrate(row: &SqliteRow) -> Issue {
687 Issue::from_trusted(
688 IssueId::from_trusted(row.get::<String, _>("id")),
689 RepoId::from_trusted(row.get::<String, _>("repo_id")),
690 IssueNumber::from_trusted(row.get::<i64, _>("number").max(1) as u64),
691 row.get::<String, _>("title"),
692 row.get::<String, _>("body"),
693 // The one place a stored value is parsed rather than trusted, because
694 // `IssueState` has no `from_trusted` to give it — and there is nothing
695 // sensible to reconstruct an unknown state as. An unreadable row would be a
696 // bug in a migration, not in user input.
697 row.get::<String, _>("state")
698 .parse()
699 .unwrap_or(IssueState::Open),
700 UserId::from_trusted(row.get::<String, _>("author_id")),
701 from_unix(row.get::<i64, _>("created_at")),
702 from_unix(row.get::<i64, _>("updated_at")),
703 row.get::<Option<i64>, _>("closed_at").map(from_unix),
704 )
705 }
706
707 fn hydrate_comment(row: &SqliteRow) -> IssueComment {
708 IssueComment::from_trusted(
709 IssueCommentId::from_trusted(row.get::<String, _>("id")),
710 IssueId::from_trusted(row.get::<String, _>("issue_id")),
711 UserId::from_trusted(row.get::<String, _>("author_id")),
712 row.get::<String, _>("body"),
713 from_unix(row.get::<i64, _>("created_at")),
714 )
715 }
716}
717
718impl IssueRepository for SqliteIssueRepo {
719 async fn find_by_number(
720 &self,
721 repo_id: &RepoId,
722 number: IssueNumber,
723 ) -> RepositoryResult<Option<Issue>> {
724 let row = sqlx::query("select * from issues where repo_id = ? and number = ?")
725 .bind(repo_id.as_str())
726 .bind(number.get() as i64)
727 .fetch_optional(&self.pool)
728 .await
729 .map_err(backend)?;
730
731 Ok(row.as_ref().map(Self::hydrate))
732 }
733
734 async fn list_by_repo(
735 &self,
736 repo_id: &RepoId,
737 state: IssueState,
738 offset: usize,
739 limit: usize,
740 ) -> RepositoryResult<Vec<Issue>> {
741 // Newest first is descending *number*, not descending `created_at`: the
742 // sequence is monotonic, so it orders identically and cannot tie — which also
743 // makes `limit`/`offset` stable, since two rows can never swap places between
744 // one page and the next.
745 //
746 // A `limit` too large for SQLite's signed integer becomes the largest one it
747 // has, which is the same answer: every remaining row.
748 let rows = sqlx::query(
749 "select * from issues where repo_id = ? and state = ?
750 order by number desc
751 limit ? offset ?",
752 )
753 .bind(repo_id.as_str())
754 .bind(state.as_str())
755 .bind(i64::try_from(limit).unwrap_or(i64::MAX))
756 .bind(i64::try_from(offset).unwrap_or(i64::MAX))
757 .fetch_all(&self.pool)
758 .await
759 .map_err(backend)?;
760
761 Ok(rows.iter().map(Self::hydrate).collect())
762 }
763
764 async fn counts(&self, repo_id: &RepoId) -> RepositoryResult<IssueCounts> {
765 let rows = sqlx::query(
766 "select state, count(*) as total from issues where repo_id = ? group by state",
767 )
768 .bind(repo_id.as_str())
769 .fetch_all(&self.pool)
770 .await
771 .map_err(backend)?;
772
773 let mut counts = IssueCounts::default();
774
775 for row in &rows {
776 let total = row.get::<i64, _>("total").max(0) as u64;
777
778 match row.get::<String, _>("state").parse() {
779 Ok(IssueState::Open) => counts.open = total,
780 Ok(IssueState::Closed) => counts.closed = total,
781 // A state neither implementation can name is not counted as either. It
782 // would take a hand-edited row to reach this.
783 Err(_) => {}
784 }
785 }
786
787 Ok(counts)
788 }
789
790 async fn comment_counts(&self, repo_id: &RepoId) -> RepositoryResult<Vec<(IssueId, u64)>> {
791 // A left join so an issue with no comments still gets a row: the caller builds a
792 // lookup out of this, and a missing key and a zero would have to be handled
793 // identically anyway.
794 let rows = sqlx::query(
795 "select issues.id as issue_id, count(issue_comments.id) as total
796 from issues
797 left join issue_comments on issue_comments.issue_id = issues.id
798 where issues.repo_id = ?
799 group by issues.id",
800 )
801 .bind(repo_id.as_str())
802 .fetch_all(&self.pool)
803 .await
804 .map_err(backend)?;
805
806 Ok(rows
807 .iter()
808 .map(|row| {
809 (
810 IssueId::from_trusted(row.get::<String, _>("issue_id")),
811 row.get::<i64, _>("total").max(0) as u64,
812 )
813 })
814 .collect())
815 }
816
817 async fn save(&self, issue: &Issue) -> RepositoryResult<()> {
818 // `number`, `repo_id` and `author_id` are absent from the update list on
819 // purpose: an issue's identity is its number on its repository, and an edit that
820 // could move it would break every link ever written to it.
821 sqlx::query(
822 "insert into issues
823 (id, repo_id, number, title, body, state, author_id, created_at, updated_at, closed_at)
824 values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
825 on conflict (id) do update set
826 title = excluded.title,
827 body = excluded.body,
828 state = excluded.state,
829 updated_at = excluded.updated_at,
830 closed_at = excluded.closed_at",
831 )
832 .bind(issue.id.as_str())
833 .bind(issue.repo_id.as_str())
834 .bind(issue.number.get() as i64)
835 .bind(&issue.title)
836 .bind(&issue.body)
837 .bind(issue.state.as_str())
838 .bind(issue.author_id.as_str())
839 .bind(to_unix(issue.created_at))
840 .bind(to_unix(issue.updated_at))
841 .bind(issue.closed_at.map(to_unix))
842 .execute(&self.pool)
843 .await
844 .map_err(backend)?;
845
846 Ok(())
847 }
848
849 async fn list_comments(&self, issue_id: &IssueId) -> RepositoryResult<Vec<IssueComment>> {
850 // `rowid` breaks a tie, which is insertion order — two comments posted in the
851 // same second read in the order they were written. The id would not do: it is a
852 // random UUID, so a tie would come back in an arbitrary order and a conversation
853 // would occasionally read backwards.
854 let rows = sqlx::query(
855 "select * from issue_comments where issue_id = ? order by created_at asc, rowid asc",
856 )
857 .bind(issue_id.as_str())
858 .fetch_all(&self.pool)
859 .await
860 .map_err(backend)?;
861
862 Ok(rows.iter().map(Self::hydrate_comment).collect())
863 }
864
865 async fn add_comment(&self, comment: &IssueComment) -> RepositoryResult<()> {
866 sqlx::query(
867 "insert into issue_comments (id, issue_id, author_id, body, created_at)
868 values (?, ?, ?, ?, ?)",
869 )
870 .bind(comment.id.as_str())
871 .bind(comment.issue_id.as_str())
872 .bind(comment.author_id.as_str())
873 .bind(&comment.body)
874 .bind(to_unix(comment.created_at))
875 .execute(&self.pool)
876 .await
877 .map_err(backend)?;
878
879 Ok(())
880 }
881}
882
883#[derive(Debug, Clone)]
884pub struct SqlitePushEventRepo {
885 pool: SqlitePool,
886}
887
888impl SqlitePushEventRepo {
889 pub fn new(pool: SqlitePool) -> Self {
890 Self { pool }
891 }
892
893 fn hydrate(row: &SqliteRow) -> PushEvent {
894 PushEvent::from_trusted(
895 PushEventId::from_trusted(row.get::<String, _>("id")),
896 RepoId::from_trusted(row.get::<String, _>("repo_id")),
897 RefName::from_trusted(row.get::<String, _>("ref_name")),
898 ObjectId::from_trusted(row.get::<String, _>("before_id")),
899 ObjectId::from_trusted(row.get::<String, _>("after_id")),
900 row.get::<Option<String>, _>("pusher_id")
901 .map(UserId::from_trusted),
902 from_unix(row.get::<i64, _>("created_at")),
903 )
904 }
905}
906
907impl PushEventRepository for SqlitePushEventRepo {
908 async fn find(&self, id: &PushEventId) -> RepositoryResult<Option<PushEvent>> {
909 let row = sqlx::query("select * from push_events where id = ?")
910 .bind(id.as_str())
911 .fetch_optional(&self.pool)
912 .await
913 .map_err(backend)?;
914
915 Ok(row.as_ref().map(Self::hydrate))
916 }
917
918 async fn list_by_repo(
919 &self,
920 repo_id: &RepoId,
921 limit: usize,
922 ) -> RepositoryResult<Vec<PushEvent>> {
923 // The id breaks the tie, as it does for tokens: a `git push --all` writes every
924 // event in the same second, and without it the order is whatever SQLite felt
925 // like.
926 let rows = sqlx::query(
927 "select * from push_events where repo_id = ?
928 order by created_at desc, id asc
929 limit ?",
930 )
931 .bind(repo_id.as_str())
932 .bind(limit as i64)
933 .fetch_all(&self.pool)
934 .await
935 .map_err(backend)?;
936
937 Ok(rows.iter().map(Self::hydrate).collect())
938 }
939
940 async fn list_recent(
941 &self,
942 repo_ids: &[RepoId],
943 limit: usize,
944 ) -> RepositoryResult<Vec<PushEvent>> {
945 // No repositories means nothing to ask about — and `in ()` is a syntax error in
946 // SQLite, so the empty case has to be answered before the query is built.
947 if repo_ids.is_empty() {
948 return Ok(Vec::new());
949 }
950
951 // The `in` list is built from the *count* and every id is bound, so nothing
952 // from a repository name ever reaches the SQL text. `push_events_repo_id`
953 // covers `(repo_id, created_at desc)`, which is what this walks.
954 let placeholders = vec!["?"; repo_ids.len()].join(", ");
955 let sql = format!(
956 "select * from push_events where repo_id in ({placeholders})
957 order by created_at desc, id asc
958 limit ?"
959 );
960
961 // `AssertSqlSafe` because the string is built here and nowhere else: the only
962 // thing that varies is how many `?` the list has, and every id is bound.
963 let mut query = sqlx::query(AssertSqlSafe(sql));
964 for id in repo_ids {
965 query = query.bind(id.as_str());
966 }
967
968 let rows = query
969 .bind(limit as i64)
970 .fetch_all(&self.pool)
971 .await
972 .map_err(backend)?;
973
974 Ok(rows.iter().map(Self::hydrate).collect())
975 }
976
977 async fn save(&self, event: &PushEvent) -> RepositoryResult<()> {
978 sqlx::query(
979 "insert into push_events
980 (id, repo_id, ref_name, before_id, after_id, pusher_id, created_at)
981 values (?, ?, ?, ?, ?, ?, ?)
982 on conflict (id) do nothing",
983 )
984 .bind(event.id.as_str())
985 .bind(event.repo_id.as_str())
986 .bind(event.ref_name.as_str())
987 .bind(event.before.as_str())
988 .bind(event.after.as_str())
989 .bind(event.pusher.as_ref().map(|id| id.as_str()))
990 .bind(to_unix(event.created_at))
991 .execute(&self.pool)
992 .await
993 .map_err(backend)?;
994
995 Ok(())
996 }
997}
998
999#[derive(Debug, Clone)]
1000pub struct SqliteWebhookRepo {
1001 pool: SqlitePool,
1002}
1003
1004impl SqliteWebhookRepo {
1005 pub fn new(pool: SqlitePool) -> Self {
1006 Self { pool }
1007 }
1008
1009 fn hydrate(row: &SqliteRow) -> Webhook {
1010 Webhook::from_trusted(
1011 WebhookId::from_trusted(row.get::<String, _>("id")),
1012 RepoId::from_trusted(row.get::<String, _>("repo_id")),
1013 WebhookUrl::from_trusted(row.get::<String, _>("url")),
1014 WebhookSecret::from_trusted(row.get::<String, _>("secret")),
1015 row.get::<i64, _>("active") != 0,
1016 from_unix(row.get::<i64, _>("created_at")),
1017 )
1018 }
1019}
1020
1021impl WebhookRepository for SqliteWebhookRepo {
1022 async fn find(&self, id: &WebhookId) -> RepositoryResult<Option<Webhook>> {
1023 let row = sqlx::query("select * from webhooks where id = ?")
1024 .bind(id.as_str())
1025 .fetch_optional(&self.pool)
1026 .await
1027 .map_err(backend)?;
1028
1029 Ok(row.as_ref().map(Self::hydrate))
1030 }
1031
1032 async fn list_by_repo(&self, repo_id: &RepoId) -> RepositoryResult<Vec<Webhook>> {
1033 let rows =
1034 sqlx::query("select * from webhooks where repo_id = ? order by created_at asc, id asc")
1035 .bind(repo_id.as_str())
1036 .fetch_all(&self.pool)
1037 .await
1038 .map_err(backend)?;
1039
1040 Ok(rows.iter().map(Self::hydrate).collect())
1041 }
1042
1043 async fn save(&self, webhook: &Webhook) -> RepositoryResult<()> {
1044 sqlx::query(
1045 "insert into webhooks (id, repo_id, url, secret, active, created_at)
1046 values (?, ?, ?, ?, ?, ?)
1047 on conflict (id) do update set
1048 url = excluded.url,
1049 active = excluded.active",
1050 )
1051 .bind(webhook.id.as_str())
1052 .bind(webhook.repo_id.as_str())
1053 .bind(webhook.url.as_str())
1054 .bind(webhook.secret.reveal())
1055 .bind(i64::from(webhook.active))
1056 .bind(to_unix(webhook.created_at))
1057 .execute(&self.pool)
1058 .await
1059 .map_err(backend)?;
1060
1061 Ok(())
1062 }
1063
1064 async fn delete(&self, id: &WebhookId) -> RepositoryResult<()> {
1065 sqlx::query("delete from webhooks where id = ?")
1066 .bind(id.as_str())
1067 .execute(&self.pool)
1068 .await
1069 .map_err(backend)?;
1070
1071 Ok(())
1072 }
1073}
1074
1075#[derive(Debug, Clone)]
1076pub struct SqliteWebhookDeliveryRepo {
1077 pool: SqlitePool,
1078}
1079
1080impl SqliteWebhookDeliveryRepo {
1081 pub fn new(pool: SqlitePool) -> Self {
1082 Self { pool }
1083 }
1084
1085 fn hydrate(row: &SqliteRow) -> WebhookDelivery {
1086 WebhookDelivery::from_trusted(
1087 WebhookDeliveryId::from_trusted(row.get::<String, _>("id")),
1088 WebhookId::from_trusted(row.get::<String, _>("webhook_id")),
1089 PushEventId::from_trusted(row.get::<String, _>("event_id")),
1090 row.get::<i64, _>("attempt") as u32,
1091 row.get::<Option<i64>, _>("status_code")
1092 .map(|code| code as u16),
1093 row.get::<String, _>("response"),
1094 row.get::<i64, _>("duration_ms").max(0) as u64,
1095 from_unix(row.get::<i64, _>("delivered_at")),
1096 row.get::<i64, _>("ok") != 0,
1097 )
1098 }
1099}
1100
1101impl WebhookDeliveryRepository for SqliteWebhookDeliveryRepo {
1102 async fn list_by_webhook(
1103 &self,
1104 webhook_id: &WebhookId,
1105 offset: usize,
1106 limit: usize,
1107 ) -> RepositoryResult<Vec<WebhookDelivery>> {
1108 // Attempt descending as the tiebreak, not the id: three attempts against a dead
1109 // endpoint can land in the same second only when the failure is instant, and
1110 // when they do the useful order is last-tried-first. The tiebreak is what makes
1111 // `offset` stable — without it two rows could swap between pages.
1112 let rows = sqlx::query(
1113 "select * from webhook_deliveries where webhook_id = ?
1114 order by delivered_at desc, attempt desc
1115 limit ? offset ?",
1116 )
1117 .bind(webhook_id.as_str())
1118 .bind(i64::try_from(limit).unwrap_or(i64::MAX))
1119 .bind(i64::try_from(offset).unwrap_or(i64::MAX))
1120 .fetch_all(&self.pool)
1121 .await
1122 .map_err(backend)?;
1123
1124 Ok(rows.iter().map(Self::hydrate).collect())
1125 }
1126
1127 async fn count_by_webhook(&self, webhook_id: &WebhookId) -> RepositoryResult<usize> {
1128 let row =
1129 sqlx::query("select count(*) as total from webhook_deliveries where webhook_id = ?")
1130 .bind(webhook_id.as_str())
1131 .fetch_one(&self.pool)
1132 .await
1133 .map_err(backend)?;
1134
1135 Ok(row.get::<i64, _>("total").max(0) as usize)
1136 }
1137
1138 async fn latest_by_webhook(
1139 &self,
1140 webhook_id: &WebhookId,
1141 ) -> RepositoryResult<Option<WebhookDelivery>> {
1142 let row = sqlx::query(
1143 "select * from webhook_deliveries where webhook_id = ?
1144 order by delivered_at desc, attempt desc
1145 limit 1",
1146 )
1147 .bind(webhook_id.as_str())
1148 .fetch_optional(&self.pool)
1149 .await
1150 .map_err(backend)?;
1151
1152 Ok(row.as_ref().map(Self::hydrate))
1153 }
1154
1155 async fn save(&self, delivery: &WebhookDelivery) -> RepositoryResult<()> {
1156 sqlx::query(
1157 "insert into webhook_deliveries
1158 (id, webhook_id, event_id, attempt, status_code, response,
1159 duration_ms, delivered_at, ok)
1160 values (?, ?, ?, ?, ?, ?, ?, ?, ?)
1161 on conflict (id) do nothing",
1162 )
1163 .bind(delivery.id.as_str())
1164 .bind(delivery.webhook_id.as_str())
1165 .bind(delivery.event_id.as_str())
1166 .bind(i64::from(delivery.attempt))
1167 .bind(delivery.status.map(i64::from))
1168 .bind(&delivery.response)
1169 .bind(delivery.duration_ms as i64)
1170 .bind(to_unix(delivery.delivered_at))
1171 .bind(i64::from(delivery.ok))
1172 .execute(&self.pool)
1173 .await
1174 .map_err(backend)?;
1175
1176 Ok(())
1177 }
1178}
1179
1180// --- Labels ------------------------------------------------------------------------
1181
1182#[derive(Debug, Clone)]
1183pub struct SqliteLabelRepo {
1184 pool: SqlitePool,
1185}
1186
1187impl SqliteLabelRepo {
1188 pub fn new(pool: SqlitePool) -> Self {
1189 Self { pool }
1190 }
1191
1192 /// `from_trusted` throughout, except the colour — which has no `from_trusted` to
1193 /// give it, exactly like `IssueState`. A value neither name matches would take a
1194 /// hand-edited row, and gray is the one reading that cannot claim a label is more
1195 /// urgent than it is.
1196 fn hydrate(row: &SqliteRow) -> Label {
1197 Label::from_trusted(
1198 LabelId::from_trusted(row.get::<String, _>("id")),
1199 RepoId::from_trusted(row.get::<String, _>("repo_id")),
1200 row.get::<String, _>("name"),
1201 row.get::<String, _>("colour")
1202 .parse()
1203 .unwrap_or(LabelColour::Gray),
1204 row.get::<Option<String>, _>("description"),
1205 from_unix(row.get::<i64, _>("created_at")),
1206 )
1207 }
1208}
1209
1210impl LabelRepository for SqliteLabelRepo {
1211 async fn list_by_repo(&self, repo_id: &RepoId) -> RepositoryResult<Vec<Label>> {
1212 let rows = sqlx::query("select * from labels where repo_id = ? order by name asc")
1213 .bind(repo_id.as_str())
1214 .fetch_all(&self.pool)
1215 .await
1216 .map_err(backend)?;
1217
1218 Ok(rows.iter().map(Self::hydrate).collect())
1219 }
1220
1221 async fn find_by_id(&self, id: &LabelId) -> RepositoryResult<Option<Label>> {
1222 let row = sqlx::query("select * from labels where id = ?")
1223 .bind(id.as_str())
1224 .fetch_optional(&self.pool)
1225 .await
1226 .map_err(backend)?;
1227
1228 Ok(row.as_ref().map(Self::hydrate))
1229 }
1230
1231 async fn find_by_name(&self, repo_id: &RepoId, name: &str) -> RepositoryResult<Option<Label>> {
1232 let row = sqlx::query("select * from labels where repo_id = ? and name = ?")
1233 .bind(repo_id.as_str())
1234 .bind(name)
1235 .fetch_optional(&self.pool)
1236 .await
1237 .map_err(backend)?;
1238
1239 Ok(row.as_ref().map(Self::hydrate))
1240 }
1241
1242 async fn save(&self, label: &Label) -> RepositoryResult<()> {
1243 // `repo_id` is absent from the update list on purpose: a label belongs to the
1244 // repository it was made on, and moving one would take it off every issue that
1245 // wears it without saying so.
1246 sqlx::query(
1247 "insert into labels (id, repo_id, name, colour, description, created_at)
1248 values (?, ?, ?, ?, ?, ?)
1249 on conflict (id) do update set
1250 name = excluded.name,
1251 colour = excluded.colour,
1252 description = excluded.description",
1253 )
1254 .bind(label.id.as_str())
1255 .bind(label.repo_id.as_str())
1256 .bind(&label.name)
1257 .bind(label.colour.as_str())
1258 .bind(label.description.as_deref())
1259 .bind(to_unix(label.created_at))
1260 .execute(&self.pool)
1261 .await
1262 .map_err(backend)?;
1263
1264 Ok(())
1265 }
1266
1267 async fn delete(&self, id: &LabelId) -> RepositoryResult<()> {
1268 // The assignments go with it through both join tables' `on delete cascade`, which
1269 // the connection enables foreign keys for — see `database::connect`.
1270 sqlx::query("delete from labels where id = ?")
1271 .bind(id.as_str())
1272 .execute(&self.pool)
1273 .await
1274 .map_err(backend)?;
1275
1276 Ok(())
1277 }
1278
1279 async fn labels_for_issue(&self, issue_id: &IssueId) -> RepositoryResult<Vec<Label>> {
1280 let rows = sqlx::query(
1281 "select labels.* from labels
1282 join issue_labels on issue_labels.label_id = labels.id
1283 where issue_labels.issue_id = ?
1284 order by labels.name asc",
1285 )
1286 .bind(issue_id.as_str())
1287 .fetch_all(&self.pool)
1288 .await
1289 .map_err(backend)?;
1290
1291 Ok(rows.iter().map(Self::hydrate).collect())
1292 }
1293
1294 async fn labels_for_repo(&self, repo_id: &RepoId) -> RepositoryResult<Vec<(IssueId, Label)>> {
1295 // Every pair on the repository in one statement: the list page renders pills on
1296 // every row, and asking per row is a query per row.
1297 let rows = sqlx::query(
1298 "select issue_labels.issue_id as issue_id, labels.* from labels
1299 join issue_labels on issue_labels.label_id = labels.id
1300 where labels.repo_id = ?
1301 order by issue_labels.issue_id asc, labels.name asc",
1302 )
1303 .bind(repo_id.as_str())
1304 .fetch_all(&self.pool)
1305 .await
1306 .map_err(backend)?;
1307
1308 Ok(rows
1309 .iter()
1310 .map(|row| {
1311 (
1312 IssueId::from_trusted(row.get::<String, _>("issue_id")),
1313 Self::hydrate(row),
1314 )
1315 })
1316 .collect())
1317 }
1318
1319 async fn issue_counts(&self, repo_id: &RepoId) -> RepositoryResult<Vec<(LabelId, u64)>> {
1320 // A left join so an unused label still gets a row, for the same reason
1321 // `comment_counts` uses one: the caller builds a lookup, and a missing key and a
1322 // zero would have to be handled identically anyway.
1323 let rows = sqlx::query(
1324 "select labels.id as label_id, count(issue_labels.issue_id) as total
1325 from labels
1326 left join issue_labels on issue_labels.label_id = labels.id
1327 where labels.repo_id = ?
1328 group by labels.id",
1329 )
1330 .bind(repo_id.as_str())
1331 .fetch_all(&self.pool)
1332 .await
1333 .map_err(backend)?;
1334
1335 Ok(rows
1336 .iter()
1337 .map(|row| {
1338 (
1339 LabelId::from_trusted(row.get::<String, _>("label_id")),
1340 row.get::<i64, _>("total").max(0) as u64,
1341 )
1342 })
1343 .collect())
1344 }
1345
1346 async fn set_issue_labels(
1347 &self,
1348 issue_id: &IssueId,
1349 labels: &[LabelId],
1350 ) -> RepositoryResult<()> {
1351 // One transaction, because the delete and the inserts are one replacement: a
1352 // reader that arrived between them would see an issue with no labels at all.
1353 let mut tx = self.pool.begin().await.map_err(backend)?;
1354
1355 sqlx::query("delete from issue_labels where issue_id = ?")
1356 .bind(issue_id.as_str())
1357 .execute(&mut *tx)
1358 .await
1359 .map_err(backend)?;
1360
1361 for label in labels {
1362 // `or ignore` rather than a plain insert: the same label ticked twice in a
1363 // tampered form is the same assignment, not an error.
1364 sqlx::query("insert or ignore into issue_labels (issue_id, label_id) values (?, ?)")
1365 .bind(issue_id.as_str())
1366 .bind(label.as_str())
1367 .execute(&mut *tx)
1368 .await
1369 .map_err(backend)?;
1370 }
1371
1372 tx.commit().await.map_err(backend)?;
1373
1374 Ok(())
1375 }
1376
1377 async fn labels_for_pull(&self, pull_id: &PullRequestId) -> RepositoryResult<Vec<Label>> {
1378 let rows = sqlx::query(
1379 "select labels.* from labels
1380 join pull_request_labels on pull_request_labels.label_id = labels.id
1381 where pull_request_labels.pull_request_id = ?
1382 order by labels.name asc",
1383 )
1384 .bind(pull_id.as_str())
1385 .fetch_all(&self.pool)
1386 .await
1387 .map_err(backend)?;
1388
1389 Ok(rows.iter().map(Self::hydrate).collect())
1390 }
1391
1392 async fn labels_for_repo_pulls(
1393 &self,
1394 repo_id: &RepoId,
1395 ) -> RepositoryResult<Vec<(PullRequestId, Label)>> {
1396 let rows = sqlx::query(
1397 "select pull_request_labels.pull_request_id as pull_request_id, labels.* from labels
1398 join pull_request_labels on pull_request_labels.label_id = labels.id
1399 where labels.repo_id = ?
1400 order by pull_request_labels.pull_request_id asc, labels.name asc",
1401 )
1402 .bind(repo_id.as_str())
1403 .fetch_all(&self.pool)
1404 .await
1405 .map_err(backend)?;
1406
1407 Ok(rows
1408 .iter()
1409 .map(|row| {
1410 (
1411 PullRequestId::from_trusted(row.get::<String, _>("pull_request_id")),
1412 Self::hydrate(row),
1413 )
1414 })
1415 .collect())
1416 }
1417
1418 async fn pull_counts(&self, repo_id: &RepoId) -> RepositoryResult<Vec<(LabelId, u64)>> {
1419 let rows = sqlx::query(
1420 "select labels.id as label_id,
1421 count(pull_request_labels.pull_request_id) as total
1422 from labels
1423 left join pull_request_labels on pull_request_labels.label_id = labels.id
1424 where labels.repo_id = ?
1425 group by labels.id",
1426 )
1427 .bind(repo_id.as_str())
1428 .fetch_all(&self.pool)
1429 .await
1430 .map_err(backend)?;
1431
1432 Ok(rows
1433 .iter()
1434 .map(|row| {
1435 (
1436 LabelId::from_trusted(row.get::<String, _>("label_id")),
1437 row.get::<i64, _>("total").max(0) as u64,
1438 )
1439 })
1440 .collect())
1441 }
1442
1443 async fn set_pull_labels(
1444 &self,
1445 pull_id: &PullRequestId,
1446 labels: &[LabelId],
1447 ) -> RepositoryResult<()> {
1448 // One transaction, for the reason `set_issue_labels` gives.
1449 let mut tx = self.pool.begin().await.map_err(backend)?;
1450
1451 sqlx::query("delete from pull_request_labels where pull_request_id = ?")
1452 .bind(pull_id.as_str())
1453 .execute(&mut *tx)
1454 .await
1455 .map_err(backend)?;
1456
1457 for label in labels {
1458 sqlx::query(
1459 "insert or ignore into pull_request_labels (pull_request_id, label_id)
1460 values (?, ?)",
1461 )
1462 .bind(pull_id.as_str())
1463 .bind(label.as_str())
1464 .execute(&mut *tx)
1465 .await
1466 .map_err(backend)?;
1467 }
1468
1469 tx.commit().await.map_err(backend)?;
1470
1471 Ok(())
1472 }
1473}
1474
1475#[derive(Debug, Clone)]
1476pub struct SqlitePullRequestRepo {
1477 pool: SqlitePool,
1478}
1479
1480impl SqlitePullRequestRepo {
1481 pub fn new(pool: SqlitePool) -> Self {
1482 Self { pool }
1483 }
1484
1485 /// `from_trusted` throughout, including both branch names: they were valid
1486 /// [`RefName`]s on the way in, and re-validating them here would turn a tightened
1487 /// rule into unreadable rows.
1488 fn hydrate(row: &SqliteRow) -> PullRequest {
1489 PullRequest::from_trusted(
1490 PullRequestId::from_trusted(row.get::<String, _>("id")),
1491 RepoId::from_trusted(row.get::<String, _>("repo_id")),
1492 IssueNumber::from_trusted(row.get::<i64, _>("number").max(1) as u64),
1493 row.get::<String, _>("title"),
1494 row.get::<String, _>("body"),
1495 // The one stored value that is parsed rather than trusted, for the reason
1496 // `SqliteIssueRepo` parses a state: `PullRequestState` has no
1497 // `from_trusted`, and there is nothing sensible to reconstruct an unknown
1498 // state as. Falling back to `Open` and not to `Merged` is deliberate — a
1499 // row that cannot be read must not claim something landed.
1500 row.get::<String, _>("state")
1501 .parse()
1502 .unwrap_or(PullRequestState::Open),
1503 UserId::from_trusted(row.get::<String, _>("author_id")),
1504 RefName::from_trusted(row.get::<String, _>("source_branch")),
1505 RefName::from_trusted(row.get::<String, _>("target_branch")),
1506 from_unix(row.get::<i64, _>("created_at")),
1507 from_unix(row.get::<i64, _>("updated_at")),
1508 row.get::<Option<i64>, _>("closed_at").map(from_unix),
1509 row.get::<Option<i64>, _>("merged_at").map(from_unix),
1510 row.get::<Option<String>, _>("merge_commit")
1511 .map(ObjectId::from_trusted),
1512 )
1513 }
1514
1515 fn hydrate_comment(row: &SqliteRow) -> PullRequestComment {
1516 PullRequestComment::from_trusted(
1517 PullRequestCommentId::from_trusted(row.get::<String, _>("id")),
1518 PullRequestId::from_trusted(row.get::<String, _>("pull_request_id")),
1519 UserId::from_trusted(row.get::<String, _>("author_id")),
1520 row.get::<String, _>("body"),
1521 from_unix(row.get::<i64, _>("created_at")),
1522 )
1523 }
1524}
1525
1526impl PullRequestRepository for SqlitePullRequestRepo {
1527 async fn find_by_number(
1528 &self,
1529 repo_id: &RepoId,
1530 number: IssueNumber,
1531 ) -> RepositoryResult<Option<PullRequest>> {
1532 let row = sqlx::query("select * from pull_requests where repo_id = ? and number = ?")
1533 .bind(repo_id.as_str())
1534 .bind(number.get() as i64)
1535 .fetch_optional(&self.pool)
1536 .await
1537 .map_err(backend)?;
1538
1539 Ok(row.as_ref().map(Self::hydrate))
1540 }
1541
1542 async fn list_by_repo(
1543 &self,
1544 repo_id: &RepoId,
1545 state: PullRequestState,
1546 offset: usize,
1547 limit: usize,
1548 ) -> RepositoryResult<Vec<PullRequest>> {
1549 // Descending number rather than descending `created_at`, exactly as the issue
1550 // list does: the sequence is monotonic, so it orders identically, cannot tie,
1551 // and makes `limit`/`offset` stable across pages.
1552 let rows = sqlx::query(
1553 "select * from pull_requests where repo_id = ? and state = ?
1554 order by number desc
1555 limit ? offset ?",
1556 )
1557 .bind(repo_id.as_str())
1558 .bind(state.as_str())
1559 .bind(i64::try_from(limit).unwrap_or(i64::MAX))
1560 .bind(i64::try_from(offset).unwrap_or(i64::MAX))
1561 .fetch_all(&self.pool)
1562 .await
1563 .map_err(backend)?;
1564
1565 Ok(rows.iter().map(Self::hydrate).collect())
1566 }
1567
1568 async fn counts(&self, repo_id: &RepoId) -> RepositoryResult<PullRequestCounts> {
1569 let rows = sqlx::query(
1570 "select state, count(*) as total from pull_requests where repo_id = ? group by state",
1571 )
1572 .bind(repo_id.as_str())
1573 .fetch_all(&self.pool)
1574 .await
1575 .map_err(backend)?;
1576
1577 let mut counts = PullRequestCounts::default();
1578
1579 for row in &rows {
1580 let total = row.get::<i64, _>("total").max(0) as u64;
1581
1582 match row.get::<String, _>("state").parse() {
1583 Ok(PullRequestState::Open) => counts.open = total,
1584 Ok(PullRequestState::Merged) => counts.merged = total,
1585 Ok(PullRequestState::Closed) => counts.closed = total,
1586 // A state neither implementation can name is counted as none of them.
1587 // It would take a hand-edited row to reach this.
1588 Err(_) => {}
1589 }
1590 }
1591
1592 Ok(counts)
1593 }
1594
1595 async fn comment_counts(
1596 &self,
1597 repo_id: &RepoId,
1598 ) -> RepositoryResult<Vec<(PullRequestId, u64)>> {
1599 // A left join so a request with no comments still gets a row: the caller builds
1600 // a lookup out of this, and a missing key and a zero would be handled alike.
1601 let rows = sqlx::query(
1602 "select pull_requests.id as pull_id, count(pull_request_comments.id) as total
1603 from pull_requests
1604 left join pull_request_comments
1605 on pull_request_comments.pull_request_id = pull_requests.id
1606 where pull_requests.repo_id = ?
1607 group by pull_requests.id",
1608 )
1609 .bind(repo_id.as_str())
1610 .fetch_all(&self.pool)
1611 .await
1612 .map_err(backend)?;
1613
1614 Ok(rows
1615 .iter()
1616 .map(|row| {
1617 (
1618 PullRequestId::from_trusted(row.get::<String, _>("pull_id")),
1619 row.get::<i64, _>("total").max(0) as u64,
1620 )
1621 })
1622 .collect())
1623 }
1624
1625 async fn save(&self, pull: &PullRequest) -> RepositoryResult<()> {
1626 // `number`, `repo_id`, `author_id` and both branches are absent from the update
1627 // list on purpose. The first three for the reason an issue's are — identity is
1628 // the number on the repository — and the branches because changing either would
1629 // make every comment on the request an opinion about a different change.
1630 sqlx::query(
1631 "insert into pull_requests
1632 (id, repo_id, number, title, body, state, author_id, source_branch,
1633 target_branch, created_at, updated_at, closed_at, merged_at, merge_commit)
1634 values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1635 on conflict (id) do update set
1636 title = excluded.title,
1637 body = excluded.body,
1638 state = excluded.state,
1639 updated_at = excluded.updated_at,
1640 closed_at = excluded.closed_at,
1641 merged_at = excluded.merged_at,
1642 merge_commit = excluded.merge_commit",
1643 )
1644 .bind(pull.id.as_str())
1645 .bind(pull.repo_id.as_str())
1646 .bind(pull.number.get() as i64)
1647 .bind(&pull.title)
1648 .bind(&pull.body)
1649 .bind(pull.state.as_str())
1650 .bind(pull.author_id.as_str())
1651 .bind(pull.source_branch.as_str())
1652 .bind(pull.target_branch.as_str())
1653 .bind(to_unix(pull.created_at))
1654 .bind(to_unix(pull.updated_at))
1655 .bind(pull.closed_at.map(to_unix))
1656 .bind(pull.merged_at.map(to_unix))
1657 .bind(pull.merge_commit.as_ref().map(ObjectId::as_str))
1658 .execute(&self.pool)
1659 .await
1660 .map_err(backend)?;
1661
1662 Ok(())
1663 }
1664
1665 async fn list_comments(
1666 &self,
1667 pull_request_id: &PullRequestId,
1668 ) -> RepositoryResult<Vec<PullRequestComment>> {
1669 // `rowid` breaks a tie, which is insertion order — two comments posted in the
1670 // same second read in the order they were written. The id would not do: it is a
1671 // random UUID, so a conversation would occasionally read backwards.
1672 let rows = sqlx::query(
1673 "select * from pull_request_comments where pull_request_id = ?
1674 order by created_at asc, rowid asc",
1675 )
1676 .bind(pull_request_id.as_str())
1677 .fetch_all(&self.pool)
1678 .await
1679 .map_err(backend)?;
1680
1681 Ok(rows.iter().map(Self::hydrate_comment).collect())
1682 }
1683
1684 async fn add_comment(&self, comment: &PullRequestComment) -> RepositoryResult<()> {
1685 sqlx::query(
1686 "insert into pull_request_comments
1687 (id, pull_request_id, author_id, body, created_at)
1688 values (?, ?, ?, ?, ?)",
1689 )
1690 .bind(comment.id.as_str())
1691 .bind(comment.pull_request_id.as_str())
1692 .bind(comment.author_id.as_str())
1693 .bind(&comment.body)
1694 .bind(to_unix(comment.created_at))
1695 .execute(&self.pool)
1696 .await
1697 .map_err(backend)?;
1698
1699 Ok(())
1700 }
1701}
1702
1703// --- Password resets ---------------------------------------------------------------
1704
1705#[derive(Debug, Clone)]
1706pub struct SqlitePasswordResetRepo {
1707 pool: SqlitePool,
1708}
1709
1710impl SqlitePasswordResetRepo {
1711 pub fn new(pool: SqlitePool) -> Self {
1712 Self { pool }
1713 }
1714
1715 /// `from_trusted`, like every other adapter here.
1716 fn hydrate(row: &SqliteRow) -> PasswordReset {
1717 PasswordReset::from_trusted(
1718 ResetId::from_trusted(row.get::<String, _>("id")),
1719 UserId::from_trusted(row.get::<String, _>("user_id")),
1720 ResetHash::from_trusted(row.get::<String, _>("token_hash")),
1721 from_unix(row.get::<i64, _>("created_at")),
1722 from_unix(row.get::<i64, _>("expires_at")),
1723 row.get::<Option<i64>, _>("used_at").map(from_unix),
1724 )
1725 }
1726}
1727
1728impl PasswordResetRepository for SqlitePasswordResetRepo {
1729 async fn find_by_hash(&self, hash: &ResetHash) -> RepositoryResult<Option<PasswordReset>> {
1730 // Matched with `=` for the reason `SqliteTokenRepo::find_by_hash` gives: this is
1731 // a digest, and the constant-time comparison guards the value that arrived in the
1732 // URL, which never reaches the database.
1733 let row = sqlx::query("select * from password_resets where token_hash = ?")
1734 .bind(hash.as_str())
1735 .fetch_optional(&self.pool)
1736 .await
1737 .map_err(backend)?;
1738
1739 Ok(row.as_ref().map(Self::hydrate))
1740 }
1741
1742 async fn save(&self, reset: &PasswordReset) -> RepositoryResult<()> {
1743 sqlx::query(
1744 "insert into password_resets
1745 (id, user_id, token_hash, created_at, expires_at, used_at)
1746 values (?, ?, ?, ?, ?, ?)",
1747 )
1748 .bind(reset.id.as_str())
1749 .bind(reset.user_id.as_str())
1750 .bind(reset.token_hash.as_str())
1751 .bind(to_unix(reset.created_at))
1752 .bind(to_unix(reset.expires_at))
1753 .bind(reset.used_at.map(to_unix))
1754 .execute(&self.pool)
1755 .await
1756 .map_err(backend)?;
1757
1758 Ok(())
1759 }
1760
1761 async fn mark_used(&self, id: &ResetId, at: SystemTime) -> RepositoryResult<()> {
1762 // `used_at is null` in the predicate, not just the id: spending a link twice must
1763 // not move the moment it was first spent, and the race that would do it is two
1764 // submissions of the same form.
1765 sqlx::query("update password_resets set used_at = ? where id = ? and used_at is null")
1766 .bind(to_unix(at))
1767 .bind(id.as_str())
1768 .execute(&self.pool)
1769 .await
1770 .map_err(backend)?;
1771
1772 Ok(())
1773 }
1774
1775 async fn invalidate_for_user(&self, user_id: &UserId, at: SystemTime) -> RepositoryResult<u64> {
1776 let result = sqlx::query(
1777 "update password_resets set used_at = ? where user_id = ? and used_at is null",
1778 )
1779 .bind(to_unix(at))
1780 .bind(user_id.as_str())
1781 .execute(&self.pool)
1782 .await
1783 .map_err(backend)?;
1784
1785 Ok(result.rows_affected())
1786 }
1787}
1788
1789#[cfg(test)]
1790#[path = "sqlite_tests.rs"]
1791mod tests;