Created
March 7, 2019 06:55
-
-
Save antpk/8b4ef1dc0d52a52648901cc7af83e6c9 to your computer and use it in GitHub Desktop.
SQL Bulk insert export script for DataGrip with limit
This file contains hidden or 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
SEP = ", " | |
QUOTE = "\'" | |
NEWLINE = System.getProperty("line.separator") | |
KEYWORDS_LOWERCASE = com.intellij.database.util.DbSqlUtil.areKeywordsLowerCase(PROJECT) | |
KW_INSERT_INTO = KEYWORDS_LOWERCASE ? "insert into " : "INSERT INTO " | |
KW_VALUES = KEYWORDS_LOWERCASE ? "values" : "VALUES" | |
KW_NULL = KEYWORDS_LOWERCASE ? "null" : "NULL" | |
OUT.append(KW_INSERT_INTO) | |
if (TABLE == null) OUT.append("MY_TABLE") | |
else OUT.append(TABLE.getParent().getName()).append(".").append(TABLE.getName()) | |
OUT.append(" (") | |
COLUMNS.eachWithIndex { column, idx -> | |
OUT.append(column.name()).append(idx != COLUMNS.size() - 1 ? SEP : "") | |
} | |
OUT.append(")").append(NEWLINE).append(KW_VALUES) | |
def record(columns, dataRow, close) { | |
OUT.append(NEWLINE).append("(") | |
columns.eachWithIndex { column, idx -> | |
def value = dataRow.value(column) | |
def skipQuote = value.toString().isNumber() || value == null | |
def stringValue = value != null ? FORMATTER.format(dataRow, column) : KW_NULL | |
if (DIALECT.getDbms().isMysql()) stringValue = stringValue.replace("\\", "\\\\") | |
OUT.append(skipQuote ? "": QUOTE).append(stringValue.replace(QUOTE, QUOTE + QUOTE)) | |
.append(skipQuote ? "": QUOTE).append(idx != columns.size() - 1 ? SEP : "") | |
} | |
deliMeter = dataRow.last() || close ? ";" : "," | |
OUT.append(")").append(deliMeter) | |
} | |
count = 0 | |
def createInsert(columns, dataRow) { | |
count++ | |
if (count%100 == 0 && !dataRow.last()) { | |
record(columns, dataRow, true) | |
OUT.append(NEWLINE).append(KW_INSERT_INTO) | |
if (TABLE == null) OUT.append("MY_TABLE") | |
else OUT.append(TABLE.getParent().getName()).append(".").append(TABLE.getName()) | |
OUT.append(" (") | |
COLUMNS.eachWithIndex { column, idx -> | |
OUT.append(column.name()).append(idx != COLUMNS.size() - 1 ? SEP : "") | |
} | |
OUT.append(")").append(NEWLINE).append(KW_VALUES) | |
return | |
} | |
record(columns, dataRow, false) | |
} | |
ROWS.each { row -> createInsert(COLUMNS, row) } |
This was super useful, thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Modified from gist by pasali
Please note this was a hack but worked for my purposes.