Repository navigation
Expand file tree
/
Copy pathupdate_usernames.go
More file actions
121 lines (101 loc) · 2.44 KB
/
Copy pathupdate_usernames.go
File metadata and controls
121 lines (101 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package github
import (
"context"
"log"
"github.com/vinovest/sqlx"
)
// Updates the usernames of every GitHub connection.
func updateUsernames(db *sqlx.DB) (limits []rateLimit, err error) {
const batchSize = 100 // GitHub limits us to 100 nodes per query.
var ids []string
rows, err := db.Query(
`SELECT encode(('04:User' || id)::bytea, 'base64')
FROM connections WHERE connection = 'github'`,
)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var id string
if err := rows.Scan(&id); err != nil {
return nil, err
}
ids = append(ids, id)
if len(ids) == batchSize {
if limit, err := updateUsernamesBatch(db, ids); err != nil {
return nil, err
} else {
limits = append(limits, *limit)
}
ids = []string{}
}
}
if len(ids) > 0 {
if limit, err := updateUsernamesBatch(db, ids); err != nil {
return nil, err
} else {
limits = append(limits, *limit)
}
}
return limits, rows.Err()
}
func updateUsernamesBatch(db *sqlx.DB, ids []string) (*rateLimit, error) {
var query struct {
RateLimit rateLimit
Nodes []struct {
User struct {
DatabaseID int
Login string
} `graphql:"... on User"`
} `graphql:"nodes(ids: $ids)"`
}
if err := client.Query(
context.Background(),
&query,
map[string]any{"ids": ids},
); err != nil {
// Log GraphQL errors, they're not fatal.
log.Print(err)
}
updateConn, err := db.Prepare(
`WITH old AS (
SELECT username FROM connections
WHERE connection = 'github' AND id = $1
) UPDATE connections SET username = $2
WHERE connection = 'github' AND id = $1
RETURNING (SELECT username FROM old)`,
)
if err != nil {
return nil, err
}
defer updateConn.Close()
updateUser, err := db.Prepare("UPDATE users SET name = $2 WHERE id = $1")
if err != nil {
return nil, err
}
defer updateUser.Close()
for _, node := range query.Nodes {
// Skip unresolved nodes.
if node.User.DatabaseID == 0 {
continue
}
var username string
if err := updateConn.QueryRow(
node.User.DatabaseID, node.User.Login,
).Scan(&username); err != nil {
return nil, err
}
if username != node.User.Login {
log.Printf("%8d: %s → %s\n",
node.User.DatabaseID, username, node.User.Login)
// Also update users, ATM they match the GitHub connection.
if _, err := updateUser.Exec(
node.User.DatabaseID, node.User.Login,
); err != nil {
return nil, err
}
}
}
return &query.RateLimit, nil
}