[pkg] golang-migrate 筆記
- Database Migrations in Go @ calhoun
- golang-migrate @ github
TL;DR
# 建立 migration 檔
$ migrate create -ext sql -dir db/migrations create_users_table
# 定義變數 POSTGRESQL_URL
export POSTGRESQL_URL="postgres://postgres:postgres@localhost:5432/blog_service?sslmode=disable"
# 執行 migration 檔
$ migrate -source file://internal/dao/migrations -database "postgres://postgres:postgres@localhost:5432/blog_service?sslmode=disable" up
$ migrate -database ${POSTGRESQL_URL} -path db/migrations up
# force
$ migrate -source file://internal/dao/migrations -database "postgres://postgres:postgres@localhost:5432/blog_service?sslmode=disable" force 20201211154328
migrate CLI @ golang migrate
PostgreSQL tutorial for beginners
使用 CLI 執行 migration
-
建立 migration 檔案
$ migrate create -ext sql -dir database/migrations create_users_table
-
在 migration 檔中填入要執行的 SQL
up:
-- 20201125101852_create_users_table.up.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:
-- 20201125101852_create_users_table.down.sql
DROP TABLE IF EXISTS users; -
在 Terminal 中設定環境變數
$ export POSTGRESQL_URL='postgres://postgres:password@localhost:5432/example? sslmode=disable'