-
Notifications
You must be signed in to change notification settings - Fork 25
/
Generate IPOCOs.groovy
59 lines (51 loc) · 2.29 KB
/
Generate IPOCOs.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
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, "I" + className + ".cs").withPrintWriter { out -> generate(out, className, fields) }
}
def generate(out, className, fields) {
out.println "using System;"
out.println ""
out.println "public interface I$className"
out.println "{"
fields.each() {
out.println " ${it.type} ${it.name} { get; set; }"
}
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("")
}