Skip to content

Instantly share code, notes, and snippets.

@nirleka
Last active November 13, 2019 18:34
Show Gist options
  • Save nirleka/f8615eaffdc557c2deb990e9893980fa to your computer and use it in GitHub Desktop.
Save nirleka/f8615eaffdc557c2deb990e9893980fa to your computer and use it in GitHub Desktop.
Intellij database extension Groovy script to copy JDL Entity to clipboard.
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
import java.awt.datatransfer.StringSelection
import java.awt.Toolkit
import java.awt.datatransfer.*
/*
* How to use:
* - right click table (you can use shift for multiple table)
* - Scripted extension > Generate Entity JDL.groovy
* - paste (ctrl + v) to JDL Studio https://start.jhipster.tech/jdl-studio/
*
* Available context bindings:
* SELECTION Iterable<DasObject>
* PROJECT project
* FILES files helper
*/
typeMapping = [
(~/(?i)bigint/) : "Long",
(~/(?i)int/) : "Integer",
(~/(?i)double|decimal|real/) : "Double",
(~/(?i)float/) : "Float",
(~/(?i)bigdecimal/) : "BigDecimal",
(~/(?i)boolean/) : "Boolean",
(~/(?i)datetime|timestamp/) : "ZonedDateTime",
(~/(?i)date/) : "LocalDate",
(~/(?i)uuid/) : "UUID",
(~/(?i)duration/) : "Duration",
(~/(?i)blob/) : "Blob",
(~/(?i)anyblob/) : "AnyBlob",
(~/(?i)imageblob/) : "ImageBlob",
(~/(?i)textblob/) : "TextBlob",
(~/(?i)instant/) : "Instant",
(~/(?i)/) : "String"
]
jdl = ""
final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard()
SELECTION.filter { it instanceof DasTable }.each { generate(it) }
clipboard.setContents(new StringSelection(jdl), null)
def generate(table) {
def className = javaName(table.getName(), true)
def fields = calcFields(table)
jdl += generateRow(className, fields)
}
def generateRow(className, fields) {
row = "";
row += "entity $className {\n"
fields.each() {
if (it.annos != "") row += " ${it.annos}\n"
row += " ${it.name} ${it.type}\n"
}
row += "}\n"
row += "\npaginate $className with pagination\n"
row += "service * with serviceClass\n"
return row;
}
def calcFields(table) {
DasUtil.getColumns(table).reduce([]) { fields, col ->
def spec = Case.LOWER.apply(col.getDataType().getSpecification())
def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
fields += [[
name : javaName(col.getName(), false),
type : typeStr,
annos: ""]]
}
}
def javaName(str, capitalize) {
def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
.collect { Case.LOWER.apply(it).capitalize() }
.join("")
.replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment