-
Notifications
You must be signed in to change notification settings - Fork 2
/
models.go
75 lines (65 loc) · 1.68 KB
/
models.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
67
68
69
70
71
72
73
74
75
package main
import (
"fmt"
"time"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
)
// Vote represents a MNO vote object and is a model for the ORM.
type Vote struct {
// Unique indexes are ideal, but add more logic to the program. So we'll leave this dumb and
// use a query to pull the most recent votes (only) per MN address instead.
Address string `json:"addr"`
Message string `json:"msg"`
Signature string `json:"sig"`
CreatedAt time.Time `json:"ts"`
}
// String implements the Stringer interface for Vote
func (v Vote) String() string {
return fmt.Sprintf(
"Vote<%s %s %s %v>",
v.Address,
v.Message,
v.Signature,
v.CreatedAt.UTC().Format(time.RFC3339),
)
}
// createSchema makes the DB tables if they don't exist
func createSchema(db *pg.DB) error {
for _, model := range []interface{}{(*Vote)(nil)} {
err := db.CreateTable(model, &orm.CreateTableOptions{
IfNotExists: true,
})
if err != nil {
return err
}
}
return nil
}
// getCurrentVotesOnly returns a list of the latest votes for each address
func getCurrentVotesOnly(db *pg.DB) ([]Vote, error) {
countingVotes := []Vote{}
query := `
select distinct t.address
, t.message
, t.signature
, t.created_at
from votes t
inner join (
select address
, max(created_at) as maxdate
from votes
group by address
) tm
on t.address = tm.address
and t.created_at = tm.maxdate
`
_, err := db.Query(&countingVotes, query)
return countingVotes, err
}
// getAllVotes returns a list of all votes in the database
func getAllVotes(db *pg.DB) ([]Vote, error) {
votes := []Vote{}
err := db.Model(&votes).Select()
return votes, err
}