This repository has been archived by the owner on Mar 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfeeds.go
100 lines (76 loc) · 1.86 KB
/
feeds.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main
import (
"database/sql"
"errors"
"net/url"
"time"
"github.com/lib/pq"
)
type Feed struct {
ID int64
Link string
NotUntil time.Time
}
type Feeds struct {
DB *sql.DB
}
func (f *Feeds) Create(link *url.URL, notUntil time.Time) (*Feed, error) {
stmt := `INSERT INTO feeds (link, not_until) VALUES ($1, $2) RETURNING id, link, not_until`
args := []any{link.String(), notUntil}
var (
created Feed
pqerr *pq.Error
)
err := f.DB.QueryRow(stmt, args...).Scan(&created.ID, &created.Link, &created.NotUntil)
if errors.As(err, &pqerr) && pqerr.Code == uniqueViolation {
err = ErrAlreadyExists
}
if err != nil {
return nil, err
}
return &created, nil
}
func (f *Feeds) ListReady(readyAfter time.Time) ([]Feed, error) {
stmt := `SELECT id, link, not_until FROM feeds WHERE not_until <= $1`
args := []any{readyAfter}
rows, err := f.DB.Query(stmt, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var list []Feed
for rows.Next() {
var f Feed
err := rows.Scan(&f.ID, &f.Link, &f.NotUntil)
if err != nil {
return nil, err
}
list = append(list, f)
}
return list, nil
}
func (f *Feeds) GetByLink(link string) (*Feed, error) {
stmt := `SELECT id, link, not_until FROM feeds WHERE link = $1`
args := []any{link}
var fetched Feed
err := f.DB.QueryRow(stmt, args...).Scan(&fetched.ID, &fetched.Link, &fetched.NotUntil)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, err
}
return &fetched, nil
}
func (f *Feeds) Update(feed *Feed) error {
stmt := `UPDATE feeds SET link = $1, not_until = $2 WHERE id = $3`
args := []any{feed.Link, feed.NotUntil, feed.ID}
_, err := f.DB.Exec(stmt, args...)
return err
}
func (f *Feeds) Delete(id int64) error {
stmt := `DELETE FROM feeds WHERE id = $1`
args := []any{id}
_, err := f.DB.Exec(stmt, args...)
return err
}