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,主要用于一些不可恢复操作之前的数据检查
  • <Any Refactoring Tag(s)> :具体的数据、表操作
  • 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)  
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,277评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,689评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,624评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,356评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,402评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,292评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,135评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,992评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,429评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,636评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,785评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,492评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,092评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,723评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,858评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,891评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,713评论 2 354

推荐阅读更多精彩内容

  • 此时此刻,夜晚的高速公路上疾驰着多辆豪车。言璃戴着一个银白色的面具,坐在红色的敞篷车内。左手掌握方向盘,右手拿着一...
    夏儆言阅读 307评论 0 1
  • 怎样才能将《红楼梦》读下去? 满纸荒唐言,一把辛酸泪。都云作者痴,谁解其中味? 好多朋友和我说起读书的时候,听说我...
    长弓凌阅读 1,026评论 0 2
  • 不知道也不记得自己是多久没有写字了,虽然每天看书,看文章,每天都会花时间让自己取阅!因为我爱阅读,我需要阅读!在阅...
    拾月蓝林阅读 292评论 3 3