-
Notifications
You must be signed in to change notification settings - Fork 0
/
crud.go
97 lines (82 loc) · 1.65 KB
/
crud.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
package db
import (
"context"
"strings"
"github.com/ViBiOh/auth/v2/pkg/model"
"github.com/jackc/pgx/v4"
)
// DoAtomic do things in a transaction
func (a App) DoAtomic(ctx context.Context, action func(context.Context) error) error {
return a.db.DoAtomic(ctx, action)
}
const getByIDQuery = `
SELECT
id,
login
FROM
auth.login
WHERE
id = $1
`
// Get get an user
func (a App) Get(ctx context.Context, id uint64) (model.User, error) {
var item model.User
scanner := func(row pgx.Row) error {
err := row.Scan(&item.ID, &item.Login)
if err == pgx.ErrNoRows {
item = model.User{}
return nil
}
return err
}
return item, a.db.Get(ctx, scanner, getByIDQuery, id)
}
const insertQuery = `
INSERT INTO
auth.login
(
login,
password
) VALUES (
$1,
crypt($2, gen_salt('bf',8))
) RETURNING id
`
// Create an user
func (a App) Create(ctx context.Context, o model.User) (uint64, error) {
return a.db.Create(ctx, insertQuery, strings.ToLower(o.Login), o.Password)
}
const updateQuery = `
UPDATE
auth.login
SET
login = $2
WHERE
id = $1
`
// Update user
func (a App) Update(ctx context.Context, o model.User) error {
return a.db.One(ctx, updateQuery, o.ID, strings.ToLower(o.Login))
}
const updatePasswordQuery = `
UPDATE
auth.login
SET
password = crypt($2, gen_salt('bf',8))
WHERE
id = $1
`
// UpdatePassword of an user
func (a App) UpdatePassword(ctx context.Context, o model.User) error {
return a.db.One(ctx, updatePasswordQuery, o.ID, o.Password)
}
const deleteQuery = `
DELETE FROM
auth.login
WHERE
id = $1
`
// Delete an user
func (a App) Delete(ctx context.Context, o model.User) error {
return a.db.One(ctx, deleteQuery, o.ID)
}