1
2

More than 1 year has passed since last update.

golang-migrateチュートリアル(migration編)

Last updated at Posted at 2022-03-02

#初めに
 golang-migrateのチュートリアルです。

#環境
PC:Mac(CPUはintel製)
Go:1.17.6 ←Goのver大事。versionは1.16以降をインストールしてください。
開発エディタ:Visual Studio Code

#ディレクトリ構成

ディレクトリ構成
~/go/src/test $ tree
.
├── db
│   └── migrations
│       ├── 000001_create_users_table.down.sql
│       └── 000001_create_users_table.up.sql
├── docker-compose.yml
└── go.mod
2 directories, 4 files

#go-migrateのインストール

golang-migrateのインストール
brew install golang-migrate

#事前準備
①DB用意
postgressを用意し、exampleという名のDBを作成する。
②環境依存情報を設定しておく

環境依存情報の設定
export POSTGRESQL_URL='postgres://postgres:postgres@localhost:5432/example?sslmode=disable'

#マイグレーションファイルの作成

ディレクトリの準備
~/go/src/test $ tree
.
├── db
│   └── migrations
├── docker-compose.yml
└── go.mod

2 directories, 2 files
docker-compose.yml
version: '3.1'

services:
  postgres:
    container_name: postgres
    image: postgres:13
    ports:
      - 5432:5432
    volumes:
      - ./.data/postgres:/var/lib/postgresql/data
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
コマンド実行
~/go/src/test $ migrate create -ext sql -dir db/migrations -seq create_users_table
/Users/kawamurakouji/go/src/test/db/migrations/000001_create_users_table.up.sql
/Users/kawamurakouji/go/src/test/db/migrations/000001_create_users_table.down.sql
createファイルの編集(000001_create_users_table.down.sql)
CREATE TABLE IF NOT EXISTS users(
   user_id serial PRIMARY KEY,
   username VARCHAR (50) UNIQUE NOT NULL,
   password VARCHAR (50) NOT NULL,
   email VARCHAR (300) UNIQUE NOT NULL
);
downファイルの編集(000001_create_users_table.down.sql)
DROP TABLE IF EXISTS users;

#migration実行

migration実行
~/go/src/test $ migrate -database ${POSTGRESQL_URL} -path db/migrations up        
1/u create_users_table (97.462811ms)

スクリーンショット 2022-03-02 21.41.50.png
スクリーンショット 2022-03-02 21.42.14.png
スクリーンショット 2022-03-02 21.42.29.png
→userテーブルが作成されていることを確認。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2