-
Notifications
You must be signed in to change notification settings - Fork 496
/
SqlDelightEnvironment.kt
346 lines (305 loc) · 13.2 KB
/
SqlDelightEnvironment.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
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
/*
* 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
import app.cash.sqldelight.core.compiler.SqlDelightCompiler
import app.cash.sqldelight.core.lang.DatabaseFileType
import app.cash.sqldelight.core.lang.DatabaseFileViewProviderFactory
import app.cash.sqldelight.core.lang.MigrationFile
import app.cash.sqldelight.core.lang.MigrationFileType
import app.cash.sqldelight.core.lang.MigrationParserDefinition
import app.cash.sqldelight.core.lang.SqlDelightFile
import app.cash.sqldelight.core.lang.SqlDelightFileType
import app.cash.sqldelight.core.lang.SqlDelightParserDefinition
import app.cash.sqldelight.core.lang.SqlDelightQueriesFile
import app.cash.sqldelight.core.lang.util.migrationFiles
import app.cash.sqldelight.core.lang.util.sqFile
import app.cash.sqldelight.core.lang.validation.OptimisticLockValidator
import app.cash.sqldelight.core.psi.SqlDelightImportStmt
import app.cash.sqldelight.dialect.api.SqlDelightDialect
import com.alecstrong.sql.psi.core.SqlAnnotationHolder
import com.alecstrong.sql.psi.core.SqlCoreEnvironment
import com.alecstrong.sql.psi.core.SqlFileBase
import com.alecstrong.sql.psi.core.psi.SqlCreateTableStmt
import com.alecstrong.sql.psi.core.psi.SqlStmt
import com.intellij.core.CoreApplicationEnvironment
import com.intellij.mock.MockModule
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleExtension
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.FileTypeFileViewProviders
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiErrorElement
import com.intellij.psi.PsiFileSystemItem
import com.intellij.psi.PsiManager
import com.intellij.psi.util.PsiTreeUtil
import org.picocontainer.MutablePicoContainer
import java.io.File
import java.util.StringTokenizer
import kotlin.math.log10
import kotlin.system.measureTimeMillis
/**
* Mocks an intellij environment for compiling sqldelight files without an instance of intellij
* running.
*/
class SqlDelightEnvironment(
private val properties: SqlDelightDatabaseProperties,
private val compilationUnit: SqlDelightCompilationUnit,
private val verifyMigrations: Boolean,
override var dialect: SqlDelightDialect,
moduleName: String,
private val sourceFolders: List<File> = compilationUnit.sourceFolders
.filter { it.folder.exists() && !it.dependency }
.map { it.folder },
private val dependencyFolders: List<File> = compilationUnit.sourceFolders
.filter { it.folder.exists() && it.dependency }
.map { it.folder },
) : SqlCoreEnvironment(sourceFolders, dependencyFolders),
SqlDelightProjectService {
val project: Project = projectEnvironment.project
val module = MockModule(project, projectEnvironment.parentDisposable)
private val moduleName = SqlDelightFileIndex.sanitizeDirectoryName(moduleName)
init {
(project.picoContainer as MutablePicoContainer).registerComponentInstance(
SqlDelightProjectService::class.java.name,
this,
)
CoreApplicationEnvironment.registerExtensionPoint(
module.extensionArea,
ModuleExtension.EP_NAME,
ModuleExtension::class.java,
)
initializeApplication {
registerFileType(MigrationFileType, MigrationFileType.defaultExtension)
registerParserDefinition(MigrationParserDefinition())
registerFileType(SqlDelightFileType, SqlDelightFileType.defaultExtension)
registerParserDefinition(SqlDelightParserDefinition())
registerFileType(DatabaseFileType, DatabaseFileType.defaultExtension)
FileTypeFileViewProviders.INSTANCE.addExplicitExtension(DatabaseFileType, DatabaseFileViewProviderFactory())
}
}
override var treatNullAsUnknownForEquality: Boolean = properties.treatNullAsUnknownForEquality
override var generateAsync: Boolean = properties.generateAsync
override fun module(vFile: VirtualFile) = module
override fun fileIndex(module: Module): SqlDelightFileIndex = FileIndex()
override fun resetIndex() = throw UnsupportedOperationException()
override fun clearIndex() = throw UnsupportedOperationException()
override fun forSourceFiles(action: (SqlFileBase) -> Unit) {
super.forSourceFiles {
if (it.fileType != MigrationFileType ||
verifyMigrations ||
properties.deriveSchemaFromMigrations
) {
action(it)
}
}
}
/**
* Run the SQLDelight compiler and return the error or success status.
*/
fun generateSqlDelightFiles(logger: (String) -> Unit): CompilationStatus {
val errors = sortedMapOf<Int, MutableList<String>>()
val extraAnnotators = listOf(OptimisticLockValidator())
annotate(
object : SqlAnnotationHolder {
override fun createErrorAnnotation(element: PsiElement, s: String) {
val key = element.sqFile().order ?: Integer.MAX_VALUE
errors.putIfAbsent(key, ArrayList())
errors[key]!!.add(errorMessage(element, s))
}
},
extraAnnotators,
)
if (errors.isNotEmpty()) return CompilationStatus.Failure(errors.values.flatten())
val writer = writer@{ fileName: String ->
val file = File(fileName)
if (!file.exists()) {
file.parentFile.mkdirs()
file.createNewFile()
}
return@writer file.writer()
}
var sourceFile: SqlDelightFile? = null
var topMigrationFile: MigrationFile? = null
forSourceFiles {
if (it is MigrationFile && properties.deriveSchemaFromMigrations) {
if (topMigrationFile == null || it.order > topMigrationFile!!.order) topMigrationFile = it
if (sourceFile == null) sourceFile = it
}
if (it !is SqlDelightQueriesFile) return@forSourceFiles
logger("----- START ${it.name} ms -------")
val timeTaken = measureTimeMillis {
SqlDelightCompiler.writeInterfaces(module, dialect, it, writer)
sourceFile = it
}
logger("----- END ${it.name} in $timeTaken ms ------")
}
topMigrationFile?.let { migrationFile ->
logger("----- START ${migrationFile.name} ms -------")
val timeTaken = measureTimeMillis {
SqlDelightCompiler.writeInterfaces(
file = migrationFile,
output = writer,
includeAll = true,
)
SqlDelightCompiler.writeImplementations(module, migrationFile, moduleName, writer)
}
logger("----- END ${migrationFile.name} in $timeTaken ms ------")
}
sourceFile?.let {
SqlDelightCompiler.writeDatabaseInterface(module, it, moduleName, writer)
if (it is SqlDelightQueriesFile) {
SqlDelightCompiler.writeImplementations(module, it, moduleName, writer)
}
}
return CompilationStatus.Success()
}
fun forMigrationFiles(body: (MigrationFile) -> Unit) {
val psiManager = PsiManager.getInstance(projectEnvironment.project)
val migrationFiles: Collection<MigrationFile> = sourceFolders
.map { localFileSystem.findFileByPath(it.absolutePath)!! }
.map { psiManager.findDirectory(it)!! }
.flatMap { directory: PsiDirectory -> directory.migrationFiles() }
migrationFiles.sortedBy { it.version }
.forEach {
val errorElements = ArrayList<PsiErrorElement>()
PsiTreeUtil.processElements(it) { element ->
when (element) {
is PsiErrorElement -> errorElements.add(element)
// Uncomment when sqm files understand their state of the world.
// is SqlAnnotatedElement -> element.annotate(annotationHolder)
}
return@processElements true
}
if (errorElements.isNotEmpty()) {
throw SqlDelightException(
"Error Reading ${it.name}:\n\n" +
errorElements.joinToString(separator = "\n") { errorMessage(it, it.errorDescription) },
)
}
body(it)
}
}
private fun errorMessage(element: PsiElement, message: String): String =
"${element.containingFile.virtualFile.path}: (${element.lineStart}, ${element.charPositionInLine}): $message\n${detailText(element)}"
private fun detailText(element: PsiElement) = try {
val context = context(element) ?: element
val result = StringBuilder()
val tokenizer = StringTokenizer(context.text, "\n", false)
val maxDigits = (log10(context.lineEnd.toDouble()) + 1).toInt()
for (line in context.lineStart..context.lineEnd) {
if (!tokenizer.hasMoreTokens()) break
result.append(("%0${maxDigits}d %s\n").format(line, tokenizer.nextToken()))
if (element.lineStart == element.lineEnd && element.lineStart == line) {
// If its an error on a single line highlight where on the line.
result.append(("%${maxDigits}s ").format(""))
if (element.charPositionInLine > 0) {
result.append(("%${element.charPositionInLine}s").format(""))
}
result.append(("%s\n").format("^".repeat(element.textLength)))
}
}
result.toString()
} catch (e: Exception) {
// If there is an exception while trying to print an error, just give back the unformatted error
// and print the stack trace for more debugging.
e.printStackTrace()
element.text
}
private val PsiElement.charPositionInLine: Int
get() {
val file = PsiDocumentManager.getInstance(project).getDocument(containingFile)!!
return textOffset - file.getLineStartOffset(file.getLineNumber(textOffset))
}
private val PsiElement.lineStart: Int
get() {
val file = PsiDocumentManager.getInstance(project).getDocument(containingFile)!!
return file.getLineNumber(textOffset) + 1
}
private val PsiElement.lineEnd: Int
get() {
val file = PsiDocumentManager.getInstance(project).getDocument(containingFile)!!
return file.getLineNumber(textOffset + textLength) + 1
}
private fun context(element: PsiElement?): PsiElement? =
when (element) {
null -> element
is SqlCreateTableStmt -> element
is SqlStmt -> element
is SqlDelightImportStmt -> element
else -> context(element.parent)
}
sealed class CompilationStatus {
class Success : CompilationStatus()
class Failure(val errors: List<String>) : CompilationStatus()
}
private inner class FileIndex : SqlDelightFileIndex {
override val contentRoot
get() = throw UnsupportedOperationException("Content root only usable from IDE")
override val packageName = properties.packageName
override val className = properties.className
override val dependencies = properties.dependencies
override val isConfigured = true
override val deriveSchemaFromMigrations = properties.deriveSchemaFromMigrations
override fun outputDirectory(file: SqlDelightFile) = outputDirectories()
override fun outputDirectories(): List<String> {
return listOf(compilationUnit.outputDirectoryFile.absolutePath)
}
private val virtualDirectoriesWithDependencies: List<VirtualFile> by lazy {
return@lazy (sourceFolders + dependencyFolders)
.map { localFileSystem.findFileByPath(it.absolutePath)!! }
}
private val directoriesWithDependencies: List<PsiDirectory> by lazy {
val psiManager = PsiManager.getInstance(projectEnvironment.project)
return@lazy virtualDirectoriesWithDependencies.map { psiManager.findDirectory(it)!! }
}
private val virtualDirectories: List<VirtualFile> by lazy {
return@lazy sourceFolders
.map { localFileSystem.findFileByPath(it.absolutePath)!! }
}
private val directories: List<PsiDirectory> by lazy {
val psiManager = PsiManager.getInstance(projectEnvironment.project)
return@lazy virtualDirectories.map { psiManager.findDirectory(it)!! }
}
override fun packageName(file: SqlDelightFile): String {
fun PsiFileSystemItem.relativePathUnder(ancestor: PsiDirectory): List<String>? {
if (this.virtualFile.path == ancestor.virtualFile.path) return emptyList()
parent?.let {
return it.relativePathUnder(ancestor)?.plus(name)
}
return null
}
for (sourceFolder in sourceFolders(file)) {
val path = file.parent!!.relativePathUnder(sourceFolder)
if (path != null) return path.joinToString(separator = ".") {
SqlDelightFileIndex.sanitizeDirectoryName(
it,
)
}
}
throw IllegalStateException(
"Tried to find package name of file ${file.virtualFile!!.path} when" +
" it is not under any of the source folders $sourceFolders",
)
}
override fun sourceFolders(file: VirtualFile, includeDependencies: Boolean) =
if (includeDependencies) virtualDirectoriesWithDependencies else virtualDirectories
override fun sourceFolders(file: SqlDelightFile, includeDependencies: Boolean) =
if (includeDependencies) directoriesWithDependencies else directories
}
}