Skip to content

第5回課題(大倉) #39

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
33 changes: 33 additions & 0 deletions db/api/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
DBNAME:=golang_study
DATASOURCE:=user:password@tcp(127.0.0.1:3314)/$(DBNAME)?parseTime=true

install:
which goose || GO111MODULE=off go get -u github.com/pressly/goose/cmd/goose

docker-compose/up:
docker-compose up -d

setup: .env install migrate/init migrate/up

mysql:
mysql -u user -h 127.0.0.1 --protocol tcp --port 3314 -p $(DBNAME)

migrate/init:
mysql -u user -h 127.0.0.1 --protocol tcp --port 3314 -e "create database if not exists \`$(DBNAME)\` " -p

migrate/status:
goose -dir "db/migrations" mysql "$(DATASOURCE)" status
migrate/up:
goose -dir "db/migrations" mysql "$(DATASOURCE)" up

migrate/down:
goose -dir "db/migrations" mysql "$(DATASOURCE)" down

.env:
cp [email protected] $@

vendor:
go mod vendor

build:
go build -o bin/api
109 changes: 109 additions & 0 deletions db/api/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
# sqlxを使ったCLIツール
https://mf.esa.io/posts/129444

## Table Of Content
- [Setup](#Setup)
- [Command](Command)
- [ユーザー一覧](#ユーザー一覧)
- [ユーザー詳細](#ユーザー詳細)
- [ユーザー作成](#ユーザー作成)
- [DB](#DB)
- [課題](#課題)

## Setup
```sh
$ make docker-compose/up
$ make setup
```

## Command
```sh
Usage of main.go
-a アクション名の指定 (e.g. index, show, create)
-f ユーザーのfirst nameの指定 (actionがcreateの時のみ有効)
-i ユーザーのidの指定 (actionがshowの時のみ有効)
-l ユーザーのlast nameの指定 (actionがcreateの時のみ有効)
```

### ユーザー一覧
```sh
$ ./bin/sqlx -a index
```

### ユーザー作成
```sh
$ ./bin/sqlx -a create -f Alan -l Turing
```

### ユーザー詳細
```sh
$ ./bin/sqlx -a show -i 1
```

### DB
```sh
# mysqlのコンソールに入る
$ make mysql # passwordはそのままpassword

# migrate/up
# railsでいう rails db:migrate
$ make migrate/up

# migrate/down
# railsでいう rails db:rollback
$ make migrate/down
```

# 課題
1. 下記のコマンドを実行した時にユーザーの情報を編集できるようにしてください。
```sh
$ ./bin/sqlx -a update -i [ID] -f [firstName] -l [lastName]
```
2. トランザクションかけてみる。(ここどういう表現にするかちょっと迷い中)
3. 下記のようなAPIサーバーを実装してください。

## GET /users ユーザー一覧
res body
```json
[
{
id: 1,
first_name: "first_name",
last_name: "last_name"
},
{
id: 2,
first_name: "first_name_2",
last_name: "last_name_2"
}
]
```

## GET /users/:id ユーザー詳細
res body
```json
{
id: 1,
first_name: "first_name",
last_name: "last_name"
}
```

## POST /users ユーザー作成
req body
```json
{
first_name: "first_name",
last_name: "last_name"
}
```

## PUT /users/:id ユーザー情報編集
req body
```json
{
id: 1,
first_name: "first_name",
last_name: "last_name"
}
```
12 changes: 12 additions & 0 deletions db/api/db/migrations/20200312232036_CreateUsersTable.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
-- +goose Up
CREATE TABLE users (
id int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- +goose Down
DROP TABLE users;
12 changes: 12 additions & 0 deletions db/api/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
version: '3.7'
services:
db:
image: mysql:5.7
restart: always
environment:
MYSQL_DATABASE: golang_study
MYSQL_USER: user
MYSQL_PASSWORD: password
MYSQL_ROOT_PASSWORD: rootpassword
ports:
- 3314:3306
12 changes: 12 additions & 0 deletions db/api/domain/user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package domain

// User is a struct for user table.
type User struct {
// sqlxのdbタグを使ってカラムとフィールドをマッピングする
ID int `db:"id" json:"id"`
FirstName string `db:"first_name" json:"first_name"`
LastName string `db:"last_name" json:"last_name"`
}

// Users have some users.
type Users []User
18 changes: 18 additions & 0 deletions db/api/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
module github.com/mf-sakura/golang_study/db/api

go 1.14

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/go-sql-driver/mysql v1.5.0
github.com/jmoiron/sqlx v1.2.0
github.com/joho/godotenv v1.3.0
github.com/kr/pretty v0.1.0 // indirect
github.com/labstack/echo/v4 v4.1.16
github.com/lib/pq v1.3.0 // indirect
github.com/mattn/go-sqlite3 v2.0.3+incompatible // indirect
golang.org/x/crypto v0.0.0-20200403201458-baeed622b8d8 // indirect
golang.org/x/sys v0.0.0-20200406113430-c6e801f48ba2 // indirect
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect
gopkg.in/yaml.v2 v2.2.8 // indirect
)
71 changes: 71 additions & 0 deletions db/api/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/jmoiron/sqlx v1.2.0 h1:41Ip0zITnmWNR/vHV+S4m+VoUivnWY5E4OJfLZjCJMA=
github.com/jmoiron/sqlx v1.2.0/go.mod h1:1FEQNm3xlJgrMD+FBdI9+xvCksHtbpVBBw5dYhBSsks=
github.com/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc=
github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/labstack/echo/v4 v4.1.16 h1:8swiwjE5Jkai3RPfZoahp8kjVCRNq+y7Q0hPji2Kz0o=
github.com/labstack/echo/v4 v4.1.16/go.mod h1:awO+5TzAjvL8XpibdsfXxPgHr+orhtXZJZIQCVjogKI=
github.com/labstack/gommon v0.3.0 h1:JEeO0bvc78PKdyHxloTKiF8BD5iGrH8T6MSeGvSgob0=
github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k=
github.com/lib/pq v1.0.0 h1:X5PMW56eZitiTeO7tKzZxFCSpbFZJtkMMooicw2us9A=
github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/lib/pq v1.3.0 h1:/qkRGz8zljWiDcFvgpwUpwIAPu3r07TDvs3Rws+o/pU=
github.com/lib/pq v1.3.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-colorable v0.1.6 h1:6Su7aK7lXmJ/U79bYtBjLNaha4Fs1Rg9plHpcH+vvnE=
github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ=
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-sqlite3 v1.9.0 h1:pDRiWfl+++eC2FEFRy6jXmQlvp4Yh3z1MJKg4UeYM/4=
github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
github.com/mattn/go-sqlite3 v2.0.3+incompatible h1:gXHsfypPkaMZrKbD5209QV9jbUTJKjyR5WD3HYQSd+U=
github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8=
github.com/valyala/fasttemplate v1.1.0 h1:RZqt0yGBsps8NGvLSGW804QQqCUYYLsaOjTVHy1Ocw4=
github.com/valyala/fasttemplate v1.1.0/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200221231518-2aa609cf4a9d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200403201458-baeed622b8d8 h1:fpnn/HnJONpIu6hkXi1u/7rR0NzilgWr4T0JmWkEitk=
golang.org/x/crypto v0.0.0-20200403201458-baeed622b8d8/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b h1:0mm1VjtFUOIlE1SbDlwjYaDxZVDP2S5ou6y0gSgXHu8=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200406113430-c6e801f48ba2 h1:Z9pPywZscwuw0ijrLEbTzW9lppFgBY4HDgbvoDnreQs=
golang.org/x/sys v0.0.0-20200406113430-c6e801f48ba2/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
38 changes: 38 additions & 0 deletions db/api/infrastructure/sqlhandler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package infrastructure

import (
"log"
"os"

// mysql driver
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"

"github.com/joho/godotenv"
)

// SQLHandler is a struct for db connection
type SQLHandler struct {
Conn *sqlx.DB
}

// NewSQLHandler make SQLHandler
func NewSQLHandler() *SQLHandler {
log.SetFlags(log.Ldate + log.Ltime + log.Lshortfile)
log.SetOutput(os.Stdout)

err := godotenv.Load()
if err != nil {
log.Fatalf("error loading .env file. %s", err)
}

database := os.Getenv("DATABASE_DATASOURCE")
conn, err := sqlx.Open("mysql", database)
if err != nil {
log.Fatalf("error opening mysql. %s", err)
}

sqlHandler := new(SQLHandler)
sqlHandler.Conn = conn
return sqlHandler
}
84 changes: 84 additions & 0 deletions db/api/interfaces/controllers/user_controller.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package controllers

import (
"strconv"
"net/http"
"database/sql"

"github.com/jmoiron/sqlx"
"github.com/labstack/echo/v4"

"github.com/mf-sakura/golang_study/db/api/interfaces/database"
"github.com/mf-sakura/golang_study/db/api/domain"
)

// UserController is a struct for db connection
type UserController struct {
db *sqlx.DB
}

// NewUserController create a struct , UserController
func NewUserController(db *sqlx.DB) *UserController {
return &UserController{db: db}
}

// Create is a function for creating a user.
func (controller *UserController) Create(c echo.Context) (err error) {
user := domain.User{}
if err := c.Bind(&user); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Internal Server Error")
}

id, err := database.Store(controller.db, user)
if err != nil {
return err
}
user.ID = id
return c.JSON(http.StatusOK, user)
}

func (controller *UserController) Update(c echo.Context) (err error) {
user := domain.User{}
if err := c.Bind(&user); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Internal Server Error")
}
tx := controller.db.MustBegin()
defer func() {
if rollbackErr := tx.Rollback(); rollbackErr != nil {
if rollbackErr != sql.ErrTxDone {
err = rollbackErr
}
}
}()

err = database.Update(tx, user)
if err != nil {
return
}
tx.Commit()

return c.JSON(http.StatusOK, user)
}

// Index is a function for returning all users.
func (controller *UserController) Index(c echo.Context) error {
users, err := database.FindAll(controller.db)
if err != nil {
return err
}
return c.JSON(http.StatusOK, users)
}

// Show is a function for returning a user.
func (controller *UserController) Show(c echo.Context) error {
id := c.Param("id")
identifier, err := strconv.Atoi(id)
user, err := database.FindByID(controller.db, identifier)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Internal Server Error")
}
if err = c.Bind(user); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Internal Server Error")
}
return c.JSON(http.StatusOK, user)
}
Loading