liquibase Groovy脚本用法示例

databaseChangeLog

属性

属性 描述
logicalFilePath 路径+文件名进行唯一标识,当重命名文件或者重构文件路径时可通过该属性经行唯一标识

子标签

preConditions

用途:

  • 记录执行的先决条件或者注释
  • 测试执行该databaseChangeLog的先决条件是否完备
  • 执行数据检查
  • 根据条件控制执行哪些changesets

属性:

属性 描述
onFail 不满足测试条件,执行以下选项:HALT/CONTINUE/MARK_RAN/WARN
onError 执行过程中出现错误,执行以下选项:HALT/CONTINUE/MARK_RAN/WARN
onUpdateSQL RUN/FAIL/IGNORE
onFailMessage 失败后输出的信息
onErrorMessage 抛错后输出的信息

http://www.liquibase.org/documentation/preconditions.html

详细用法示例如下:

databaseChangeLog(logicalFilePath: '') {
    preConditions(onFail: 'WARN') {
        and {
          dbms(type: 'mysql')
          runningAs(username: 'root')
          or {
            changeSetExecuted(id: '', author: '', changeLogFile: '')
            columnExists(schemaName: '', tableName: '', columnName: '')
            tableExists(schemaName: '', tableName: '')
            viewExists(schemaName: '', viewName: '')
            foreignKeyConstraintExists(schemaName: '', foreignKeyName: '')
            indexExists(schemaName: '', indexName: '')
            sequenceExists(schemaName: '', sequenceName: '')
            primaryKeyExists(schemaName: '', primaryKeyName: '', tableName: '')
            sqlCheck(expectedResult: '') {
              "SELECT COUNT(1) FROM monkey WHERE status='angry'"
            }
            customPrecondition(className: '') {
              tableName('our_table')
              count(42)
            }
          }
        }
      }
}
property

可以自定义一些参数:

databaseChangeLog(logicalFilePath: '') {
    clobType = 0
}
changeSet
属性 描述
id 必输 ,一般以时间戳+名称作为唯一标识
author 必输 ,创建者
dbms 指定数据库类型
runAlways 该changeSet不论之前是否执行过,每次都会执行 true/false
runOnChange 在第一次或者修改后执行 true/false
context 特定的上下文通过后执行
runInTransaction 执行是否事务化,默认为true,大部分情况下都为true
failOnError 是否忽略错误继续执行

属性:

属性 描述
id 必输 ,一般以时间戳+名称作为唯一标识
author 必输 ,创建者
dbms 指定数据库类型
runAlways 该changeSet不论之前是否执行过,每次都会执行 true/false
runOnChange 在第一次或者修改后执行 true/false
context 特定的上下文通过后执行
runInTransaction 执行是否事务化,默认为true,大部分情况下都为true
failOnError 是否忽略错误继续执行

子标签:

  • comment: changeSet的描述
  • preConditions:必须通过后才能执行该changeSet,主要用于一些不可恢复操作之前的数据检查
  • :具体的数据、表操作
  • validCheckSum:一般不用,使用来区分数据库中储存的changeSet与该changeSet是否一致,一般会自动生成。
  • rollback:会滚操作

具体详细用例如下:

  1. rollback
databaseChangeLog(logicalFilePath: '') {
  
  //定义参数
  clobType = 0
  
  //rollback的用法
  changeSet(id: '', author: '', dbms: '', runAlways: true, runOnChange: false, context: '', runInTransaction: true, failOnError: false) {
    // 添加描述
    comment "Liquibase can be aware of this comment"

    preConditions {
      // 与changeLog的preConditions一致
    }
    
    validCheckSum 'd0763edaa9d9bd2a9516280e9044d885'
    
    // rollback可以直接是一个string,会当作SQL直接执行
    rollback "DROP TABLE monkey_table"
    rollback """
      UPDATE monkey_table SET emotion='angry' WHERE status='PENDING';
      ALTER TABLE monkey_table DROP COLUMN angry;
    """
    
    // 也可以是liquibase脚本
    rollback {
      dropTable(tableName: 'monkey_table')
    }
    
    // 也可以指定执行某个changeSet
    rollback(changeSetId: '', changeSetAuthor: '')
    
  }
  
  1. addColumn语法:
  changeSet(id: 'add-column', author: 'tlberglund') {
    addColumn(tableName: '', schemaName: '') {
      column(name: '', type: '', value: '', defaultValue: '', autoIncrement: false, remarks: '') {
        
        // 约束
        
        // 写法一
        constraints {
          nullable(false)//是否必输
          primaryKey(true)//主键约束
          unique(true)//唯一约束
          uniqueConstraintName('make_it_unique_yo')//唯一约束名称
          foreignKeyName('key_to_monkey')//外键约束名称
          references('monkey_table')//外键约束
          deleteCascade(true)//是否级联删除
          deferrable(true)//约束验证是否可延时(事务中或者事务完成后)
          initiallyDeferred(false)//事务结束的时候才去检查约束
        }
        
        // 写法二,推荐使用写法二,可读性较好
        constraints(nullable: false, primaryKey: true)
        constraints(unique: true, uniqueConstraintName: 'make_it_unique_yo')
        constraints(foreignKeyName: 'key_to_monkey', references: 'monkey_table')
        constraints(deleteCascase: true)
        constraints(deferrable: true, initiallyDeferred: false)
      }
      

      // 列的其他属性
      column(name: '', type: '', valueNumeric: '', defaultValueNumeric: '')
      column(name: '', type: '', valueBoolean: '', defaultValueBoolean: '')
      column(name: '', type: '', valueDate: '', defaultValueDate: '')
    }
  }
  1. 列column操作:
  // renameColumn
  changeSet(id: 'rename-column', author: 'tlberglund') {
    renameColumn(schemaName: '', tableName: '', oldColumnName: '', newColumnName: '', columnDataType: '')
  }
  
  // modifyColumn
  changeSet(id: 'modify-column', author: 'tlberglund') {
    modifyColumn(schemaName: '', tableName: '') {
      column() { }
    }
  }
  // dropColumn
  changeSet(id: 'drop-column', author: 'tlberglund') {
    dropColumn(schemaName: '', tableName: '', columnName: '')
  }
  
  1. 自增长列
 changeSet(id: 'alter-sequence', author: 'tlberglund') {
   alterSequence(sequenceName: '', incrementBy: '')
 }
  1. 表table操作:
  // createTable
  changeSet(id: 'create-table', author: 'tlberglund') {
    createTable(schemaName: '', tablespace: '', tableName: '', remarks: '') {
      column() {}
      column() {}
      column() {}
      column() {}
    }
  }
  // renameTable
  changeSet(id: 'rename-table', author: 'tlberglund') {
    renameTable(schemaName: '', oldTableName: '', newTableName: '')
  }
  
  // dropTab
  changeSet(id: 'drop-table', author: 'tlberglund') {
    dropTab(schemaName: '', tableName: '')
  }
  
  1. 视图view相关操作:
  
  changeSet(id: 'create-view', author: 'tlberglund') {
    createView:(schemaName: '', viewName: '', replaceIfExists: true) {
      "SELECT id, emotion FROM monkey"
    }
  }
  
  changeSet(id: 'rename-view', author: 'tlberglund') {
    renameView(schemaName: '', oldViewName: '', newViewName: '')
  }
  
  
  changeSet(id: 'drop-view', author: 'tlberglund') {
    dropView(schemaName: '', viewName: '')
  }
  
  1. 列合并:
  changeSet(id: 'merge-columns', author: 'tlberglund') {
    mergeColumns(schemaName: '', tableName: '', column1Name: '', column2Name: '', finalColumnName: '', finalColumnType: '', joinString: ' ')
  }
  
  1. 存储过程
 changeSet(id: 'create-stored-proc', author: 'tlberglund') {
   createStoredProcedure """
     CREATE OR REPLACE PROCEDURE testMonkey
     IS
     BEGIN
      -- do something with the monkey
     END;
   """
 }
  1. 单独列操作,如约束、序列、默认值等等操作:
 
 changeSet(id: 'add-not-null-constraint', author: 'tlberglund') {
   addNotNullConstraint(tableName: '', columnName: '', defaultNullValue: '')
 }
 
 
 changeSet(id: 'drop-not-null-constraint', author: 'tlberglund') {
   dropNotNullConstraint(schemaName: '', tableName: '', columnName: '', columnDataType: '')
 }
 
 
 changeSet(id: 'add-unique-constraint', author: 'tlberglund') {
   addUniqueConstraint(tableName: '', columnNames: '', constraintName: '')
 }
 
 
 changeSet(id: 'drop-unique-constraint', author: 'tlberglund') {
   dropUniqueConstraint(schemaName: '', tableName: '', constraintName: '')
 }
 
 
 changeSet(id: 'create-sequence', author: 'tlberglund') {
   createSequence(sequenceName: '', schemaName: '', incrementBy: '', minValue: '', maxValue: '', ordered: true, startValue: '')
 }
 
 
 changeSet(id: 'drop-sequence', author: 'tlberglund') {
   dropSequence(sequenceName: '')
 }
 
 
 changeSet(id: 'add-auto-increment', author: 'tlberglund') {
   addAutoIncrement(schemaName: '', tableName: '', columnName: '', columnDataType: '')
 }
 
 
 changeSet(id: 'add-default-value', author: 'tlberglund') {
   addDefaultValue(schemaName: '', tableName: '', columnName: '', defaultValue: '')
   addDefaultValue(schemaName: '', tableName: '', columnName: '', defaultValueNumeric: '')
   addDefaultValue(schemaName: '', tableName: '', columnName: '', defaultValueBoolean: '')
   addDefaultValue(schemaName: '', tableName: '', columnName: '', defaultValueDate: '')
 }
 
 
 changeSet(id: 'drop-default-value', author: 'tlberglund') {
   dropDefaultValue(schemaName: '', tableName: '', columnName: '')
 }
 
 
 changeSet(id: 'add-foreign-key-constraint', author: 'tlberglund') {
   addForeignKeyConstraint(constraintName: '', 
                           baseTableName: '', baseTableSchemaName: '', baseColumnNames: '',
                           referencedTableName: '', referencedTableSchemaName: '', referencedColumnNames: '',
                           deferrable: true,
                           initiallyDeferred: false,
                           deleteCascase: true,
                           onDelete: 'CASCADE|SET NULL|SET DEFAULT|RESTRICT|NO ACTION',
                           onUpdate: 'CASCADE|SET NULL|SET DEFAULT|RESTRICT|NO ACTION')
 }
 
 
 changeSet(id: 'drop-foreign-key', author: 'tlberglund') {
   dropForeignKeyConstraint(constraintName: '', baseTableName: '', baseTableSchemaName: '')
 }
 
 
 changeSet(id: 'add-primary-key', author: 'tlberglund') {
   addPrimaryKey(schemaName: '', tablespace: '', tableName: '', columnNames: '', constraintName: '')
 }
 
 
 changeSet(id: 'drop-primary-key', author: 'tlberglund') {
   dropPrimaryKey(schemaName: '', tableName: '', constraintName: '')
 }
 
  1. 数据操作,我们一般采用excel进行数据导入,这里用法一般不用:
  changeSet(id: 'insert-data', author: 'tlberglund') {
    insert(schemaName: '', tableName: '') {
      column(name: '', value: '')
      column(name: '', valueNumeric: '')
      column(name: '', valueDate: '')
      column(name: '', valueBoolean: '')
    }
  }
  
  
  changeSet(id: 'load-data', author: 'tlberglund') {
    loadData(schemaName: '', tableName: '', file: '', encoding: 'UTF8|etc') {
      column(name: '', index: 2, type: 'NUMERIC')
      column(name: '', index: 3, type: 'BOOLEAN')
      column(name: '', header: 'shipDate', type: 'DATE')
      column(name: '', index: 5, type: 'STRING')
    }
  }
  
  
  changeSet(id: 'load-update-data', author: 'tlberglund') {
    loadUpdateData(schemaName: '', tableName: '', primaryKey: '', file: '', encoding: '') {
      column(name: '', index: 2, type: 'NUMERIC')
      column(name: '', index: 3, type: 'BOOLEAN')
      column(name: '', header: 'shipDate', type: 'DATE')
      column(name: '', index: 5, type: 'STRING')
    }
  }
  
  
  changeSet(id: 'update', author: 'tlberglund') {
    update(schemaName: '', tableName: '') {
      column(name: '', value: '')
      column(name: '', valueNumeric: '')
      column(name: '', valueDate: '')
      column(name: '', valueBoolean: '')
      where "species='monkey' AND status='angry'"
    }
  }
  
  
  changeSet(id: 'delete-data', author: 'tlberglund') {
    delete(schemaName: '', tableName: '') {
        where "id=39" // optional
    }
  }
  1. 索引:
  changeSet(id: 'create-index', author: 'tlberglund') {
    createIndex(schemaName: '', tablespace: '', tableName: '', indexName: '', unique: true) {
      column(name: '')
      column(name: '')
      column(name: '')
    }
  }
  
  
  changeSet(id: 'drop-index', author: 'tlberglund') {
    dropIndex(tableName: '', indexName: '')
  }
  1. sql执行:
  changeSet(id: 'custom-sql', author: 'tlberglund') {
    sql(stripComments: true, splitStatements: false, endDelimiter: ';') {
      "INSERT INTO ANIMALS (id, species, status) VALUES (1, 'monkey', 'angry')"
    }
  }
  
  
  changeSet(id: 'sql-file', author: 'tlberglund') {
    sqlFile(path: '', stripComments: true, splitStatements: '', encoding: '', endDelimiter: '')
  }
  
  1. 其他:
 changeSet(id: 'custom-refactoring', author: 'tlberglund') {
   customChange(class: 'net.saliman.liquibase.MonkeyRefactoring') {
     tableName('animal')
     species('monkey')
     status('angry')
   }
 }
 
 
 changeSet(id: 'shell-command', author: 'tlberglund') {
   executeCommand(executable: '') {
     arg('--monkey')
     arg('--skip:1')
   }
 }
   
 changeSet(id: 'tag', author: 'tlberglund') {
   tagDatabase(tag: 'monkey')
 }
 
 
 changeSet(id: 'stop', author: 'tlberglund') {
   stop('Migration stopped because something bad went down')
 }
include
属性 描述
file 要引入的文件名
relativeToChangelogFile 关联的文件路径是否为相对路径,默认false

类似js中的引入,可以通过该标签引入其他的文件
属性:

属性 描述
file 要引入的文件名
relativeToChangelogFile 关联的文件路径是否为相对路径,默认false
databaseChangeLog(logicalFilePath: '') {
 include(file: '', relative: true)  
}

你可能感兴趣的:(liquibase Groovy脚本用法示例)