天天看點

Liquibase入門介紹

簡介

Liquibase社群版是一個開源項目,可以幫助開發人員快速管理資料庫架構更改。跟蹤、版本化和部署資料庫變更。目前基于Maven插件将Liquibase內建到項目中,可以使資料庫可持續開發部署管理。

Liquibase配置檔案

通過Maven的profile,不同環境的資料庫使用不同的Liquibase配置檔案( local,dev,stg,prod),如下圖所示

changeLogFile=src/main/resources/db/changelog/db.changelog-master.xml

driver=org.postgresql.Driver

defaultSchemaName=minefocus

url=jdbc:postgresql://localhost:5432/demo

username=postgres password=123456

outputChangeLogFile=/var/data/liquibase/changelog/db.changelog-export.xml

diffTypes=tables,columns,views,primaryKeys,indexes,foreignKeys,sequences,data dataDir=/var/data/liquibase/changelog/csv

outputDirectory=target/docs
           

Liquibase目錄結構

Liquibase的changelog檔案放在resources/db/changelog目錄下,如下圖所示,我們隻需要追加更改這些檔案來更新資料庫。db.changelog-master.xml是主檔案,隻用于包含檔案,一般不做更改。根據修改類型:增加,修改,删除表對象和資料導入分别在各自檔案添加。資料檔案以csv格式放到csv目錄下。

如果多次release,可以通過檔案夾加版本号增加新的changelog檔案。如:

master.xml

--release1.0.0

----release.xml

----add.xml

----update.xml

----remove.xml

----data.xml

----csv

--release1.0.1

----release.xml

----add.xml

----update.xml

----remove.xml

----data.xml

----csv

中小項目如果對changgelog都非常熟悉,可以用一個xml定義changelog。

大型項目可以按照子產品劃分目錄結構,如

master.xml

--release1.0.0

----release.xml

----user.xml

----user.csv

----company.xml

--release1.0.1

----release.xml

----user.xml

----user.csv

----company.xml

以上僅供參考,根據項目情況可以自定義目錄結構。

資料庫changelog

1. changelog

有xml、yaml,json結構,根據需要選擇其中一種,xml易讀;yaml簡潔;json介于前兩者之間。

Tag Description
preConditions Pre-conditions required to execute the changelog. Read More
property Value to set property to, if not set by another means. Read More
changeSet The changesets to execute. Read More
include Additional files containing changesets to execute. Read More
context Context to be appended (using AND) to all changesets since 3.5
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
                   xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog 
                   http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.8.xsd 
                   http://www.liquibase.org/xml/ns/dbchangelog-ext 
                   http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">
    <property name="clob.type" value="clob" dbms="oracle,postgresql"/>
    <property name="clob.type" value="longtext" dbms="mysql"/>
    <property name="table.name" value="tableA"/>
    <changeSet id="1" author="joe">
        <createTable tableName="${table.name}">
            <column name="id" type="int"/>
            <column name="${column1.name}" type="${clob.type}"/>
            <column name="${column2.name}" type="int"/>
        </createTable>
    </changeSet>
</databaseChangeLog>
           

更多資訊:https://docs.liquibase.com/concepts/basic/changelog.html

2. changeSet

Available attributes

id An alpha-numeric identifier required
author The creator of the changeset required
dbms The type of a database which that changeset is to be used for. When the migration step is running, it checks the database type against this attribute. Valid database type names are listed on the supported databases page. It is possible to list multiple databases separated by commas. You can also specify that a changeset is NOT applicable to a particular database type by prefixing with !. The keywords all and none are also available.
runAlways Executes the changeset on every run, even if it has been run before
runOnChange Executes the change the first time it is seen and each time the change set has been changed
Contexts Controls whether a changeset is executed, depending on runtime settings. Any string can be used for the context name and they are checked case-insensitively.
Labels Controls whether a changeset is executed, depending on runtime settings. Any string can be used for the label name and they are checked case-insensitively.
runInTransaction Should the changeset be ran as a single transaction (if possible)? Defaults to true. Warning: be careful with this attribute. If set to false and an error occurs part way through running a changeset containing multiple statements, the LiquibaseDATABASECHANGELOG table will be left in an invalid state. Since 1.9
failOnError Should the migration fail if an error occurs while executing the changeset? Default=true
objectQuotingStrategy

This controls how object names are quoted in the SQL generated or used in calls to the database. Different databases do different things to the names of objects, for example Oracle converts everything to uppercase (unless quoted). There are three possible values. The default value is LEGACY.

LEGACY - Same behavior as in Liquibase 2.0

QUOTE_ALL_OBJECTS - Every object gets quoted. e.g. person becomes "person".

QUOTE_ONLY_RESERVED_WORDS - Quote reserved keywords and invalid column names.

runOrder Since 3.5
created Since 3.5
ignore Ignore the changeset from the executionSince 3.6
logicalFilePath Use to override the file name and path when creating the unique identifier of changesets. Required when moving or renaming change logs.

Available sub-tags

comment A description of the changeset. XML comments will provide the same benefit, future releases of Liquibase may be able to make use of <comment> tag comments to generate documentation
preConditions Preconditions that must pass before the change set will be executed. Useful for doing a data sanity check before doing something unrecoverable such as a dropTable Since 1.7
<Any Refactoring Tag(s)> The database change(s) to run as part of this changeset (so called Change Types).
validCheckSum Add a checksum that is considered valid for this changeset, regardless of what is stored in the database. Used primarily when you need to change a changeset and don't want errors thrown on databases on which it has already run (not a recommended procedure). Special value "1:any" will match to any checksum and not execute the changeset on ANY changeSince 1.7
rollback SQL statements or Change Type tags that describe how to rollback the changeset. See Rolling back changesets.
<?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" xmlns:pro="http://www.liquibase.org/xml/ns/pro" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.8.xsd http://www.liquibase.org/xml/ns/pro http://www.liquibase.org/xml/ns/pro/liquibase-pro-3.8.xsd"> <changeSet id="1" author="bob"> <comment>A sample change log</comment> <createTable/> </changeSet> <changeSet id="2" author="bob" runAlways="true"> <alterTable/> </changeSet> <changeSet id="3" author="alice" failOnError="false" dbms="oracle"> <alterTable/> </changeSet> <changeSet id="4" author="alice" failOnError="false" dbms="!oracle"> <alterTable/> </changeSet> </databaseChangeLog>
           

更多資訊:https://docs.liquibase.com/concepts/basic/changeset.html

3.Change Types

增加

addAutoIncrement addColumn
addDefaultValue addForeignKeyConstraint
addLookupTable addNotNullConstraint
addPrimaryKey addUniqueConstraint

建立

createIndex createProcedure
createSequence createTable
createView

移除

dropAllForeignKeyConstraints dropColumn
dropDefaultValue dropForeignKeyConstraint
dropIndex dropNotNullConstraint
dropPrimaryKey dropProcedure
dropSequence dropTable
dropUniqueConstraint dropView

重命名

renameColumn renameSequence
renameTable renameView

SQL

sql sqlFile

其它

alterSequence customChange
delete empty
executeCommand insert
loadData loadUpdateData
mergeColumns modifyDataType
output setColumnRemarks
setTableRemarks stop
tagDatabase update

指令

1. 原生

更多資訊:https://docs.liquibase.com/commands/community/home.html

2. maven常用指令

2.1 更新資料庫:mvn liquibase:update

2.2 生成changelog:mvn liquibase:generateChangeLog 注意:導出的changelog會追加到xml檔案,而不是覆寫

2.3 資料庫差異比較:mvn liquibase:diff

2.4 生成資料庫文檔:mvn liquibase:dbDoc

更對資訊:https://docs.liquibase.com/tools-integrations/maven/commands/home.html

繼續閱讀