Skip to content

Instantly share code, notes, and snippets.

@deinspanjer
Created December 11, 2017 19:01
Show Gist options
  • Save deinspanjer/57158b788c7faaeb6658a001b0edb6f2 to your computer and use it in GitHub Desktop.
Save deinspanjer/57158b788c7faaeb6658a001b0edb6f2 to your computer and use it in GitHub Desktop.
/*
* 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() }
*/
SEPARATOR = ","
QUOTE = "'"
NEWLINE = System.getProperty("line.separator")
def printRow = { values, valueToString ->
def formatted = values.inject([]) { result, item ->
def str = valueToString(item)
def safeStr = "${ -> str.matches("-?[0-9.]+|true|TRUE|false|FALSE|null|NULL") ? str : "'${str}'" }"
result << safeStr
}
if (formatted.size() > 1) {
OUT.append("(${formatted.join(",")})")
} else {
OUT.append(formatted)
}
}
if (!TRANSPOSED) {
ROWS.each { row -> printRow(COLUMNS, { FORMATTER.format(row, it) }); OUT.append(row.last() ? "" : ",\n") }
}
else {
def values = COLUMNS.collect { new ArrayList<String>() }
ROWS.each { row -> COLUMNS.eachWithIndex { col, i -> values[i].add(FORMATTER.format(row, col)) } }
values.each { printRow(it, { it }) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment