public
Created

Generate LiquiBase changeLogs using Groovy

  • Download Gist
gistfile1.groovy
Groovy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
def writer = new FileWriter('sample2.xml')
 
// Define 2 tables
def tables =[]
def dept = new Table(tableName:'departments')
dept.columns << new Column(name:'id', type:'number(4,0)', nullable:false)
dept.columns << new Column(name:'dname', type:'varchar2(14)', remarks:'Department name')
tables << dept
 
def emp = new Table(tableName:'employees', remarks:'All employees known in HR system')
emp.columns << new Column(name:'id', type:'number(4,0)', nullable:false)
emp.columns << new Column(name:'ename', type:'varchar2(14)', remarks:'Full name')
emp.columns << new Column(name:'dept_id', type:'number(4,0)', nullable:false)
tables << emp
 
def cct = new ChangelogCreateTable(author: "james")
cct.generate(writer, tables)
 
class ChangelogCreateTable {
String author
def changesetId = 1
def generate(writer, tables) {
// MarkupBuilder cannot output an XML declaration, so this is a workaround
def eol = System.properties.'line.separator'
writer << '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' << eol
 
def xml = new groovy.xml.MarkupBuilder(writer)
xml.databaseChangeLog( xmlns : "http://www.liquibase.org/xml/ns/dbchangelog/1.9"
, "xmlns:xsi" : "http://www.w3.org/2001/XMLSchema-instance"
, "xsi:schemaLocation" : "http://www.liquibase.org/xml/ns/dbchangelog/1.9 http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-1.9.xsd"
) {
tables.each { table ->
changeSet(author: author, id : changesetId++) {
createTable( table.getAttributes() ) {
table.columns.each { col ->
column(col.getAttributes() ) {
if(col.getConstraintsAttributes()) {
constraints(col.getConstraintsAttributes())
}
}
}
}
}
}
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.