Created
September 19, 2024 00:18
-
-
Save macowie/b55f9b053864ae327ae32c4be822a5e5 to your computer and use it in GitHub Desktop.
SQL VALUES Data Extractor for Jetbrains DataGrip, Copy table data as formatted SQL `VALUES`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Adapted from One-row.sql.groovy included with DataGrip | |
* | |
* Available context bindings: | |
* COLUMNS List<DataColumn> | |
* ROWS Iterable<DataRow> | |
* OUT { append() } | |
* FORMATTER { format(row, col); formatValue(Object, col); getTypeName(Object, col); isStringLiteral(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 = "'" | |
STRING_PREFIX = DIALECT.getDbms().isMicrosoft() ? "N" : "" | |
KEYWORDS_LOWERCASE = com.intellij.database.util.DbSqlUtil.areKeywordsLowerCase(PROJECT) | |
KW_NULL = KEYWORDS_LOWERCASE ? "null" : "NULL" | |
OUT.append("VALUES ") | |
first_row = true | |
ROWS.each { row -> | |
OUT.append(first_row ? "(" : (SEPARATOR + "(")) | |
first_col = true | |
COLUMNS.each { column -> | |
def value = row.value(column) | |
def stringValue = value == null ? KW_NULL : FORMATTER.formatValue(value, column) | |
def isStringLiteral = value != null && FORMATTER.isStringLiteral(value, column) | |
if (isStringLiteral && DIALECT.getDbms().isMysql()) stringValue = stringValue.replace("\\", "\\\\") | |
OUT.append(first_col ? "" : SEPARATOR) | |
.append(isStringLiteral ? (STRING_PREFIX + QUOTE) : "") | |
.append(stringValue ? stringValue.replace(QUOTE, QUOTE + QUOTE) : stringValue) | |
.append(isStringLiteral ? QUOTE : "") | |
first_col = false | |
} | |
OUT.append(")") | |
first_row = false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment