-
Notifications
You must be signed in to change notification settings - Fork 25
/
Generate POCO.groovy
61 lines (53 loc) · 2.33 KB
/
Generate POCO.groovy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
typeMapping = [
(~/(?i)^bit$/) : "bool",
(~/(?i)^tinyint$/) : "byte",
(~/(?i)^uniqueidentifier|uuid$/) : "Guid",
(~/(?i)^int|integer|number$/) : "int",
(~/(?i)^bigint$/) : "long",
(~/(?i)^varbinary|image$/) : "byte[]",
(~/(?i)^double|float|real$/) : "double",
(~/(?i)^decimal|money|numeric|smallmoney$/) : "decimal",
(~/(?i)^datetimeoffset$/) : "DateTimeOffset",
(~/(?i)^datetime|datetime2|timestamp|date|time$/) : "DateTime",
(~/(?i)^char$/) : "char",
]
notNullableTypes = [ "string", "byte[]" ]
FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
SELECTION.filter { it instanceof DasTable && it.getKind() == ObjectKind.TABLE }.each { generate(it, dir) }
}
def generate(table, dir) {
def className = csharpName(table.getName())
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 "public class $className"
out.println "{"
fields.each() {
out.println ""
out.println " public ${it.type} ${it.name} { 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 ?: "string"
def nullable = col.isNotNull() || typeStr in notNullableTypes ? "" : "?"
fields += [[
name : csharpName(col.getName()),
type : typeStr + nullable]]
}
}
def csharpName(str) {
com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
.collect { Case.LOWER.apply(it).capitalize() }
.join("")
}