From sqlx to db - golang ORMs
Short post -- ended up switching from sqlx to db.v3 since I felt that the sqlx layer was more likely to be error prone.
db.v3 example
1func (u *UserService) UpdateUser(user *model.User, args struct {
2 Name *string
3 Email *string
4 Password *string
5}) (*model.User, error) {
6 update := make(map[string]interface{})
7
8 if args.Password != nil {
9 user.HashPassword(*args.Password)
10 update["password"] = user.Password
11 }
12 if args.Name != nil && *args.Name != user.Name {
13 update["name"] = *args.Name
14 }
15 if args.Email != nil && *args.Email != user.Email {
16 update["email"] = *args.Email
17 }
18
19 if len(update) == 0 {
20 return user, nil
21 }
22 update["updated_at"] = "NOW()"
23
24 err := u.db.Collection("users")
25 .Find(db.Cond{"id": user.ID}).Update(update)
26
27 if err != nil {
28 return user, err
29 }
30
31 return user, nil
32}
sqlx example
1func (u *UserService) UpdateUser(user *model.User, args struct {
2 Name *string
3 Email *string
4 Password *string
5}) (*model.User, error) {
6 update := []string{}
7
8 if args.Password != nil {
9 user.HashPassword(*args.Password)
10 update = append(update, "password = :password")
11 }
12 if args.Name != nil && *args.Name != user.Name {
13 update = append(update, "name = :name")
14 }
15 if args.Email != nil && *args.Email != user.Email {
16 update = append(update, "email = :email")
17 }
18
19 if len(update) == 0 {
20 return user, nil
21 }
22
23 _, err := u.db.NamedExec(
24 fmt.Sprintf(`UPDATE users SET %s, updated_at = NOW() WHERE = :id`,
25 strings.Join(",", update)), user);
26
27 if err != nil {
28 return user, err
29 }
30
31 return user, nil
32}