-
Notifications
You must be signed in to change notification settings - Fork 0
/
user_sqlite3.go
95 lines (80 loc) · 2.47 KB
/
user_sqlite3.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
package goserver
import (
"fmt"
"github.com/jmoiron/sqlx"
)
// UserRepoSqlite3 fulfills UserRepo using a Sqlite3 database
type UserRepoSqlite3 struct {
db *sqlx.DB
insertStmt *sqlx.NamedStmt
updatePasswdStmt *sqlx.NamedStmt
getByIDStmt *sqlx.NamedStmt
getByUsernameStmt *sqlx.NamedStmt
}
const (
userInsert = `
INSERT INTO users (username, password, salt)
VALUES (:username, :password, :salt)
`
userUpdatePasswd = `
UPDATE users SET
password=:password,
salt=:salt
WHERE id=:id
`
userSelectBase = `SELECT * FROM users`
userGetByID = userSelectBase + ` WHERE id=:id LIMIT 1`
userGetByUsername = userSelectBase + ` WHERE username=:username LIMIT 1`
)
// NewUserRepoSqlite3 prepares a repo given a sqlite db handle
func NewUserRepoSqlite3(db *sqlx.DB) (*UserRepoSqlite3, error) {
var err error
repo := &UserRepoSqlite3{db: db}
repo.insertStmt, err = db.PrepareNamed(userInsert)
if err != nil {
return repo, fmt.Errorf("Failed to prepare statement `%s`: %v", userInsert, err)
}
repo.updatePasswdStmt, err = db.PrepareNamed(userUpdatePasswd)
if err != nil {
return repo, fmt.Errorf("Failed to prepare statement `%s`: %v", userUpdatePasswd, err)
}
repo.getByIDStmt, err = db.PrepareNamed(userGetByID)
if err != nil {
return repo, fmt.Errorf("Failed to prepare statement `%s`: %v", userGetByID, err)
}
repo.getByUsernameStmt, err = db.PrepareNamed(userGetByUsername)
if err != nil {
return repo, fmt.Errorf("Failed to prepare statement `%s`: %v", userGetByUsername, err)
}
return repo, err
}
// CreateUser tries to insert a user and fills in the ID of the provided user
func (repo *UserRepoSqlite3) CreateUser(s *User) error {
res, err := repo.insertStmt.Exec(s)
if err == nil {
var id int64
id, err = res.LastInsertId()
if err == nil {
s.ID = int(id)
}
}
return err
}
// UpdateUserPasswd attempts to update the given user's corresponding password
// and salt
func (repo *UserRepoSqlite3) UpdateUserPasswd(s *User) (err error) {
_, err = repo.updatePasswdStmt.Exec(s)
return
}
// GetUserByID fills the passed User struct's fields using the ID field, which
// must be filled in
func (repo *UserRepoSqlite3) GetUserByID(s *User) (err error) {
err = repo.getByIDStmt.Get(s, s)
return
}
// GetUserByUsername fills the passed User struct's fields using the username field, which
// must be filled in
func (repo *UserRepoSqlite3) GetUserByUsername(s *User) (err error) {
err = repo.getByUsernameStmt.Get(s, s)
return
}