/
repo_peer.go
66 lines (51 loc) · 1.58 KB
/
repo_peer.go
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
package repo
import (
"context"
"sort"
"github.com/volatiletech/sqlboiler/v4/boil"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/volatiletech/null/v8"
"github.com/volatiletech/sqlboiler/v4/queries"
"github.com/volatiletech/sqlboiler/v4/types"
"github.com/dennis-tra/optimistic-provide/pkg/db"
"github.com/dennis-tra/optimistic-provide/pkg/models"
)
type PeerRepo interface {
Find(context.Context, peer.ID) (*models.Peer, error)
UpsertPeer(ctx context.Context, exec boil.ContextExecutor, pid peer.ID, av string, protocols []string) (*models.Peer, error)
}
var _ PeerRepo = &Peer{}
type Peer struct {
dbc *db.Client
}
func NewPeerRepo(dbc *db.Client) PeerRepo {
return &Peer{
dbc: dbc,
}
}
func (p *Peer) Find(ctx context.Context, pid peer.ID) (*models.Peer, error) {
return models.Peers(models.PeerWhere.MultiHash.EQ(pid.Pretty())).One(ctx, p.dbc)
}
func (p *Peer) UpsertPeer(ctx context.Context, exec boil.ContextExecutor, pid peer.ID, av string, protocols []string) (*models.Peer, error) {
sort.Strings(protocols)
dbPeer := &models.Peer{
MultiHash: pid.String(),
AgentVersion: null.NewString(av, av != ""),
Protocols: types.StringArray(protocols),
}
var prots interface{} = types.StringArray(protocols)
if len(protocols) == 0 {
prots = nil
}
rows, err := queries.Raw("SELECT upsert_peer($1, $2, $3)", dbPeer.MultiHash, dbPeer.AgentVersion.Ptr(), prots).QueryContext(ctx, exec)
if err != nil {
return nil, err
}
if !rows.Next() {
return nil, rows.Err()
}
if err = rows.Scan(&dbPeer.ID); err != nil {
return nil, err
}
return dbPeer, rows.Close()
}