17.
GoでDBのマイグレーション
● goose( bitbucket.org/liamstask/goose )
○ マイグレーション:DBのバージョン管理のこと
(テーブルの作成、カラムの追加、ロールバックなど)
○ マイグレーションのスクリプトは SQL かGoで書く
○ create 、up 、down コマンドを使って管理
16/02/27 17
$ goose create create_posts
goose: created db/migrations/20160226202023_create_posts.sql
$ goose up
goose: migrating db environment 'development', ...
OK 20160226202023_create_posts.sql
$ goose down
goose: migrating db environment 'development', ...
OK 20160226202023_create_posts.sql
18.
gooseのマイグレーションファイル
● マイグレーションファイルのサンプル
○ up・down に対応するSQLスクリプトを書く
○ Goで書く場合は sql.Tx.Exec でSQLを実行
○ IDの AUTO_INCREMENT や PRIMARY KEY の設定を忘れずに
16/02/27 18
-- +goose Up
-- SQL in section 'Up' is executed when this migration is ...
CREATE TABLE IF NOT EXISTS `posts` (
`id` INT NOT NULL AUTO_INCREMENT,
`title` VARCHAR(255) NOT NULL,
`body` TEXT NOT NULL,
PRIMARY KEY (`id`)
);
-- +goose Down
-- SQL section 'Down' is executed when this migration is ...
DROP TABLE `posts`;
19.
DBから構造体にマッピング
● ORM(Object-Relation Mapping)
○ DBのタプルをGoの 構造体 に変換するもの
○ WAFと同じく シンプル なモノと フルスタック なモノ
○ マイグレーションもできるものが多い
16/02/27 19
type Model struct {
ID uint `gorm:"primary_key"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time
}
type User struct {
gorm.Model
Name string
}
Clipping is a handy way to collect and organize the most important slides from a presentation. You can keep your great finds in clipboards organized around topics.
Be the first to comment