0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

sql-migrateまとめ

Posted at

sql-migrateを使用する機会があったため、よく使用するコマンドや発生したエラーを記録しておく。DBはPostgreSQL。

sql-migrateとは

Go製のマイグレーションツール。
SQLファイルを作成してマイグレーションを行う。実行環境を分けることが容易である。

コマンド

  • マイグレーションファイル作成
sql-migrate new [ファイル名]

年月日時分秒-ファイル名.sqlで作成される。

  • 現在のマイグレーション数確認
sql-migrate status
  • マイグレーション実行
sql-migrate up
  • ロールバック(ひとつ前)
sql-migrate down
  • ロールバック(一括で戻す場合)
sql-migrate down -limit=N
  • コマンド確認
sql-migrate --help

マイグレーションの実行順序はファイル名のバージョン番号かタイムスタンプ。

エラー

・更新日時のカラムに自動更新するようにストアドプロシージャでトリガー設定のSQLを書き、マイグレーションを実行した時に発生。

実行.sql
-- +migrate Up
CREATE OR REPLACE FUNCTION set_update_datetime()
RETURNS TRIGGER AS $$
BEGIN
  NEW.update_datetime = CURRENT_TIMESTAMP;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;
# sql-migrate up
Migration failed: pq: unterminated dollar-quoted string at or near "$$
BEGIN
  NEW.update_datetime = CURRENT_TIMESTAMP" handling 実行.sql
解決.sql
-- +migrate Up
-- +migrate StatementBegin
CREATE OR REPLACE FUNCTION set_update_datetime()
RETURNS TRIGGER AS $$
BEGIN
  NEW.update_datetime = CURRENT_TIMESTAMP;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- +migrate StatementEnd

セミコロンを含む複雑なステートメントがある場合は境界を分かりやすくするために、StatementBegin StatementEndを使用する。

参考

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?