Created
December 3, 2018 13:28
-
-
Save maartenba/532f0ea66bcf0b600bc16334afe6c5b0 to your computer and use it in GitHub Desktop.
Rider generate C# from database
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
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 = "RiderGenerated" | |
typeMapping = [ | |
(~/(?i)int/) : "long", | |
(~/(?i)float|double|decimal|real/) : "double", | |
(~/(?i)datetime|timestamp|date|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 = csharpName(table.getName(), true) | |
def fields = calcFields(table) | |
new File(dir, className + ".cs").withPrintWriter { 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() { | |
out.println " public ${it.type} ${it.name.capitalize()} { get; set; }" | |
} | |
out.println " }" | |
out.println "}" | |
} | |
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 : csharpName(col.getName(), false), | |
type : typeStr, | |
annos: ""]] | |
} | |
} | |
def csharpName(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