-
Notifications
You must be signed in to change notification settings - Fork 9
/
Generate Kotlin-Model.groovy
364 lines (321 loc) · 14.8 KB
/
Generate Kotlin-Model.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
import com.intellij.database.model.DasColumn
import com.intellij.database.model.DasObject
import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.codeStyle.NameUtil
import groovy.json.JsonSlurper
/*
* Available context bindings:
* SELECTION Iterable<DasObject>
* PROJECT project
* FILES files helper
*/
DEBUG = false // if true output debug trace to debug.log
// can be overridden in model-config.json
classFileNameSuffix = "Model" // appended to class file name
downsizeLongIdToInt = true // if true changes id columns which would be declared Long to Int, change this to false to leave them as Long
fileExtension = ".kt" // file extension for generated models
forceBooleanTinyInt = "" // regex for column names marked as boolean when tinyint, only needed if using jdbc introspection which does not report actual declared type so all tinyint are tinyint(3)
snakeCaseTables = false // if true convert snake_case table names to Pascal case, else leave as is
sp = " " // string to use for each indent level
//forceBooleanTinyInt = (~/^(?:deleted|checkedStatus|checked_status|optionState|option_state)$/)
typeMapping = [
(~/(?i)tinyint\(1\)/) : "Boolean",
(~/(?i)tinyint/) : "TinyInt", // changed to Int if column name not in forceBooleanTinyInt
(~/(?i)bigint/) : "Long",
(~/(?i)int/) : "Int",
(~/(?i)float/) : "Float",
(~/(?i)double|decimal|real/): "Double",
(~/(?i)datetime|timestamp/) : "Timestamp",
(~/(?i)date/) : "Date",
(~/(?i)time/) : "Time",
(~/(?i)/) : "String"
]
FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { File dir ->
// read in possible map of tables to subdirectories
def tableMap = null
String packagePrefix = ""
String removePrefix = ""
boolean skipUnmapped = false
File exportDir = dir
File mapFile = null
File projectDir = null
def File tryDir = dir
while (tryDir != null && tryDir.exists() && tryDir.isDirectory()) {
def File tryMap = new File(tryDir, "model-config.json")
if (tryMap.isFile() && tryMap.canRead()) {
mapFile = tryMap
exportDir = tryDir
break
}
// see if this directory has .idea, then must be project root
tryMap = new File(tryDir, ".idea")
if (tryMap.isDirectory() && tryMap.exists()) {
projectDir = tryDir
break
}
tryDir = tryDir.parentFile
}
String packageName
if (projectDir != null) {
packageName = exportDir.path.substring(projectDir.path.length() + 1).replace('/', '.')
// now drop first part since it is most likely sources root and not part of the package path
int dot = packageName.indexOf('.')
if (dot > 0) packageName = packageName.substring(dot + 1)
} else {
packageName = "com.sample"
}
if (DEBUG) {
new File(exportDir, "debug.log").withPrintWriter { PrintWriter dbg ->
dbg.println("exportDir: ${exportDir.path}, mapFile: ${mapFile}")
if (mapFile != null && mapFile.isFile() && mapFile.canRead()) {
JsonSlurper jsonSlurper = new JsonSlurper()
def reader = new BufferedReader(new InputStreamReader(new FileInputStream(mapFile), "UTF-8"))
data = jsonSlurper.parse(reader)
if (DEBUG && data != null) {
packagePrefix = data["package-prefix"] ?: ""
removePrefix = data["remove-prefix"] ?: ""
skipUnmapped = data["skip-unmapped"] ?: false
tableMap = data["file-map"]
dbg.println("package-prefix: '$packagePrefix'")
dbg.println ""
dbg.println("skip-unmapped: $skipUnmapped")
dbg.println ""
dbg.println "file-map: {"
tableMap.each { dbg.println " $it" }
dbg.println "}"
dbg.println ""
}
}
SELECTION.filter { DasObject it -> it instanceof DasTable && it.getKind() == ObjectKind.TABLE }.each { DasTable it ->
generate(dbg, it, exportDir, tableMap, packageName, packagePrefix, removePrefix, skipUnmapped)
}
}
} else {
PrintWriter dbg = null
if (mapFile != null && mapFile.isFile() && mapFile.canRead()) {
JsonSlurper jsonSlurper = new JsonSlurper()
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(mapFile), "UTF-8"))
data = jsonSlurper.parse(reader)
packagePrefix = data["package-prefix"] ?: ""
removePrefix = data["remove-prefix"] ?: ""
skipUnmapped = data["skip-unmapped"] ?: false
// grab values from config
classFileNameSuffix = data["classFileNameSuffix"] ?: classFileNameSuffix
downsizeLongIdToInt = data["downsizeLongIdToInt"] ?: downsizeLongIdToInt
fileExtension = data["fileExtension"] ?: fileExtension
forceBooleanTinyInt = data["forceBooleanTinyInt"] ?: forceBooleanTinyInt
snakeCaseTables = data["snakeCaseTables"] ?: snakeCaseTables
sp = data["indent"] ?: sp
tableMap = data["file-map"]
}
SELECTION.filter { DasObject it -> it instanceof DasTable && it.getKind() == ObjectKind.TABLE }.each { DasTable it ->
generate(dbg, it, exportDir, tableMap, packageName, packagePrefix, removePrefix, skipUnmapped)
}
}
}
void generate(PrintWriter dbg, DasTable table, File dir, tableMap, String packageName, String packagePrefix, String removePrefix, boolean skipUnmapped) {
String className = snakeCaseTables ? toJavaName(toSingular(table.getName()), true) : toSingular(table.getName())
dbg.println("className: ${className}, tableName: ${table.getName()}, singular: ${toSingular(table.getName())}")
def fields = calcFields(table)
String fileName = className + "${classFileNameSuffix}$fileExtension"
def mappedFile = tableMap != null ? tableMap[fileName] : null
if (mappedFile == null && tableMap != null && tableMap[""] != null) {
mappedFile = suffixOnceWith(tableMap[""], "/") + fileName
}
if (dbg != null) dbg.println "fileName ${fileName} mappedFile ${mappedFile}"
def file
if (mappedFile != null && !mappedFile.trim().isEmpty()) {
file = new File(dir, mappedFile);
String unprefixed = (removePrefix == "" || !mappedFile.startsWith(removePrefix)) ? mappedFile : mappedFile.substring(removePrefix.length())
packageName = packagePrefix + new File(unprefixed).parent.replace("/", ".")
} else {
file = new File(dir, fileName)
packageName = packageName
if (dbg != null && (skipUnmapped || mappedFile != null)) dbg.println "skipped ${fileName}"
if (skipUnmapped || mappedFile != null) return
}
file.withPrintWriter { out -> generateModel(dbg, out, (String) table.getName(), className, fields, packageName) }
}
static String defaultValue(def value) {
String text = (String) value
return text == null ? "" : (text == "CURRENT_TIMESTAMP" ? " $text" : " '$text'")
}
def calcFields(table) {
def colIndex = 0
DasUtil.getColumns(table).reduce([]) { def fields, DasColumn col ->
def dataType = col.getDataType()
def spec = dataType.getSpecification()
def suffix = dataType.suffix
def typeStr = (String) typeMapping.find { p, t -> p.matcher(Case.LOWER.apply(spec)).find() }.value
def colName = (String) col.getName()
def colNameLower = (String) Case.LOWER.apply(colName)
colIndex++
def colType = downsizeLongIdToInt && typeStr == "Long" && DasUtil.isPrimary(col) || DasUtil.isForeign(col) && colNameLower.endsWith("id") ? "Int" : typeStr
def javaColName = (String) toJavaName(colName, false)
if (typeStr == "TinyInt") {
if (forceBooleanTinyInt && javaColName.matches(forceBooleanTinyInt)) {
colType = "Boolean"
} else {
colType = "Int"
}
}
def attrs = col.getTable().getColumnAttrs(col)
def columnDefault = col.getDefault()
def isAutoInc = DasUtil.isAutoGenerated(col)
def isAuto = isAutoInc || columnDefault == "CURRENT_TIMESTAMP" || attrs.contains(DasColumn.Attribute.COMPUTED)
fields += [[
name : javaColName,
column : colName,
type : colType,
suffix : suffix,
col : col,
spec : spec,
attrs : attrs,
default : columnDefault,
// constraints : constraints.reduce("") { all, constraint ->
// all += "[ name: ${constraint.name}, " + "kind: ${constraint.getKind()}," + "]"
// },
notNull : col.isNotNull(),
autoInc : isAutoInc,
nullable: !col.isNotNull() || isAuto || columnDefault != null,
key : DasUtil.isPrimary(col),
auto : isAuto,
annos : ""]]
fields
}
}
static String rightPad(String text, int len) {
def padded = text
def pad = len - text.length()
while (pad-- > 0) padded += " "
return padded
}
static String suffixOnceWith(String str, String suffix) {
return str.endsWith(suffix) ? str : "$str$suffix";
}
static String lowerFirst(String str) {
return str.length() > 0 ? Case.LOWER.apply(str[0]) + str[1..-1] : str
}
static String toSingular(String str) {
String[] s = NameUtil.splitNameIntoWords(str).collect { it }
String lastSingular = StringUtil.unpluralize(s[-1]) ?: ""
return str.substring(0, str.length() - s[-1].length()) + lastSingular
}
static String toPlural(String str) {
String[] s = NameUtil.splitNameIntoWords(str).collect { it }
String lastPlural = StringUtil.pluralize(s[-1]) ?: ""
return str.substring(0, str.length() - s[-1].length()) + lastPlural
}
static String toJavaName(String str, boolean capitalize) {
String s = 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]
}
void generateModel(PrintWriter dbg, PrintWriter out, String tableName, String className, def fields, String packageName) {
def dbCase = true
def keyCount = 0
def nonKeyCount = 0
def timestampCount = 0
def dateCount = 0
def timeCount = 0
fields.each() {
if (it.name != it.column) dbCase = false
if (it.key) keyCount++
else nonKeyCount++
if (it.type == "Timestamp") timestampCount++
else if (it.type == "Date") dateCount++
else if (it.type == "Time") timeCount++
}
// set single key to nullable and auto
if (keyCount == 1 && nonKeyCount > 0) {
fields.each() {
if (it.key) {
it.nullable = true
it.auto = true
}
}
}
out.println "package $packageName"
out.println ""
out.println "import com.vladsch.kotlin.jdbc.Model"
out.println "import com.vladsch.kotlin.jdbc.Session"
// out.println "import com.vladsch.kotlin.jdbc.ModelCompanion"
if (timestampCount > 0) out.println "import java.sql.Timestamp"
if (dateCount > 0) out.println "import java.sql.Date"
if (timeCount > 0) out.println "import java.sql.Time"
// out.println "import javax.json.JsonObject"
out.println ""
out.println "data class $className("
def sep = "";
fields.each() {
out.print sep
sep = ",\n";
if (it.annos != "") out.println "${sp}${it.annos}"
out.print "${sp}val ${it.name}: ${it.type}"
if (it.nullable) out.print "?"
// if (it.attrs != null) out.print(" // attrs: '${it.attrs}'")
// if (it.default != null) out.print(" // default: '${it.default}'")
if (it.suffix != null && it.suffix != "") out.print(" // suffix: '${it.suffix}'")
}
out.println "\n)"
out.println ""
// model class
out.println "@Suppress(\"MemberVisibilityCanBePrivate\")"
out.println "class ${className}Model(session: Session? = null, quote: String? = null) : Model<${className}Model, ${className}>(session, tableName, dbCase = ${dbCase}, quote = quote) {"
def maxWidth = 0
def lines = []
fields.each() {
def line = ""
if (it.annos != "") line += "${sp}${it.annos}"
line += "${sp}var ${it.name}: ${it.type}"
if (it.nullable) line += "?"
line += " by db"
if (it.auto && it.key) line += ".autoKey"
else if (it.auto) line += ".auto"
else if (it.key) line += ".key"
else if (it.default) line += ".default"
if (maxWidth < line.length()) maxWidth = line.length()
lines.add(line)
}
maxWidth += 7 - (maxWidth % 4)
def i = 0
lines.each() { it ->
out.print rightPad(it, maxWidth)
out.println "// ${fields[i].column} ${fields[i].spec}${fields[i].notNull ? " NOT NULL" : ""}${fields[i].autoInc ? " AUTO_INCREMENT" : ""}${defaultValue(fields[i].default)}${fields[i].suffix != null ? " ${fields[i].suffix}" : ""}"
i++
}
// data copy constructor
out.println ""
out.println "${sp}constructor(other: ${className}, session: Session? = null, quote: String? = null) : this(session, quote) {"
fields.each() {
out.println "${sp}${sp}${it.name} = other.${it.name}"
}
out.println "${sp}${sp}snapshot()"
out.println "${sp}}"
out.println ""
// copy factory
out.println "${sp}override operator fun invoke() = ${className}Model(_session, _quote)"
out.println ""
// data factory
out.println "${sp}override fun toData() = ${className}("
sep = "";
fields.each() {
out.print sep
sep = ",\n";
out.print "${sp}${sp}${it.name}"
}
out.println "\n${sp})"
out.println ""
out.println "${sp}companion object {"
out.println "${sp}${sp}const val tableName = \"${tableName}\""
// out.println "${sp}${sp}override fun createModel(quote:String?): ${className}Model = ${className}Model(quote)"
// out.println "${sp}${sp}override fun createData(model: ${className}Model): ${className} = model.toData()"
out.println "${sp}}"
out.println "}"
}