Skip to content

Instantly share code, notes, and snippets.

@suhdev
Created August 3, 2021 22:48
Show Gist options
  • Save suhdev/f842f4cc0980d5cb94c7ed1031b73099 to your computer and use it in GitHub Desktop.
Save suhdev/f842f4cc0980d5cb94c7ed1031b73099 to your computer and use it in GitHub Desktop.
Generate C# Classes from Tables in DataGrip
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
/*
* Available context bindings:
* SELECTION Iterable<DasObject>
* PROJECT project
* FILES files helper
*/
packageName = "Sample.Entities"
typeMapping = [
(~/(?i)int/) : "long",
(~/(?i)decimal|real/): "decimal",
(~/(?i)float|double/): "double",
(~/(?i)datetime|timestamp/) : "DateTimeOffset",
(~/(?i)date/) : "DateTime",
(~/(?i)time/) : "DateTime",
(~/(?i)/) : "string"
]
FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}
def generate(table, dir) {
def className = javaName(table.getName(), true)
new File(dir, className + ".cs").withPrintWriter { out ->
def fields = calcFields(table, out)
generate(out, className, fields) }
}
def generate(out, className, fields) {
out.println "using System;"
out.println ""
out.println "namespace $packageName {"
out.println ""
out.println " public class $className {"
out.println ""
fields.each() {
if (it.annos != "") out.println " ${it.annos}"
def nullOp = "?";
if (it.notNull) nullOp = ""
out.println " public ${it.type}${nullOp} ${it.name.capitalize()} {get; set;}"
}
out.println " }"
out.println "}"
}
def calcFields(table, out) {
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,
notNull: col.notNull,
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