/
useracc_repository.go
64 lines (53 loc) · 1.8 KB
/
useracc_repository.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
package useracc
import (
"database/sql"
"fmt"
"github.com/ccthomas/gridiron/pkg/logger"
"go.uber.org/zap"
)
type UserAccountRepositoryImpl struct {
DB *sql.DB
}
func NewUserAccountRepository(db *sql.DB) *UserAccountRepositoryImpl {
logger.Get().Debug("Construct new user account repository.")
return &UserAccountRepositoryImpl{
DB: db,
}
}
func (r *UserAccountRepositoryImpl) InsertUserAccount(userAccount UserAccount) error {
logger.Get().Debug("Insert user account.")
stmt, err := r.DB.Prepare("INSERT INTO user_account.user_account (id, username, password_hash) VALUES ($1, $2, $3)")
if err != nil {
return err
}
defer stmt.Close()
logger.Get().Debug("Execute the SQL statement with the user account data.")
_, err = stmt.Exec(userAccount.Id, userAccount.Username, userAccount.PasswordHash)
if err != nil {
return err
}
logger.Get().Debug("Successfully inserted user account data.")
return nil
}
func (r *UserAccountRepositoryImpl) SelectByUsername(username string) (*UserAccount, error) {
logger.Get().Debug("Select user account by username.")
stmt, err := r.DB.Prepare("SELECT id, username, password_hash FROM user_account.user_account WHERE username = $1")
if err != nil {
return nil, err
}
defer stmt.Close()
logger.Get().Debug("Execute the SQL statement to retrieve the user account data.")
row := stmt.QueryRow(username)
logger.Get().Debug("Scan the data into a user account struct.")
var userAccount UserAccount
err = row.Scan(&userAccount.Id, &userAccount.Username, &userAccount.PasswordHash)
if err != nil {
if err == sql.ErrNoRows {
logger.Get().Debug("User account not found.")
return nil, fmt.Errorf("user account not found")
}
return nil, err
}
logger.Get().Debug("Found user account.", zap.String("Username", userAccount.Username))
return &userAccount, nil
}