This repository has been archived by the owner on Mar 1, 2023. It is now read-only.
/
postgres.go
225 lines (208 loc) · 6.99 KB
/
postgres.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package postgres
import (
"context"
"database/sql"
"github.com/lib/pq"
"darlinggo.co/pan"
yall "yall.in"
"lockbox.dev/grants"
)
const (
// TestConnStringEnvVar is the name of the environment variable
// to set to the connection string when running tests.
TestConnStringEnvVar = "PG_TEST_DB"
)
// Storer is a PostgreSQL implementation of the Storer
// interface.
type Storer struct {
db *sql.DB
}
// NewStorer returns a PostgreSQL Storer instance that is ready
// to be used as a Storer.
func NewStorer(ctx context.Context, conn *sql.DB) Storer {
return Storer{db: conn}
}
func createGrantSQL(grant Grant) *pan.Query {
return pan.Insert(grant)
}
// CreateGrant inserts the passed Grant into the Storer,
// returning an ErrGrantAlreadyExists error if a Grant
// with the same ID alreday exists in the Storer, or am
// ErrGrantSourceAlreadyExists error if a Grant with the
// same SourceType and SourceID already exists in the Storer.
func (s Storer) CreateGrant(ctx context.Context, grant grants.Grant) error {
query := createGrantSQL(toPostgres(grant))
queryStr, err := query.PostgreSQLString()
if err != nil {
return err
}
_, err = s.db.Exec(queryStr, query.Args()...)
if e, ok := err.(*pq.Error); ok {
if e.Constraint == "grants_pkey" {
err = grants.ErrGrantAlreadyExists
} else if e.Constraint == "grants_source_type_source_id_key" {
err = grants.ErrGrantSourceAlreadyUsed
}
}
return err
}
func exchangeGrantUpdateSQL(g grants.GrantUse) *pan.Query {
var grant Grant
query := pan.New("UPDATE " + pan.Table(grant) + " SET ")
query.Comparison(grant, "Used", "=", true)
query.Comparison(grant, "UseIP", "=", g.IP)
query.Comparison(grant, "UsedAt", "=", g.Time)
query.Flush(", ").Where()
query.Comparison(grant, "ID", "=", g.Grant)
query.Comparison(grant, "Used", "=", false)
return query.Flush(" AND ")
}
func exchangeGrantGetSQL(id string) *pan.Query {
var grant Grant
query := pan.New("SELECT " + pan.Columns(grant).String() + " FROM " + pan.Table(grant))
query.Where()
query.Comparison(grant, "ID", "=", id)
return query.Flush(" ")
}
// ExchangeGrant applies the GrantUse to the Storer, marking
// the Grant in the Storer with an ID matching the Grant
// property of the GrantUse as used and recording metadata
// about the IP and time the Grant was used. If no Grant
// has an ID matching the Grant property of the GrantUse,
// an ErrGrantNotFound error is returned. If the Grant in
// the Storer with an ID matching the Grant propery of the
// GrantUse is already marked as used, an ErrGrantAlreadyUsed
// error will be returned.
func (s Storer) ExchangeGrant(ctx context.Context, g grants.GrantUse) (grants.Grant, error) {
log := yall.FromContext(ctx).WithField("grant", g.Grant)
// exchange the grant
query := exchangeGrantUpdateSQL(g)
queryStr, err := query.PostgreSQLString()
if err != nil {
return grants.Grant{}, err
}
log.WithField("query", queryStr).WithField("query_args", query.Args()).Debug("running update portion of grant exchange query")
result, err := s.db.Exec(queryStr, query.Args()...)
if err != nil {
return grants.Grant{}, err
}
// figure out how many rows exchanging affected
count, err := result.RowsAffected()
if err != nil {
return grants.Grant{}, err
}
log.WithField("rows_affected", count).Debug("successfully executed query")
query = exchangeGrantGetSQL(g.Grant)
queryStr, err = query.PostgreSQLString()
if err != nil {
return grants.Grant{}, err
}
log.WithField("query", queryStr).WithField("query_args", query.Args()).Debug("running get portion of grant exchange query")
rows, err := s.db.Query(queryStr, query.Args()...)
if err != nil {
return grants.Grant{}, err
}
var grant Grant
for rows.Next() {
err = pan.Unmarshal(rows, &grant)
if err != nil {
return fromPostgres(grant), err
}
}
if err = rows.Err(); err != nil {
return fromPostgres(grant), err
}
// if we affected one or more rows, the exchange was
// successfull, return the grant and we're done
if count >= 1 {
return fromPostgres(grant), nil
}
// if we affected fewer than one rows, the grant
// wasn't successful.
// if the grant doesn't exist in the Storer, that's an
// ErrGrantNotFound error
if grant.ID == "" {
return fromPostgres(grant), grants.ErrGrantNotFound
}
// if the grant does exist in the Storer, the only reason
// the exchange wouldn't have used it would be because it
// has already been used. In that case, we want an
// ErrGrantAlreadyUsed error.
return grants.Grant{}, grants.ErrGrantAlreadyUsed
}
func getGrantSQL(id string) *pan.Query {
var grant Grant
query := pan.New("SELECT " + pan.Columns(grant).String() + " FROM " + pan.Table(grant))
query.Where()
query.Comparison(grant, "ID", "=", id)
return query.Flush(" ")
}
// GetGrant retrieves the Grant specified by `id` from the Storer,
// returning an ErrGrantNotFound error if no Grant in the Storer
// has an ID matching `id`.
func (s Storer) GetGrant(ctx context.Context, id string) (grants.Grant, error) {
log := yall.FromContext(ctx).WithField("grant", id)
query := getGrantSQL(id)
queryStr, err := query.PostgreSQLString()
if err != nil {
return grants.Grant{}, err
}
log.WithField("query", queryStr).WithField("query_args", query.Args()).Debug("running get grant query")
rows, err := s.db.Query(queryStr, query.Args()...)
if err != nil {
return grants.Grant{}, err
}
var grant Grant
for rows.Next() {
err = pan.Unmarshal(rows, &grant)
if err != nil {
return fromPostgres(grant), err
}
}
if err = rows.Err(); err != nil {
return fromPostgres(grant), err
}
if grant.ID == "" {
return fromPostgres(grant), grants.ErrGrantNotFound
}
return fromPostgres(grant), nil
}
func getGrantBySourceSQL(sourceType, sourceID string) *pan.Query {
var grant Grant
query := pan.New("SELECT " + pan.Columns(grant).String() + " FROM " + pan.Table(grant))
query.Where()
query.Comparison(grant, "SourceType", "=", sourceType)
query.Comparison(grant, "SourceID", "=", sourceID)
return query.Flush(" AND ")
}
// GetGrantBySource retrieves the Grant specified by `sourceType` and
// `sourceID` from the Storer, returning an ErrGrantNotFound error if no Grant
// in the Storer has a SourceType and SourceID matching those parameters.
func (s Storer) GetGrantBySource(ctx context.Context, sourceType, sourceID string) (grants.Grant, error) {
log := yall.FromContext(ctx).WithField("source_type", sourceType)
log = log.WithField("source_id", sourceID)
query := getGrantBySourceSQL(sourceType, sourceID)
queryStr, err := query.PostgreSQLString()
if err != nil {
return grants.Grant{}, err
}
log.WithField("query", queryStr).WithField("query_args", query.Args()).Debug("running get grant by source query")
rows, err := s.db.Query(queryStr, query.Args()...)
if err != nil {
return grants.Grant{}, err
}
var grant Grant
for rows.Next() {
err = pan.Unmarshal(rows, &grant)
if err != nil {
return fromPostgres(grant), err
}
}
if err = rows.Err(); err != nil {
return fromPostgres(grant), err
}
if grant.ID == "" {
return fromPostgres(grant), grants.ErrGrantNotFound
}
return fromPostgres(grant), nil
}