Skip to content

Instantly share code, notes, and snippets.

@pthiers
Last active March 7, 2024 14:26
Show Gist options
  • Star 32 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pthiers/6afa65b68947770e5b7ec07bec2117f2 to your computer and use it in GitHub Desktop.
Save pthiers/6afa65b68947770e5b7ec07bec2117f2 to your computer and use it in GitHub Desktop.
datagrip php array extractor
/*
* 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")
count = 0;
OUT.append("[").append(NEWLINE)
def printRow = { values, valueToString ->
OUT.append("\t[").append(NEWLINE)
values.eachWithIndex { value, idx ->
def str = valueToString(value)
str = str.replace("'","\\'")
OUT.append("\t\t'").append(value.name()).append("' => ")
if(str == "NULL" || str.isNumber()) {
OUT.append(str).append(",")
} else {
OUT.append("'").append(str).append("',")
}
OUT.append(NEWLINE)
}
OUT.append("\t],")
OUT.append(NEWLINE)
}
ROWS.each { row -> printRow(COLUMNS, { FORMATTER.format(row, it) }) }
OUT.append("];")
@pthiers
Copy link
Author

pthiers commented Jul 9, 2021

I had an issue with single quotes in my values, so had to ammend…

str = str.replace("'","\'")

… for …

str = str.replace("'","\\'")

… in case it helps someone.

Fixed! Thanks!!!

@whitefang57
Copy link

I was having an issue with some null values not being detected, as well as certain numbers (zip-codes starting with 0) being incorrectly parsed, so I replaced

if(str == "NULL") {
    OUT.append(str).append(",")
} else {
    OUT.append("'").append(str).append("',")
}

with

if(str == "NULL" || str == "null") {
    OUT.append(str).append(",")
} else if (str.isNumber() && str ==~ /^(0\.\d+|[1-9]\d*|\d)$/) {
    // The string is a number and doesn't start with 0
    // unless it is 0, or a decimal starting with 0
    OUT.append(str).append(",")
} else {
    OUT.append("'").append(str).append("',")
}

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