-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
tag.go
107 lines (93 loc) · 1.83 KB
/
tag.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
101
102
103
104
105
106
107
package store
import (
"context"
"database/sql"
"strings"
)
type Tag struct {
Name string
CreatorID int32
}
type FindTag struct {
CreatorID int32
}
type DeleteTag struct {
Name string
CreatorID int32
}
func (s *Store) UpsertTag(ctx context.Context, upsert *Tag) (*Tag, error) {
stmt := `
INSERT INTO tag (
name, creator_id
)
VALUES (?, ?)
ON CONFLICT(name, creator_id) DO UPDATE
SET
name = EXCLUDED.name
`
if _, err := s.db.ExecContext(ctx, stmt, upsert.Name, upsert.CreatorID); err != nil {
return nil, err
}
tag := upsert
return tag, nil
}
func (s *Store) ListTags(ctx context.Context, find *FindTag) ([]*Tag, error) {
where, args := []string{"creator_id = ?"}, []any{find.CreatorID}
query := `
SELECT
name,
creator_id
FROM tag
WHERE ` + strings.Join(where, " AND ") + `
ORDER BY name ASC
`
rows, err := s.db.QueryContext(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
list := []*Tag{}
for rows.Next() {
tag := &Tag{}
if err := rows.Scan(
&tag.Name,
&tag.CreatorID,
); err != nil {
return nil, err
}
list = append(list, tag)
}
if err := rows.Err(); err != nil {
return nil, err
}
return list, nil
}
func (s *Store) DeleteTag(ctx context.Context, delete *DeleteTag) error {
where, args := []string{"name = ?", "creator_id = ?"}, []any{delete.Name, delete.CreatorID}
stmt := `DELETE FROM tag WHERE ` + strings.Join(where, " AND ")
result, err := s.db.ExecContext(ctx, stmt, args...)
if err != nil {
return err
}
if _, err = result.RowsAffected(); err != nil {
return err
}
return nil
}
func vacuumTag(ctx context.Context, tx *sql.Tx) error {
stmt := `
DELETE FROM
tag
WHERE
creator_id NOT IN (
SELECT
id
FROM
user
)`
_, err := tx.ExecContext(ctx, stmt)
if err != nil {
return err
}
return nil
}