Skip to content

Instantly share code, notes, and snippets.

@davidwatkins73
Last active September 29, 2022 14:50
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save davidwatkins73/05f9011d56e52a5738be2d06b1d7a433 to your computer and use it in GitHub Desktop.
Save davidwatkins73/05f9011d56e52a5738be2d06b1d7a433 to your computer and use it in GitHub Desktop.
Jetbrains Intellij / Datagrip: Data Extractor - allows export of row data into Liquibase compatible insert statements
/*
* Available context bindings:
* COLUMNS List<DataColumn>
* ROWS Iterable<DataRow>
* OUT { append() }
* FORMATTER { format(row, col); formatValue(Object, col) }
* TRANSPOSED Boolean
* plus ALL_COLUMNS, TABLE, DIALECT
*
* where:
* DataRow { rowNumber(); first(); last(); data(): List<Object>; value(column): Object }
* DataColumn { columnNumber(), name() }
*/
import java.util.regex.Pattern
NEWLINE = System.getProperty("line.separator")
pattern = Pattern.compile("[^\\w\\d]")
def escapeTag(name) {
name = pattern.matcher(name).replaceAll("_")
return name.isEmpty() || !Character.isLetter(name.charAt(0)) ? "_$name" : name
}
def printRow = { values, rowTag, namer, valueToString ->
OUT.append("""$NEWLINE\t<${rowTag} tableName="${TABLE.name}">$NEWLINE""")
values.eachWithIndex { it, index ->
def colName = namer(it, index)
def str = valueToString(it)
OUT.append("""\t\t<column name="${colName}" value="${str}"/>$NEWLINE""")
}
OUT.append("\t</$rowTag>")
}
OUT.append(
"""
<changeSet id="xxx"
author="xxx">
\t<comment>Extracted changeset</comment>
""")
if (!TRANSPOSED) {
ROWS.each { row -> printRow(COLUMNS, "insert", {it, _ -> escapeTag(it.name())}) { FORMATTER.format(row, it) } }
}
else {
def values = COLUMNS.collect { new ArrayList<String>() }
ROWS.each { row -> COLUMNS.eachWithIndex { col, i -> values[i].add(FORMATTER.format(row, col)) } }
values.eachWithIndex { it, index -> printRow(it, escapeTag(COLUMNS[index].name()), { _, i -> "row${i + 1}" }, { it }) }
}
OUT.append("""
</changeSet>
""")
@davidwatkins73
Copy link
Author

davidwatkins73 commented May 13, 2019

Usage:
Copy contents into a new file located in your <workspace>\Scratches and Consoles\Extensions\Database Tools and SQL\data\extractors directory.

Todo:

  • omit generated columns (autosequence ids)
  • add username / timestap to change set metadata

@davidwatkins73
Copy link
Author

Adapted from the built-in xml exporter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment