forked from cashapp/sqldelight
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DatabaseGenerator.kt
278 lines (252 loc) · 9.97 KB
/
DatabaseGenerator.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
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
/*
* Copyright (C) 2017 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.SqlDelightException
import app.cash.sqldelight.core.SqlDelightFileIndex
import app.cash.sqldelight.core.lang.ASYNC_RESULT_TYPE
import app.cash.sqldelight.core.lang.DATABASE_SCHEMA_TYPE
import app.cash.sqldelight.core.lang.DRIVER_NAME
import app.cash.sqldelight.core.lang.DRIVER_TYPE
import app.cash.sqldelight.core.lang.QUERY_RESULT_TYPE
import app.cash.sqldelight.core.lang.SUSPENDING_TRANSACTER_IMPL_TYPE
import app.cash.sqldelight.core.lang.SUSPENDING_TRANSACTER_TYPE
import app.cash.sqldelight.core.lang.SqlDelightFile
import app.cash.sqldelight.core.lang.TRANSACTER_IMPL_TYPE
import app.cash.sqldelight.core.lang.TRANSACTER_TYPE
import app.cash.sqldelight.core.lang.UNIT_RESULT_TYPE
import app.cash.sqldelight.core.lang.queriesName
import app.cash.sqldelight.core.lang.queriesType
import app.cash.sqldelight.core.lang.util.forInitializationStatements
import app.cash.sqldelight.core.lang.util.migrationFiles
import app.cash.sqldelight.core.lang.util.queryFiles
import app.cash.sqldelight.core.lang.util.rawSqlText
import com.alecstrong.sql.psi.core.psi.SqlStmt
import com.intellij.openapi.module.Module
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.INT
import com.squareup.kotlinpoet.KModifier.OPERATOR
import com.squareup.kotlinpoet.KModifier.OVERRIDE
import com.squareup.kotlinpoet.KModifier.PRIVATE
import com.squareup.kotlinpoet.ParameterSpec
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.asTypeName
internal class DatabaseGenerator(
module: Module,
sourceFile: SqlDelightFile,
) {
private val sourceFolders = SqlDelightFileIndex.getInstance(module).sourceFolders(sourceFile)
private val moduleFolders = SqlDelightFileIndex.getInstance(module)
.sourceFolders(sourceFile, includeDependencies = false)
private val fileIndex = SqlDelightFileIndex.getInstance(module)
private val type = ClassName(fileIndex.packageName, fileIndex.className)
private val dialect = sourceFile.dialect
private val generateAsync = sourceFile.generateAsync
fun interfaceType(): TypeSpec {
val typeSpec = TypeSpec.interfaceBuilder(fileIndex.className)
.addSuperinterface(if (generateAsync) SUSPENDING_TRANSACTER_TYPE else TRANSACTER_TYPE)
fileIndex.dependencies.forEach {
typeSpec.addSuperinterface(ClassName(it.packageName, it.className))
}
val invoke = FunSpec.builder("invoke")
.returns(ClassName(fileIndex.packageName, fileIndex.className))
.addModifiers(OPERATOR)
val invokeReturn = CodeBlock.builder()
.add("return %T::class.newInstance(", type)
// Database constructor parameter:
// driver: SqlDriver
val dbParameter = ParameterSpec.builder(DRIVER_NAME, DRIVER_TYPE).build()
invoke.addParameter(dbParameter)
invokeReturn.add("%N", dbParameter)
moduleFolders.flatMap { it.queryFiles() }
.filterNot { it.isEmpty() }
.sortedBy { it.name }
.forEach { file ->
// queries property added to QueryWrapper type:
// val dataQueries = DataQueries(this, driver)
typeSpec.addProperty(file.queriesName, file.queriesType)
}
forAdapters {
invoke.addParameter(it.name, it.type)
invokeReturn.add(", %L", it.name)
}
return typeSpec
.addType(
TypeSpec.companionObjectBuilder()
.addProperty(
PropertySpec.builder("Schema", DATABASE_SCHEMA_TYPE)
.getter(
FunSpec.getterBuilder()
.addStatement("return %T::class.schema", type)
.build()
)
.build()
)
.addFunction(
invoke
.addCode(
invokeReturn
.add(")")
.build()
)
.build()
)
.build()
)
.build()
}
private fun forAdapters(
block: (PropertySpec) -> Unit
) {
sourceFolders
.flatMap { it.queryFiles() }
.flatMap { it.requiredAdapters }
.sortedBy { it.name }
.toSet()
.forEach(block)
}
fun type(): TypeSpec {
val typeSpec = TypeSpec.classBuilder("${fileIndex.className}Impl")
.superclass(if (generateAsync) SUSPENDING_TRANSACTER_IMPL_TYPE else TRANSACTER_IMPL_TYPE)
.addModifiers(PRIVATE)
.addSuperclassConstructorParameter(DRIVER_NAME)
val constructor = FunSpec.constructorBuilder()
// Database constructor parameter:
// driver: SqlDriver
val dbParameter = ParameterSpec.builder(DRIVER_NAME, DRIVER_TYPE).build()
constructor.addParameter(dbParameter)
// Static on create function:
// fun create(driver: SqlDriver)
val createFunction = FunSpec.builder("create")
.addModifiers(OVERRIDE)
.returns(QUERY_RESULT_TYPE.parameterizedBy(Unit::class.asTypeName()))
.addParameter(DRIVER_NAME, DRIVER_TYPE)
val oldVersion = ParameterSpec.builder("oldVersion", INT).build()
val newVersion = ParameterSpec.builder("newVersion", INT).build()
val migrateFunction = FunSpec.builder("migrate")
.addModifiers(OVERRIDE)
.returns(QUERY_RESULT_TYPE.parameterizedBy(Unit::class.asTypeName()))
.addParameter(DRIVER_NAME, DRIVER_TYPE)
.addParameter(oldVersion)
.addParameter(newVersion)
forAdapters {
constructor.addParameter(it.name, it.type)
}
sourceFolders.flatMap { it.queryFiles() }
.filterNot { it.isEmpty() }
.sortedBy { it.name }
.forEach { file ->
var adapters = ""
if (file.requiredAdapters.isNotEmpty()) {
adapters = file.requiredAdapters.joinToString(
prefix = ", ",
transform = { it.name }
)
}
// queries property added to QueryWrapper type:
// val dataQueries = DataQueries(this, driver, transactions)
typeSpec.addProperty(
PropertySpec.builder(file.queriesName, file.queriesType)
.addModifiers(OVERRIDE)
.initializer("%T($DRIVER_NAME$adapters)", file.queriesType)
.build()
)
}
if (generateAsync) {
createFunction.beginControlFlow("return %T", ASYNC_RESULT_TYPE)
migrateFunction.beginControlFlow("return %T", ASYNC_RESULT_TYPE)
}
if (!fileIndex.deriveSchemaFromMigrations) {
// Derive the schema from queries files.
sourceFolders.flatMap { it.queryFiles() }
.sortedBy { it.name }
.forInitializationStatements(dialect.allowsReferenceCycles) { sqlText ->
val statement = if (generateAsync) "$DRIVER_NAME.execute(null, %L, 0).await()" else "$DRIVER_NAME.execute(null, %L, 0)"
createFunction.addStatement(statement, sqlText.toCodeLiteral())
}
} else {
val orderedMigrations = sourceFolders.flatMap { it.migrationFiles() }
.sortedBy { it.order }
// Derive the schema from migration files.
orderedMigrations.flatMap { it.sqlStatements() }
.filter { it.isSchema() }
.forEach {
val statement = if (generateAsync) "$DRIVER_NAME.execute(null, %L, 0).await()" else "$DRIVER_NAME.execute(null, %L, 0)"
createFunction.addStatement(statement, it.rawSqlText().toCodeLiteral())
}
}
var maxVersion = 1
sourceFolders.flatMap { it.migrationFiles() }
.sortedBy { it.version }
.forEach { migrationFile ->
try {
maxVersion = maxOf(maxVersion, migrationFile.version + 1)
} catch (e: Throwable) {
throw SqlDelightException("Migration files can only have versioned names (1.sqm, 2.sqm, etc)")
}
migrateFunction.beginControlFlow(
"if (%N <= ${migrationFile.version} && %N > ${migrationFile.version})",
oldVersion, newVersion
)
migrationFile.sqlStatements().forEach {
migrateFunction.addStatement(
if (generateAsync) "$DRIVER_NAME.execute(null, %S, 0).await()" else "$DRIVER_NAME.execute(null, %S, 0)",
it.rawSqlText()
)
}
migrateFunction.endControlFlow()
}
if (!generateAsync) {
createFunction.addStatement("return %T", UNIT_RESULT_TYPE)
migrateFunction.addStatement("return %T", UNIT_RESULT_TYPE)
} else {
createFunction.endControlFlow()
migrateFunction.endControlFlow()
}
return typeSpec
.addType(
TypeSpec.objectBuilder("Schema")
.addSuperinterface(DATABASE_SCHEMA_TYPE)
.addFunction(createFunction.build())
.addFunction(migrateFunction.build())
.addProperty(
PropertySpec.builder("version", INT, OVERRIDE)
.getter(FunSpec.getterBuilder().addStatement("return $maxVersion").build())
.build()
)
.build()
)
.addSuperinterface(ClassName(fileIndex.packageName, fileIndex.className))
.primaryConstructor(constructor.build())
.build()
}
private fun SqlStmt.isSchema() = when {
createIndexStmt != null -> true
createTableStmt != null -> true
createTriggerStmt != null -> true
createViewStmt != null -> true
createVirtualTableStmt != null -> true
alterTableStmt != null -> true
dropIndexStmt != null -> true
dropTableStmt != null -> true
dropTriggerStmt != null -> true
dropViewStmt != null -> true
else -> false
}
}