/
notification.go
79 lines (69 loc) · 1.64 KB
/
notification.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
76
77
78
79
package eventline
import (
"errors"
"time"
"github.com/galdor/go-service/pkg/pg"
"github.com/jackc/pgx/v5"
)
type Notification struct {
Id Id
ProjectId Id
Recipients []string
Message []byte
NextDeliveryTime time.Time
DeliveryDelay int // seconds
}
func LoadNotificationForDelivery(conn pg.Conn) (*Notification, error) {
now := time.Now().UTC()
query := `
SELECT id, project_id, recipients, message, next_delivery_time,
delivery_delay
FROM notifications
WHERE next_delivery_time < $1
ORDER BY next_delivery_time
LIMIT 1
FOR UPDATE SKIP LOCKED;
`
var n Notification
err := pg.QueryObject(conn, &n, query, now)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
} else if err != nil {
return nil, err
}
return &n, nil
}
func (n *Notification) Insert(conn pg.Conn) error {
query := `
INSERT INTO notifications
(id, project_id, recipients, message, next_delivery_time,
delivery_delay)
VALUES
($1, $2, $3, $4, $5,
$6);
`
return pg.Exec(conn, query,
n.Id, n.ProjectId, n.Recipients, n.Message, n.NextDeliveryTime,
n.DeliveryDelay)
}
func (n *Notification) Update(conn pg.Conn) error {
query := `
UPDATE notifications SET
next_delivery_time = $2,
delivery_delay = $3
WHERE id = $1
`
return pg.Exec(conn, query,
n.Id, n.NextDeliveryTime, n.DeliveryDelay)
}
func (n *Notification) Delete(conn pg.Conn) error {
query := `
DELETE FROM notifications
WHERE id = $1;
`
return pg.Exec(conn, query, n.Id)
}
func (n *Notification) FromRow(row pgx.Row) error {
return row.Scan(&n.Id, &n.ProjectId, &n.Recipients, &n.Message,
&n.NextDeliveryTime, &n.DeliveryDelay)
}