Skip to content

Instantly share code, notes, and snippets.

@sqrtM
Created February 14, 2025 16:23
Show Gist options
  • Save sqrtM/0fd6caf55237dd209753ca6561f200be to your computer and use it in GitHub Desktop.
Save sqrtM/0fd6caf55237dd209753ca6561f200be to your computer and use it in GitHub Desktop.

basic little formatter that I use to export query plans from datagrip.

i used to use the "pretty" formatter, but for complex plans, if you're using a viewer that auto-line wraps, it's basically unreadable like that. this formatter uses a lot less decoration, so is hopefully a bit more readable.

hope it helps. i was definitely looking for something like this for a while before i just sat down and wrote it

import com.intellij.openapi.util.text.StringUtil
NEWLINE = System.getProperty('line.separator')
static def splitByLines(values, size) {
def splitValues = []
def maxLines = 0
for (int i = 0; i < size; i++) {
def splitValue = StringUtil.splitByLines(values(i))
splitValues.add(splitValue)
maxLines = Math.max(maxLines, splitValue.size())
}
def byLines = new ArrayList<>(maxLines)
for (int i = 0; i < maxLines; i++) {
def lineValues = []
byLines.add(lineValues)
for (int j = 0; j < splitValues.size(); j++) {
def splitValue = splitValues[j]
lineValues.add(splitValue.size() <= i ? null : splitValue[i])
}
}
return byLines
}
def printRow(values, size) {
def byLines = splitByLines(values, size)
byLines.each { line ->
def lineSize = line.size()
if (lineSize > 0) OUT.append('')
for (int i = 0; i < lineSize; i++) {
def value = line[i] == null ? '' : line.get(i)
OUT.append(value)
if (i < lineSize - 1) OUT.append(' ')
}
OUT.append(NEWLINE)
}
}
def printRows() {
def colNames = COLUMNS*.name()
def rows = []
def widths = new int[COLUMNS.size()]
ROWS.each { row ->
def rowValues = COLUMNS.withIndex().collect { col, idx ->
def value = FORMATTER.format(row, col)
widths[idx] = Math.max(widths[idx], value.length())
value
}
rows.add(rowValues)
}
width = { widths[it] }
printRow({ '' }, COLUMNS.size())
printRow({ colNames[it] }, COLUMNS.size())
printRow({ '' }, 5)
rows.each { row ->
printRow({ row[it] }, row.size())
}
}
def printRowsTransposed() {
def valuesByRow = COLUMNS.collect { col -> new ArrayList<String>([col.name()]) }
ROWS.each { row ->
COLUMNS.eachWithIndex { col, i ->
def formattedValue = FORMATTER.format(row, col)
valuesByRow[i].add(formattedValue)
}
}
valuesByRow.each { row ->
printRow({ row[it] }, row.size())
}
}
if (TRANSPOSED) {
printRowsTransposed()
} else {
printRows()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment