Skip to content

Go勉強会第5回課題 #35

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions db/database_sql/interfaces/controllers/user_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,27 @@ func NewUserController(db *sql.DB) *UserController {
return &UserController{db: db}
}

// Update is a function for updating a user.
func (controller *UserController) Update(id string, firstName string, lastName string) (err error) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Named Return Value使えてて良い感じです。

identifier, err := strconv.Atoi(id)
if err != nil {
return
}

user := domain.User{
ID: identifier,
FirstName: firstName,
LastName: lastName,
}

err = database.Update(controller.db, user)
if err != nil {
return
}

return
}

// Create is a function for creating a user.
func (controller *UserController) Create(firstName string, lastName string) (*domain.User, error) {
user := domain.User{
Expand Down
9 changes: 9 additions & 0 deletions db/database_sql/interfaces/database/user_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@ import (
"github.com/mf-sakura/golang_study/db/database_sql/domain"
)

// Update is a function for updating a user
func Update(db *sql.DB, u domain.User) (err error) {
_, err = db.Exec(
"update users set first_name = ?, last_name = ? where id = ?", u.FirstName, u.LastName, u.ID,
)

return
}

// Store is a function for creating a user.
func Store(db *sql.DB, u domain.User) (int, error) {
// `?`はmysqlのplaceholder
Expand Down
17 changes: 17 additions & 0 deletions db/database_sql/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,23 @@ func main() {
}
fmt.Printf("ID: %v, FirstName: %v, LastName: %v\n", user.ID, user.FirstName, user.LastName)
return
// ユーザー更新
case "update":
if *id == "" {
log.Fatal("You need a user.id.")
}
if *firstName == "" {
log.Fatal("You need a first name.")
}
if *lastName == "" {
log.Fatal("You need a last name.")
}
err := userController.Update(*id, *firstName, *lastName)
if err != nil {
log.Fatal(err)
}
fmt.Printf("ID: %v, FirstName: %v, LastName: %v\n", *id, *firstName, *lastName)
return
default:
log.Fatal("Unrecognized option.")
}
Expand Down