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