forked from
tangled.org/core
Monorepo for Tangled
1package db
2
3import (
4 "context"
5
6 "github.com/bluesky-social/indigo/atproto/syntax"
7
8 "tangled.org/core/appview/models"
9)
10
11const EntityStateBackfillName = "backfill-entity-state"
12
13type BackfillSubject struct {
14 Subject syntax.ATURI
15 Value models.StateValue
16 CreatedAt string
17}
18
19func EnqueueEntityStateBackfill(ctx context.Context, e Execer) (int64, error) {
20 res, err := e.ExecContext(ctx, `
21 insert into pds_migration (name, did, collection, rkey)
22 select distinct ?, r.did, '', ''
23 from repos r
24 where r.did like 'did:%'
25 and (
26 exists (
27 select 1 from issues i
28 where i.repo_did = r.repo_did and i.open = 0 and i.deleted is null and i.rkey != ''
29 and not exists (select 1 from issue_states s where s.subject = i.at_uri)
30 )
31 or exists (
32 select 1 from pulls p
33 where p.repo_did = r.repo_did and p.state in (0, 2) and p.rkey != ''
34 and not exists (select 1 from pull_states s where s.subject = p.at_uri)
35 )
36 )
37 on conflict(name, did, collection, rkey) do update set
38 status = 'pending',
39 retry_count = 0,
40 retry_after = 0,
41 error_msg = null
42 where pds_migration.status in ('done', 'failed')
43 `, EntityStateBackfillName)
44 if err != nil {
45 return 0, err
46 }
47 return res.RowsAffected()
48}
49
50func ColumnOnlyClosedSubjectsForOwner(ctx context.Context, e Execer, owner syntax.DID) ([]BackfillSubject, error) {
51 rows, err := e.QueryContext(ctx, `
52 select i.at_uri, ?, i.created
53 from issues i join repos r on i.repo_did = r.repo_did
54 where r.did = ? and i.open = 0 and i.deleted is null and i.rkey != ''
55 and not exists (select 1 from issue_states s where s.subject = i.at_uri)
56 union all
57 select p.at_uri, case p.state when 2 then ? else ? end, p.created
58 from pulls p join repos r on p.repo_did = r.repo_did
59 where r.did = ? and p.state in (0, 2) and p.rkey != ''
60 and not exists (select 1 from pull_states s where s.subject = p.at_uri)
61 `,
62 string(models.StateClosed),
63 owner,
64 string(models.StateMerged), string(models.StateClosed),
65 owner,
66 )
67 if err != nil {
68 return nil, err
69 }
70 defer rows.Close()
71
72 var subjects []BackfillSubject
73 for rows.Next() {
74 var subject, value, created string
75 if err := rows.Scan(&subject, &value, &created); err != nil {
76 return nil, err
77 }
78 subjects = append(subjects, BackfillSubject{
79 Subject: syntax.ATURI(subject),
80 Value: models.StateValue(value),
81 CreatedAt: created,
82 })
83 }
84 return subjects, rows.Err()
85}