-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathvotes.go
More file actions
66 lines (54 loc) · 1.35 KB
/
votes.go
File metadata and controls
66 lines (54 loc) · 1.35 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
package database
import (
"context"
"github.com/jackc/pgx/pgtype"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
"time"
)
type Votes struct {
*pgxpool.Pool
}
func newVotes(db *pgxpool.Pool) *Votes {
return &Votes{
db,
}
}
func (v Votes) Schema() string {
return `
CREATE TABLE IF NOT EXISTS votes(
"user_id" int8 NOT NULL UNIQUE,
"vote_time" timestamp NOT NULL,
PRIMARY KEY("user_id")
);`
}
func (v *Votes) Get(ctx context.Context, userId uint64) (voteTime time.Time, e error) {
query := `SELECT "vote_time" from votes WHERE "user_id" = $1`
if err := v.QueryRow(ctx, query, userId).Scan(&voteTime); err != nil && err != pgx.ErrNoRows {
e = err
}
return
}
func (v *Votes) Any(ctx context.Context, userIds ...uint64) (bool, error) {
query := `
SELECT EXISTS(
SELECT 1
FROM votes
WHERE "user_id" = ANY($1) AND vote_time > NOW() - INTERVAL '24 hours'
);
`
userIdArray := &pgtype.Int8Array{}
if err := userIdArray.Set(userIds); err != nil {
return false, err
}
var res bool
if err := v.QueryRow(ctx, query, userIdArray).Scan(&res); err != nil {
return false, err
}
return res, nil
}
func (v *Votes) Set(ctx context.Context, userId uint64) (err error) {
query := `INSERT INTO votes("user_id", "vote_time") VALUES($1, NOW()) ON CONFLICT("user_id") DO UPDATE SET "vote_time" = NOW();`
_, err = v.Exec(ctx, query, userId)
return
}