liquibase-maven-pluginを使って持続的なデータベース統合を実現します。

55978 ワード

データベースバージョンの管理、継続的な統合は、常にみんなが関心を持っている問題です。ネット上でも多くの関連記事が紹介されています。ずっとルビオン・ライルスのdatabase migrationが羨ましいです。java陣営にも似たようなツールがあります。データベースのバージョンを管理して、データベースの移転を実現します。本稿では、liquibase-maven-pluginというMavenプラグインについて詳しく紹介します。
一、properties-maven-pluginを配置し、外部属性配置ファイルをロードさせる
liquibaseは、データベースの接続属性やドライバなどのパラメータを設定する必要があります。これらのパラメータが直接pomファイルに配置されると、配置管理者の作業量が増加します。ウェブアプリケーションに配置されているプロpertiesファイルの配置属性を一括して読み取ることができるようにしたいです。プロperties-maven-pluginプラグインを使用して配置ファイルを導入することができます。構成例は以下の通りです。
    <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>properties-maven-plugin</artifactId>
        <version>1.0-alpha-2</version>
        <executions>
          <execution>
            <phase>initialize</phase>
            <goals>
              <goal>read-project-properties</goal>
            </goals>
            <configuration>
              <files>
                <file>${basedir}/src/main/resources/conf/geoq.properties</file>
              </files>
            </configuration>
          </execution>
        </executions>
    </plugin>
geoq.propertiesの構成例は以下の通りである。
    jdbc.driverClassName=org.postgresql.Driver
    jdbc.url=jdbc:postgresql://localhost:5432/geoq_dev
    jdbc.username=postgres
    jdbc.password=4652
設定属性は、pomで$ProptyNmaeを使用して参照することができます。
    <configuration>
      <changeLogFile>src/main/resources/liquiabse/business_table.xml</changeLogFile>
      <driver>${jdbc.driverClassName}</driver>
      <url>${jdbc.url}</url>
      <username>${jdbc.username}</username>
      <password>${jdbc.password}</password>
    </configuration>
二、liquibase-maven-pluginを配置する。
構成例は以下の通りです。
    <plugin>
        <groupId>org.liquibase</groupId>
        <artifactId>liquibase-maven-plugin</artifactId>
        <version>2.0.5</version>
        <dependencies>
            <dependency>
                <groupId>org.liquibase</groupId>
                <artifactId>liquibase-core</artifactId>
                <version>2.0.5</version>
            </dependency>
        </dependencies>
        <executions>
            <execution>
              <phase>process-resources</phase>
              <configuration>
                    <changeLogFile>src/main/resources/liquiabse/business_table.xml</changeLogFile>
                    <driver>${jdbc.driverClassName}</driver>
                    <url>${jdbc.url}</url>
                    <username>${jdbc.username}</username>
                    <password>${jdbc.password}</password>
              </configuration>
              <goals>
                    <goal>update</goal>
              </goals>
            </execution>
        </executions>
    </plugin>
1、dependencyでjarパッケージliquibase-coreを導入する必要があります。バージョン番号はプラグインのバージョン番号と一致します。
2、phaseパラメータでいつ運行するかを指定します。普通はprocess-resourceです。
3、changeLogFileパラメータ指定liquibaseデータベース変更ログファイル
4、driver、url、username、password配置データベース接続パラメータ
 三、データベースからデータベース変更ログファイルを生成する
既存のデータベースに対して、どのように対応するデータベース変更ログファイルを生成するかは、GEnerate Change Logコマンドを使用して、このコマンドを使用してliquibaseの実行プログラムをダウンロードする必要があります。コマンドの例は以下の通りです。
    liquibase --driver=org.postgresql.Driver --classpath="C:\Program Files (x86)\PostgreSQL\pgJDBC\postgresql-9.1-901.jdbc4.jar" --changeLogFile=db.changelog.xml --url="jdbc:postgresql://localhost:5432/geoq_dev" --username=postgres --password=4652 generateChangeLog
generate Chenglogはデフォルトではデータベース構造の変更ログファイルだけを作成します。挿入データの変更ログファイルを作成するなら、パラメータdiffTypesを使用してもいいです。このパラメータには以下のオプションが含まれています。
  • テーブル
  • columns[DEFAULT]  列
  • view[DEFAULT]  ビュー
  • prmaryKeys[DEFAULT]  メインキー
  • indexes[DEFAULT]  インデックス
  • foreignKeys[DEFAULT] 
  • sequences[DEFAULT]
  • data
  •     liquibase --driver=org.postgresql.Driver --classpath="C:\Program Files (x86)\PostgreSQL\pgJDBC\postgresql-9.1-901.jdbc4.jar" --changeLogFile=db.changelog.xml --url="jdbc:postgresql://localhost:5432/geoq_dev_full" --username=postgres --password=4652 --diffTypes=data generateChangeLog
    二つのデータベースを比較:
        liquibase --driver=org.postgresql.Driver --classpath="C:\Program Files (x86)\PostgreSQL\pgJDBC\postgresql-9.1-901.jdbc4.jar" --changeLogFile=db.changelog.xml --url="jdbc:postgresql://localhost:5432/geoq_dev" --username=postgres --password=4652 diffChangeLog --referenceUrl="jdbc:postgresql://localhost:5432/geoq_dev_full" --referenceUsername=postgres --referencePassword=4652
    四、既存のデータベースを再構築する
    データベース変更ログファイルは、データベースの変更をバージョン管理し、特定のデータベースに対する依存性から脱却することができますので、データベース変更ログファイルの関連文法を理解する必要があります。
    1、列を編集する:
    列を追加
        <changeSet id="4" author="joe">
            <addColumn tableName="distributor">
              <column name="phonenumber" type="varchar(255)"/>
            </addColumn>
        </changeSet>
    自己増加列を追加:
        <column autoIncrement="true" name="module_config_id" type="int" startWith="1">
            <constraints nullable="false" primaryKey="true" primaryKeyName="pk_t_module_config"/>
        </column>
    列を削除:
        <dropColumn tableName="distributor" columnName="phonenumber"/>
    既存の列を改ページする
        <addAutoIncrement tableName="person" columnName="id" columnDataType="int"/>
    postgresqlを修正して、列の現在のインデックス値を増加します。liquibaseはこの操作をサポートしていません。sqlラベルを使って実現できます。
        <sql>
            ALTER SEQUENCE t_role_role_id_seq RESTART WITH 3;
        </sql>
    2、テーブルを作成する:
        <changeSet id="3" author="betsey">
            <createTable tableName="distributor">
              <column name="id" type="int">
                <constraints primaryKey="true" nullable="false"/>
              </column>
              <column name="name" type="varchar(255)">
                <constraints nullable="false"/>
              </column>
              <column name="address" type="varchar(255)">
                <constraints nullable="true"/>
              </column>
              <column name="active" type="boolean" defaultValue="1"/>
            </createTable>
        </changeSet>
    3、操作データ:
        <changeSet id="3" author="betsey">
            <code type="section" width="100%">
            <insert tableName="distributor">
              <column name="id" valueNumeric="3"/>
              <column name="name" value="Manassas Beer Company"/>
            </insert>
            <insert tableName="distributor">
              <column name="id" valueNumeric="4"/>
              <column name="name" value="Harrisonburg Beer Distributors"/>
            </insert>
        </changeSet>
    データを操作するためのSQLスクリプトを作成するべきです。SQLスクリプトを使ってデータベースに大量の変更を適用すると簡単になります。LiquiBaseもこれらのシナリオをサポートすることができます。
    次の例は、LiquiBase変更セットからカスタマイズSQLファイルを実行します。
        <changeSet id="6" author="joe"> 
            <sqlFile path="insert-distributor-data.sql"/>
        </changeSet>
    changesetを作成する場合、フィールドの内容がhtmlタグであれば、<![CDATA[htmlタグ付きテキストをインポートします。 
    4、操作手順:
    シーケンスを作成
    <createSequence sequenceName="seq_employee_id"/>
    sequenceName
    シーケンス名 [required]
    schema Name
    表schema名称
    increment By
    自己増加間隔値
    minValue
    シーケンスの最小値
    maxValue
    シーケンスの最大値
    orded
    'true'または'false'
    startValue
    シーケンスの開始値
    シーケンスの変更
    <alterSequence sequenceName="seq_employee_id" incrementBy="10"/>
    sequenceName
    シーケンスの名前 [required]
    increment By
    新しい自己増加間隔の値 [required]
     五、liquibase-maven-plugin基本命令
  • データベース更新:mvn liquibase:udate
  • バージョンラベル:mvn liquibase:(
  • 最近の更新版、または指定されたラベルバージョン、または日付、または更新回数:mvn liquibase:rollback-Dliquibase.rollbackCount=1
  • sql更新脚本:mvn liquibase:udateSQL
  •  六、データベースバージョンの制御
    1、バージョンラベルを追加する:
    a、コマンドラインを使用する:
    mvn liquibase:tag -Dliquibase.tag=checkpoint
    b、プロファイルを使用する:
        <executions>
            <execution>
                <phase>process-resources</phase>
                <configuration>
                    <tag>${project.version}</tag>
                </configuration>
                <goals>
                    <goal>update</goal>
                    <goal>tag</goal>
                </goals>
            </execution>
        </executions>
    2、次のコマンドを使ってあるバージョンにスクロールできます。
        mvn liquibase:rollback -Dliquibase.rollbackTag=checkpoint
    対応するMavenは以下のように配置されています。
        <executions>
            <execution>
                <phase>process-resources</phase>
                <configuration>
                    <changeLogFile>src/main/resources/liquiabse/master-changelog.xml</changeLogFile>
                    <driver>${jdbc.driverClassName}</driver>
                    <url>${jdbc.url}</url>
                    <username>${jdbc.username}</username>
                    <password>${jdbc.password}</password>
                    <rollbackTag>1.1</rollbackTag>
                </configuration>
                <goals>
                    <goal>update</goal>
                    <goal>rollback</goal>
                </goals>
            </execution>
        </executions>
    rollback操作のオプションパラメータは、以下を含む。
    change Log File
    String
    Liquibase変更セットファイルを設定します。
    clear CheckSums
    bollan
    データベースのチェックを強制的にクリアするかどうかを識別します。標準値はfalseです。
    contexts
    String
    Liquibase実行のコンテキストを設定します。複数のコンテキストはカンマ区切りを使用できます。
    databaseClass
    String
    データベースオブジェクトのクラス
    default SchemaName
    String
    データベース接続で使用するデフォルトのデータベース構造名
    driver
    String
    データベース接続のドライバ名
    empptyPassword
    bollan
    期限が切れています。空の文字列またはnullをデータベース接続のパスワードとして使うかどうかのデフォルト値はfalseです。
    expressionVarables
    Map
    プラグインに渡す配列変数
    expressitionVars
    Propties
    プラグインに渡す配列変数
    include Artfact
    bollan
    Liquibase属性またはデータベース変更ログを取得するために許可されているかどうかは、mavenプロジェクトコンポーネントのデフォルト値を含みます。true.
    include Test Output Directory
    bollan
    Liquibase属性またはデータベース変更ログの取得を許可するかどうかは、テスト出力ディレクトリのデフォルト値を含みます。true.
    ロゴ
    String
    プラグインの出力ログレベルを制御します。オプション値は、「all」、「finet」、「finer」、「fine」、「info」、「warning」、「severe」or「off」があります。デフォルトの値は、INFO.
    password
    String
    データベース接続のパスワード
    prompt Onnon Local Database
    bollan
    リモートデータベースのデフォルト値は、ユーザの制御を許可するかどうか:true.
    propertyFile
    String
    Liquibaseプロパティファイルの位置
    propertyFileWillOverride
    bollan
    フラグは、Liquibaseプロパティファイルを使用してプラグインをカバーすることを許可するかどうかの設定のデフォルト値は、falseです。
    rollback Count
    要点
    ロールバックの変更セット数のデフォルト値は:-1.
    rollbackDate
    String
    ロールバックの日付を設定します。日付書式は、プラグイン実行のためのtheDateFormat.getDateInstance()操作設定の日付書式に一致します。
    rollbackTag
    String
    それに逆戻りします。
    server
    String
    settings.xmlにおけるサーバIDの認証時に使用します。
    skyp
    bollan
    「true」に設定してliquibaseをスキップします。このパラメータは推奨されていません。
    system Properties
    Propties
    データベースに渡すシステムのプロパティ
    url
    String
    データベース接続アドレス
    username
    String
    ユーザ名
    ボトムス
    bollan
    起動プラグインの出力の詳細を制御します。デフォルトの値はfalseです。
    ロールバックのステップ数を指定することもできます。
        mvn liquibase:rollback -Dliquibase.rollbackCount=3
    またはロールバックのsqlスクリプトを生成します。
        mvn liquibase:rollbackSQL -Dliquibase.rollbackTag=checkpoint
    3、異なるバージョンによってそれぞれ関連するchangeファイルを作成し、includeタグを使ってそれぞれ導入してもいいです。例えば、主幹のchangeファイルはmater-change og.xmlであり、下記のように定義されています。
        <?xml version="1.0" encoding="UTF-8"?>
         
        <databaseChangeLog
          xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd">
            <include file="src/main/resources/liquibase/liquibase-create-tables.xml" />
            <include file="src/main/resources/liquibase/liquibase-insert-data.xml" />
            <include file="src/main/resources/liquibase/liquibase-mobile-menu.xml" />
            …...
            <include file="src/main/resources/liquibase/liquibase-update-to-1.4.xml"/>
            <include file="src/main/resources/liquibase/liquibase-update-to-1.6.xml"/>
            …...
        </databaseChangeLog>
    七、特殊な種類のフィールドを作成する
    changelogファイルでpostgresqlサポートのenumを作成したいなら、使用できる方法は以下の通りです。
    1、sqlスクリプトを使って直接作成する
        <changeSet id="1" author="Arthur">
            <sql>CREATE TYPE my_state AS ENUM ('yes','no')</sql>
            <table name="foo">
                <column name="state" type="my_state"/>
            </table>
        </changeSet>
    2、使用制約
        <changeSet id="1" author="X">
            <table name="t">
                <column name="c" type="varchar(3)"/>
            </table>
            <sql>ALTER TABLE t ADD CONSTRAINT check_yes_no CHECK (c = 'yes' OR c = 'no')</sql>
        </changeSet>
    3、システムの現在時間を取得する
    最初に異なるデータベース取得時間の属性ラベルを定義します。
        <property name="now" value="sysdate" dbms="oracle"/>
        <property name="now" value="now()" dbms="mysql"/>
    changesetsでこの属性を参照します。
        <column name="Join_date" defaultValueFunction="${now}"/>
    完全な例は以下の通りです。
        <property name="now" value="UNIX_TIMESTAMP()" dbms="mysql"/>
        <changeSet id="emp_1" author="Me">
            <insert tableName="Emp" schemaName="XYZ">
                <column name="EmpName" value="abc"/>
                <column name="Join_date" valueDate="${now}"/>
                <column name="Profile_last_update" valueDate="${now}"/>
                <column name="group_name" value="BlahBlah"/>
            </insert>
        </changeset>
    八、マルチデータベース対応
    pomファイルで複数のexecutionタグを使って複数のデータベースをサポートすることができますが、各executionは必ずIDラベルを定義してください。
        <plugin>
            <groupId>org.liquibase</groupId>
            <artifactId>liquibase-plugin</artifactId>
            <version>1.9.5.0</version>
            <executions>
                <execution>
                    <phase>process-resources</phase>
                    <configuration>
                        <changeLogFile>src/main/resources/db.changelog.xml</changeLogFile>
                        <driver>com.mysql.jdbc.Driver</driver>
                        <url>jdbc:mysql://localhost:3306/charm</url>  
                        <username>***</username>
                        <password>***</password>
                    </configuration>
                    <goals>
                        <goal>update</goal>
                    </goals>
                </execution>
                <execution>
                    <phase>process-resources</phase>
                    <configuration>
                        <changeLogFile>src/main/resources/db.changelog.xml</changeLogFile>
                        <driver>com.mysql.jdbc.Driver</driver>
                        <url>jdbc:mysql://localhost:3306/charm2</url>  
                        <username>***</username>
                        <password>***</password>
                    </configuration>
                    <goals>
                        <goal>update</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    九、参考サイト
    主駅:http://www.liquibase.org/
    ヘルプマニュアル:http://www.liquibase.org/manual/home
    properties-maven-pluginマニュアル:http://www.liquibase.org/manual/maven