-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsql_repository.go
69 lines (58 loc) · 1.58 KB
/
sql_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
65
66
67
68
69
package users
import (
"database/sql"
"time"
)
type userRepoSQL struct {
db *sql.DB
}
// newSQLRepo accepts SQL database instance and return Repostory.
// Note that Put, Upd and Rename methods enforce non-zero timestapms
// of User struct. If either Created or Updated fields are zero time
// values (IsZero() returns true), then they are updated with time.Now()
// Put method also sets Enabled field to true for User struct. Upd
// always sets Updated field to time.Now().
// This way it is safe to actually fill only Name and Secret fields
// of User struct and pass it to Put method.
func newSQLRepo(db *sql.DB) Repository {
return &userRepoSQL{db}
}
func (u *userRepoSQL) Get(username string) (User, error) {
return getUsr(u.db, username)
}
func (u *userRepoSQL) Put(user User) error {
if !isValidUser(&user) {
return ErrValidateUser
}
updateTimestamps(&user)
user.Enabled = true
return putUsr(u.db, &user)
}
func (u *userRepoSQL) Upd(user User) error {
if !isValidUser(&user) {
return ErrValidateUser
}
updateTimestamps(&user)
return updUsr(u.db, &user)
}
func (u *userRepoSQL) Del(username string) error {
return delUsr(u.db, username)
}
func (u *userRepoSQL) Rename(old, new string) error {
return renameUsr(u.db, old, new, time.Now())
}
func (u *userRepoSQL) Close() error {
return u.db.Close()
}
// a bit of enforcement of data integrity
func updateTimestamps(u *User) {
now := time.Now()
if u.Created.IsZero() {
u.Created = now
}
u.Updated = now
}
// thou shalt not ever omit these fields
func isValidUser(u *User) bool {
return u.Username != "" && u.Secret != ""
}