-
Notifications
You must be signed in to change notification settings - Fork 2
/
userdb.go
255 lines (213 loc) · 6.16 KB
/
userdb.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
// Package userdb contains user related CRUD functionality.
package userdb
import (
"bytes"
"context"
"errors"
"fmt"
"net/mail"
"encore.dev/rlog"
"github.com/ardanlabs/encore/business/domain/userbus"
"github.com/ardanlabs/encore/business/sdk/order"
"github.com/ardanlabs/encore/business/sdk/sqldb"
"github.com/ardanlabs/encore/business/sdk/sqldb/dbarray"
"github.com/ardanlabs/encore/business/sdk/transaction"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
)
// Store manages the set of APIs for user database access.
type Store struct {
log rlog.Ctx
db sqlx.ExtContext
}
// NewStore constructs the api for data access.
func NewStore(log rlog.Ctx, db *sqlx.DB) *Store {
return &Store{
log: log,
db: db,
}
}
// NewWithTx constructs a new Store value replacing the sqlx DB
// value with a sqlx DB value that is currently inside a transaction.
func (s *Store) NewWithTx(tx transaction.CommitRollbacker) (userbus.Storer, error) {
ec, err := sqldb.GetExtContext(tx)
if err != nil {
return nil, err
}
store := Store{
log: s.log,
db: ec,
}
return &store, nil
}
// Create inserts a new user into the database.
func (s *Store) Create(ctx context.Context, usr userbus.User) error {
const q = `
INSERT INTO users
(user_id, name, email, password_hash, roles, department, enabled, date_created, date_updated)
VALUES
(:user_id, :name, :email, :password_hash, :roles, :department, :enabled, :date_created, :date_updated)`
if err := sqldb.NamedExecContext(ctx, s.log, s.db, q, toDBUser(usr)); err != nil {
if errors.Is(err, sqldb.ErrDBDuplicatedEntry) {
return fmt.Errorf("namedexeccontext: %w", userbus.ErrUniqueEmail)
}
return fmt.Errorf("namedexeccontext: %w", err)
}
return nil
}
// Update replaces a user document in the database.
func (s *Store) Update(ctx context.Context, usr userbus.User) error {
const q = `
UPDATE
users
SET
"name" = :name,
"email" = :email,
"roles" = :roles,
"password_hash" = :password_hash,
"department" = :department,
"enabled" = :enabled,
"date_updated" = :date_updated
WHERE
user_id = :user_id`
if err := sqldb.NamedExecContext(ctx, s.log, s.db, q, toDBUser(usr)); err != nil {
if errors.Is(err, sqldb.ErrDBDuplicatedEntry) {
return userbus.ErrUniqueEmail
}
return fmt.Errorf("namedexeccontext: %w", err)
}
return nil
}
// Delete removes a user from the database.
func (s *Store) Delete(ctx context.Context, usr userbus.User) error {
data := struct {
ID string `db:"user_id"`
}{
ID: usr.ID.String(),
}
const q = `
DELETE FROM
users
WHERE
user_id = :user_id`
if err := sqldb.NamedExecContext(ctx, s.log, s.db, q, data); err != nil {
return fmt.Errorf("namedexeccontext: %w", err)
}
return nil
}
// Query retrieves a list of existing users from the database.
func (s *Store) Query(ctx context.Context, filter userbus.QueryFilter, orderBy order.By, pageNumber int, rowsPerPage int) ([]userbus.User, error) {
data := map[string]interface{}{
"offset": (pageNumber - 1) * rowsPerPage,
"rows_per_page": rowsPerPage,
}
const q = `
SELECT
user_id, name, email, password_hash, roles, department, enabled, date_created, date_updated
FROM
users`
buf := bytes.NewBufferString(q)
applyFilter(filter, data, buf)
orderByClause, err := orderByClause(orderBy)
if err != nil {
return nil, err
}
buf.WriteString(orderByClause)
buf.WriteString(" OFFSET :offset ROWS FETCH NEXT :rows_per_page ROWS ONLY")
var dbUsrs []user
if err := sqldb.NamedQuerySlice(ctx, s.log, s.db, buf.String(), data, &dbUsrs); err != nil {
return nil, fmt.Errorf("namedqueryslice: %w", err)
}
return toBusUsers(dbUsrs)
}
// Count returns the total number of users in the DB.
func (s *Store) Count(ctx context.Context, filter userbus.QueryFilter) (int, error) {
data := map[string]interface{}{}
const q = `
SELECT
count(1)
FROM
users`
buf := bytes.NewBufferString(q)
applyFilter(filter, data, buf)
var count struct {
Count int `db:"count"`
}
if err := sqldb.NamedQueryStruct(ctx, s.log, s.db, buf.String(), data, &count); err != nil {
return 0, fmt.Errorf("db: %w", err)
}
return count.Count, nil
}
// QueryByID gets the specified user from the database.
func (s *Store) QueryByID(ctx context.Context, userID uuid.UUID) (userbus.User, error) {
data := struct {
ID string `db:"user_id"`
}{
ID: userID.String(),
}
const q = `
SELECT
user_id, name, email, password_hash, roles, department, enabled, date_created, date_updated
FROM
users
WHERE
user_id = :user_id`
var dbUsr user
if err := sqldb.NamedQueryStruct(ctx, s.log, s.db, q, data, &dbUsr); err != nil {
if errors.Is(err, sqldb.ErrDBNotFound) {
return userbus.User{}, fmt.Errorf("db: %w", userbus.ErrNotFound)
}
return userbus.User{}, fmt.Errorf("db: %w", err)
}
return toCoreUser(dbUsr)
}
// QueryByIDs gets the specified users from the database.
func (s *Store) QueryByIDs(ctx context.Context, userIDs []uuid.UUID) ([]userbus.User, error) {
ids := make([]string, len(userIDs))
for i, userID := range userIDs {
ids[i] = userID.String()
}
data := struct {
ID any `db:"user_id"`
}{
ID: dbarray.Array(ids),
}
const q = `
SELECT
user_id, name, email, password_hash, roles, department, enabled, date_created, date_updated
FROM
users
WHERE
user_id = ANY(:user_id)`
var dbUsrs []user
if err := sqldb.NamedQuerySlice(ctx, s.log, s.db, q, data, &dbUsrs); err != nil {
if errors.Is(err, sqldb.ErrDBNotFound) {
return nil, userbus.ErrNotFound
}
return nil, fmt.Errorf("db: %w", err)
}
return toBusUsers(dbUsrs)
}
// QueryByEmail gets the specified user from the database by email.
func (s *Store) QueryByEmail(ctx context.Context, email mail.Address) (userbus.User, error) {
data := struct {
Email string `db:"email"`
}{
Email: email.Address,
}
const q = `
SELECT
user_id, name, email, password_hash, roles, department, enabled, date_created, date_updated
FROM
users
WHERE
email = :email`
var dbUsr user
if err := sqldb.NamedQueryStruct(ctx, s.log, s.db, q, data, &dbUsr); err != nil {
if errors.Is(err, sqldb.ErrDBNotFound) {
return userbus.User{}, fmt.Errorf("db: %w", userbus.ErrNotFound)
}
return userbus.User{}, fmt.Errorf("db: %w", err)
}
return toCoreUser(dbUsr)
}