Skip to content

Commit

Permalink
seedデータ投入用のコマンド作成
Browse files Browse the repository at this point in the history
  • Loading branch information
kazuyainoue0124 committed Jan 3, 2025
1 parent b54dccb commit fbf2664
Show file tree
Hide file tree
Showing 2 changed files with 103 additions and 2 deletions.
78 changes: 78 additions & 0 deletions cmd/seed/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package main

import (
"database/sql"
"fmt"
"log"
"time"

_ "github.com/go-sql-driver/mysql"
"github.com/kazuyainoue0124/go-rest-api/config"
)

func main() {
cfg, err := config.LoadConfig()
if err != nil {
log.Fatal("failed to load config: ", err)
}

dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?parseTime=true&loc=Local&charset=utf8mb4",
cfg.DB.User, cfg.DB.Password, cfg.DB.Host, cfg.DB.Port, cfg.DB.Name)

db, err := sql.Open("mysql", dsn)
if err != nil {
log.Fatalf("Failed to connect DB: %v", err)
}
defer db.Close()

_, err = db.Exec(`
INSERT INTO tasks (id, title, description, created_at, updated_at)
VALUES
(?, ?, ?, ?, ?),
(?, ?, ?, ?, ?),
(?, ?, ?, ?, ?),
(?, ?, ?, ?, ?),
(?, ?, ?, ?, ?)
`,
// 1行目
1,
"タイトル1",
"説明1",
time.Now(),
time.Now(),

// 2行目
2,
"タイトル2",
"説明2",
time.Now(),
time.Now(),

// 3行目
3,
"タイトル3",
"説明3",
time.Now(),
time.Now(),

// 4行目
4,
"タイトル4",
"説明4",
time.Now(),
time.Now(),

// 5行目
5,
"タイトル5",
"説明5",
time.Now(),
time.Now(),
)

if err != nil {
log.Fatalf("Failed to seed data: %v", err)
}

fmt.Println("Seed data inserted!")
}
27 changes: 25 additions & 2 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ services:
volumes:
- db_data:/var/lib/mysql
healthcheck:
test: ["CMD-SHELL", "mysql -u todouser -psecret -h localhost -e 'SELECT 1'"]
test:
["CMD-SHELL", "mysql -u todouser -psecret -h localhost -e 'SELECT 1'"]
interval: 10s
timeout: 5s
retries: 5
Expand All @@ -22,11 +23,33 @@ services:
depends_on:
db:
condition: service_healthy
entrypoint: ["migrate", "-path", "/migrations", "-database", "mysql://todouser:secret@tcp(db:3306)/todo"]
entrypoint:
[
"migrate",
"-path",
"/migrations",
"-database",
"mysql://todouser:secret@tcp(db:3306)/todo",
]
command: ["up"]
volumes:
- ./infrastructure/db/migrations:/migrations:ro

seed-runner:
build:
context: .
target: build-stage
depends_on:
db:
condition: service_healthy
command: go run cmd/seed/main.go
environment:
DB_HOST: db
DB_USER: todouser
DB_PASSWORD: secret
DB_NAME: todo
DB_PORT: 3306

app:
build: .
environment:
Expand Down

0 comments on commit fbf2664

Please sign in to comment.