ごっそログ

勉強したことなどを書いていきます

Nuxt 3+Spring BootでREST API #5 flywayでDBのマイグレーションを行う

目次

flywayのインストール

前回で無事にマルチプロジェクト構成にできたので、今回はマイグレーション周りを整備していく。
build.gradle に組み込む方法もあるっぽいけど今回はnpmでnode-flywaydbを導入する。
今回はひとまずローカルで実行できるところまで。

まずはnpm initnpm install node-flywaydbでインストールを行う。

現時点のpackage.json

設定ファイルの記述

以下を参考に config.js を記述する。
github.com

// This can be a function or an object literal.
module.exports = function () {
  console.log(`migaration start`);
  return {
    flywayArgs: {
      url: `jdbc:mysql://localhost:3307/base`,
      schemas: "base",
      locations: "filesystem:migrate/sql",
      user: "root",
      password: ****,
      sqlMigrationSuffixes: ".sql",
      baselineOnMigrate: true,
    },
    // Use to configure environment variables used by flyway
    env: {
      JAVA_ARGS: "-Djava.util.logging.config.file=./conf/logging.properties",
    },
    version: "6.3.2", // optional, empty or missing will download the latest
    mavenPlugins: [
      {
        // optional, use to add any plugins (ie. logging)
        groupId: "org.slf4j",
        artifactId: "slf4j-api",
        version: "1.7.25",
        // This can be a specifc url to download that may be different then the auto generated url.
        downloadUrl:
          "https://repo1.maven.org/maven2/org/slf4j/slf4j-api/1.7.25/slf4j-api-1.7.25.jar",
      },
      {
        groupId: "org.slf4j",
        artifactId: "slf4j-jdk14",
        version: "1.7.25",
      },
    ],
    downloads: {
      storageDirectory: "migrate/lib", // optional, the specific directory to store the flyway downloaded files. The directory must be writable by the node app process' user.
      expirationTimeInMs: -1, // optional, -1 will never check for updates, defaults to 1 day.
    },
  };
};

package.jsonの編集

npmコマンドでマイグレーションを実行できるようにする。
scripts が以下になるように2行追記。

  "scripts": {
    "migrate": "flyway -c migrate/config.js migrate",
    "clean": "flyway -c migrate/config.js clean",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

npm run migrate を実行してみる。
config.jsで指定したbase というスキーマができていれば成功。

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

migration直下に sqlディレクトリを作成し、ここにマイグレーションファイルを配置していくことにする。
今回は V1.0.0__init.sqlという名前で作成した。flywayのマイグレーションファイルには命名規則があり、正常に動作させるには厳密に従う必要があるので注意すること。(ここでは詳述しない)
以下、特に意味のないテスト用テーブルのDDL

DROP TABLE IF EXISTS t_test;
CREATE TABLE t_test (
  id varchar(8) not null comment 'ID',
  name varchar(20) not null comment '名称',
  constraint t_test_pk primary key (id)
) comment='テスト';

試運転

再度 npm run migrate を実行してみる。

テーブルが作成された。
先ほどpackage.jsonに定義した、マイグレーションの進行状況をクリーンするためのコマンドも動作確認しておく。
npm run clean を実行。

テーブルが削除されていればOK。

参考

GradleでFlywayでMySQLをマイグレーション - Qiita