-
Notifications
You must be signed in to change notification settings - Fork 496
/
SqlDelightCompiler.kt
235 lines (211 loc) · 7.93 KB
/
SqlDelightCompiler.kt
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
/*
* Copyright (C) 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.sqldelight.core.compiler
import app.cash.sqldelight.core.SqlDelightFileIndex
import app.cash.sqldelight.core.capitalize
import app.cash.sqldelight.core.compiler.model.NamedQuery
import app.cash.sqldelight.core.compiler.model.SelectQueryable
import app.cash.sqldelight.core.lang.MigrationFile
import app.cash.sqldelight.core.lang.SqlDelightFile
import app.cash.sqldelight.core.lang.SqlDelightQueriesFile
import app.cash.sqldelight.core.lang.queriesName
import app.cash.sqldelight.core.lang.util.sqFile
import app.cash.sqldelight.dialect.api.SqlDelightDialect
import com.alecstrong.sql.psi.core.psi.InvalidElementDetectedException
import com.alecstrong.sql.psi.core.psi.NamedElement
import com.alecstrong.sql.psi.core.psi.SqlCreateViewStmt
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.psi.PsiElement
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.NameAllocator
import java.io.Closeable
private typealias FileAppender = (fileName: String) -> Appendable
object SqlDelightCompiler {
fun writeInterfaces(
module: Module,
dialect: SqlDelightDialect,
file: SqlDelightQueriesFile,
output: FileAppender,
) {
try {
writeTableInterfaces(file, output)
writeQueryInterfaces(file, output)
writeQueries(module, dialect, file, output)
} catch (e: InvalidElementDetectedException) {
// It's okay if compilation is cut short, we can just quit out.
}
}
fun writeInterfaces(
file: MigrationFile,
output: FileAppender,
includeAll: Boolean = false,
) {
writeTableInterfaces(file, output, includeAll)
}
fun writeDatabaseInterface(
module: Module,
file: SqlDelightFile,
implementationFolder: String,
output: FileAppender,
) {
writeQueryWrapperInterface(module, file, implementationFolder, output)
}
fun writeImplementations(
module: Module,
sourceFile: SqlDelightFile,
implementationFolder: String,
output: FileAppender,
) {
val fileIndex = SqlDelightFileIndex.getInstance(module)
val packageName = "${fileIndex.packageName}.$implementationFolder"
val databaseImplementationType = DatabaseGenerator(module, sourceFile).type()
val exposer = DatabaseExposerGenerator(databaseImplementationType, fileIndex, sourceFile.generateAsync)
val fileSpec = FileSpec.builder(packageName, databaseImplementationType.name!!)
.addProperty(exposer.exposedSchema())
.addFunction(exposer.exposedConstructor())
.addType(databaseImplementationType)
.build()
fileIndex.outputDirectory(sourceFile).forEach { outputDirectory ->
val packageDirectory = "$outputDirectory/${packageName.replace(".", "/")}"
fileSpec.writeToAndClose(output("$packageDirectory/${databaseImplementationType.name}.kt"))
}
}
private fun writeQueryWrapperInterface(
module: Module,
sourceFile: SqlDelightFile,
implementationFolder: String,
output: FileAppender,
) {
val fileIndex = SqlDelightFileIndex.getInstance(module)
val packageName = fileIndex.packageName
val queryWrapperType = DatabaseGenerator(module, sourceFile).interfaceType()
val fileSpec = FileSpec.builder(packageName, queryWrapperType.name!!)
// TODO: Remove these when kotlinpoet supports top level types.
.addImport("$packageName.$implementationFolder", "newInstance", "schema")
.apply {
var index = 0
fileIndex.dependencies.forEach {
addAliasedImport(ClassName(it.packageName, it.className), "${it.className}${index++}")
}
}
.addType(queryWrapperType)
.build()
fileIndex.outputDirectory(sourceFile).forEach { outputDirectory ->
val packageDirectory = "$outputDirectory/${packageName.replace(".", "/")}"
fileSpec.writeToAndClose(output("$packageDirectory/${queryWrapperType.name}.kt"))
}
}
internal fun writeTableInterfaces(
file: SqlDelightFile,
output: FileAppender,
includeAll: Boolean = false,
) {
val packageName = file.packageName ?: return
file.tables(includeAll).forEach { query ->
val statement = query.tableName.parent
if (statement is SqlCreateViewStmt && statement.compoundSelectStmt != null) {
listOf(NamedQuery(allocateName(statement.viewName), SelectQueryable(statement.compoundSelectStmt!!)))
.writeQueryInterfaces(file, output)
return@forEach
}
val fileSpec = FileSpec.builder(packageName, allocateName(query.tableName))
.apply {
tryWithElement(statement) {
val generator = TableInterfaceGenerator(query)
addType(generator.kotlinImplementationSpec())
}
}
.build()
statement.sqFile().generatedDirectories?.forEach { directory ->
fileSpec.writeToAndClose(output("$directory/${allocateName(query.tableName).capitalize()}.kt"))
}
}
}
internal fun writeQueryInterfaces(
file: SqlDelightQueriesFile,
output: FileAppender,
) {
file.namedQueries.writeQueryInterfaces(file, output)
}
internal fun writeQueries(
module: Module,
dialect: SqlDelightDialect,
file: SqlDelightQueriesFile,
output: FileAppender,
) {
val packageName = file.packageName ?: return
val queriesType = QueriesTypeGenerator(module, file, dialect)
.generateType(packageName) ?: return
val fileSpec = FileSpec.builder(packageName, file.queriesName.capitalize())
.addType(queriesType)
.build()
file.generatedDirectories?.forEach { directory ->
fileSpec.writeToAndClose(output("$directory/${queriesType.name}.kt"))
}
}
internal fun allocateName(namedElement: NamedElement): String {
return NameAllocator().newName(namedElement.normalizedName)
}
private fun List<NamedQuery>.writeQueryInterfaces(file: SqlDelightFile, output: FileAppender) {
return filter { tryWithElement(it.select) { it.needsInterface() } == true }
.forEach { namedQuery ->
val fileSpec = FileSpec.builder(namedQuery.interfaceType.packageName, namedQuery.name)
.apply {
tryWithElement(namedQuery.select) {
val generator = QueryInterfaceGenerator(namedQuery)
addType(generator.kotlinImplementationSpec())
}
}
.build()
file.generatedDirectories(namedQuery.interfaceType.packageName)?.forEach { directory ->
fileSpec.writeToAndClose(output("$directory/${namedQuery.name.capitalize()}.kt"))
}
}
}
private val NamedElement.normalizedName: String
get() {
val f = name[0]
val l = name[name.lastIndex]
return if ((f in "\"'`" && f == l) || (f == '[' && l == ']')) {
name.substring(1, name.length - 1)
} else {
name
}
}
private fun FileSpec.writeToAndClose(appendable: Appendable) {
writeTo(appendable)
if (appendable is Closeable) appendable.close()
}
}
internal fun <T> tryWithElement(
element: PsiElement,
block: () -> T,
): T? {
try {
return block()
} catch (e: ProcessCanceledException) {
throw e
} catch (e: InvalidElementDetectedException) {
// It's okay if compilation is cut short, we can just quit out.
return null
} catch (e: Throwable) {
val exception = IllegalStateException("Failed to compile $element :\n${element.text}")
exception.initCause(e)
throw exception
}
}