1package db
2
3import (
4 "fmt"
5 "strings"
6 "time"
7
8 "tangled.org/core/appview/models"
9)
10
11func AddCollaborator(e Execer, c models.Collaborator) error {
12 _, err := e.Exec(
13 `insert into collaborators (did, rkey, subject_did, repo_at) values (?, ?, ?, ?);`,
14 c.Did, c.Rkey, c.SubjectDid, c.RepoAt,
15 )
16 return err
17}
18
19func DeleteCollaborator(e Execer, filters ...filter) error {
20 var conditions []string
21 var args []any
22 for _, filter := range filters {
23 conditions = append(conditions, filter.Condition())
24 args = append(args, filter.Arg()...)
25 }
26
27 whereClause := ""
28 if conditions != nil {
29 whereClause = " where " + strings.Join(conditions, " and ")
30 }
31
32 query := fmt.Sprintf(`delete from collaborators %s`, whereClause)
33
34 _, err := e.Exec(query, args...)
35 return err
36}
37
38func CollaboratingIn(e Execer, collaborator string) ([]models.Repo, error) {
39 rows, err := e.Query(`select repo_at from collaborators where subject_did = ?`, collaborator)
40 if err != nil {
41 return nil, err
42 }
43 defer rows.Close()
44
45 var repoAts []string
46 for rows.Next() {
47 var aturi string
48 err := rows.Scan(&aturi)
49 if err != nil {
50 return nil, err
51 }
52 repoAts = append(repoAts, aturi)
53 }
54 if err := rows.Err(); err != nil {
55 return nil, err
56 }
57 if repoAts == nil {
58 return nil, nil
59 }
60
61 return GetRepos(e, 0, FilterIn("at_uri", repoAts))
62}
63
64func GetCollaborators(e Execer, filters ...filter) ([]models.Collaborator, error) {
65 var collaborators []models.Collaborator
66 var conditions []string
67 var args []any
68 for _, filter := range filters {
69 conditions = append(conditions, filter.Condition())
70 args = append(args, filter.Arg()...)
71 }
72 whereClause := ""
73 if conditions != nil {
74 whereClause = " where " + strings.Join(conditions, " and ")
75 }
76 query := fmt.Sprintf(`select
77 id,
78 did,
79 rkey,
80 subject_did,
81 repo_at,
82 created
83 from collaborators %s`,
84 whereClause,
85 )
86 rows, err := e.Query(query, args...)
87 if err != nil {
88 return nil, err
89 }
90 defer rows.Close()
91 for rows.Next() {
92 var collaborator models.Collaborator
93 var createdAt string
94 if err := rows.Scan(
95 &collaborator.Id,
96 &collaborator.Did,
97 &collaborator.Rkey,
98 &collaborator.SubjectDid,
99 &collaborator.RepoAt,
100 &createdAt,
101 ); err != nil {
102 return nil, err
103 }
104 collaborator.Created, err = time.Parse(time.RFC3339, createdAt)
105 if err != nil {
106 collaborator.Created = time.Now()
107 }
108 collaborators = append(collaborators, collaborator)
109 }
110 if err := rows.Err(); err != nil {
111 return nil, err
112 }
113 return collaborators, nil
114}