-
Notifications
You must be signed in to change notification settings - Fork 496
/
ColumnTypeMixin.kt
250 lines (231 loc) · 9.24 KB
/
ColumnTypeMixin.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
/*
* 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.lang.psi
import app.cash.sqldelight.core.compiler.SqlDelightCompiler.allocateName
import app.cash.sqldelight.core.lang.types.typeResolver
import app.cash.sqldelight.core.lang.util.parentOfType
import app.cash.sqldelight.core.lang.util.sqFile
import app.cash.sqldelight.core.psi.SqlDelightAnnotation
import app.cash.sqldelight.core.psi.SqlDelightAnnotationValue
import app.cash.sqldelight.core.psi.SqlDelightColumnType
import app.cash.sqldelight.core.psi.SqlDelightJavaType
import app.cash.sqldelight.core.psi.SqlDelightJavaTypeName
import app.cash.sqldelight.core.psi.SqlDelightParameterizedJavaType
import app.cash.sqldelight.core.psi.SqlDelightStmtList
import app.cash.sqldelight.dialect.api.DialectType
import app.cash.sqldelight.dialect.api.IntermediateType
import com.alecstrong.sql.psi.core.SqlAnnotationHolder
import com.alecstrong.sql.psi.core.psi.Queryable
import com.alecstrong.sql.psi.core.psi.SqlColumnDef
import com.alecstrong.sql.psi.core.psi.SqlColumnName
import com.alecstrong.sql.psi.core.psi.SqlIdentifier
import com.alecstrong.sql.psi.core.psi.SqlTypeName
import com.alecstrong.sql.psi.core.psi.SqlTypes
import com.alecstrong.sql.psi.core.psi.impl.SqlColumnTypeImpl
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.tree.TokenSet
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.castSafelyTo
import com.squareup.kotlinpoet.AnnotationSpec
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.joinToCode
import com.squareup.kotlinpoet.jvm.jvmInline
internal abstract class ColumnTypeMixin(
node: ASTNode
) : SqlColumnTypeImpl(node),
TypedColumn,
SqlDelightColumnType {
override fun type(): IntermediateType {
val columnName = (parent as SqlColumnDef).columnName
val columnConstraintList = (parent as SqlColumnDef).columnConstraintList
var type = typeResolver.definitionType(typeName).copy(column = (parent as SqlColumnDef), name = allocateName(columnName))
javaTypeName?.type()?.let { type = type.copy(javaType = it) }
// Ensure we use the same value type for a foreign key.
columnConstraintList.mapNotNull { it.foreignKeyClause }.singleOrNull() // Foreign Key
?.columnNameList?.singleOrNull() // Foreign Column
?.reference?.resolve()?.let { resolvedKey -> // Resolved Column
val dialectType = resolvedKey.castSafelyTo<SqlColumnName>() // Column Name
?.parent?.castSafelyTo<SqlColumnDef>() // Column Definition
?.columnType?.castSafelyTo<ColumnTypeMixin>() // Column type
?.type()?.dialectType?.castSafelyTo<ValueTypeDialectType>() ?: return@let // SqlDelight type
type = type.copy(
dialectType = dialectType,
javaType = dialectType.javaType
)
}
valueClass()?.let { valueType ->
val newDialectType = ValueTypeDialectType(valueType.name!!, type.dialectType)
type = type.copy(
dialectType = newDialectType,
javaType = newDialectType.javaType
)
}
if (columnConstraintList.none {
(it.node.findChildByType(SqlTypes.NOT) != null && it.node.findChildByType(SqlTypes.NULL) != null) ||
it.node.findChildByType(SqlTypes.PRIMARY) != null
}
) {
type = type.asNullable()
}
if (annotationList.isNotEmpty()) {
type = type.copy(
javaType = type.javaType
.copy(annotations = type.javaType.annotations + annotationList.map { it.spec() })
)
}
return typeResolver.simplifyType(type)
}
override fun adapter(): PropertySpec? {
if (type().simplified) return null
val columnName = (parent as SqlColumnDef).columnName
javaTypeName?.let {
val customType = try {
it.parameterizedJavaType.type()
} catch (e: IllegalArgumentException) {
// Found an invalid type.
return null
}
return PropertySpec
.builder(
name = "${allocateName(columnName)}Adapter",
type = columnAdapterType.parameterizedBy(customType, typeResolver.definitionType(typeName).dialectType.javaType)
)
.build()
}
return null
}
internal fun valueClass(): TypeSpec? {
if (node.getChildren(null).all { it.text != "VALUE" && it.text != "LOCK" }) return null
val columnName = (parent as SqlColumnDef).columnName.name
val type = typeResolver.definitionType(typeName).javaType
return TypeSpec.classBuilder(columnName.capitalize())
.primaryConstructor(
FunSpec.constructorBuilder()
.addParameter(columnName, type)
.build()
)
.addProperty(
PropertySpec.builder(columnName, type)
.initializer(columnName)
.build()
)
.addModifiers(KModifier.VALUE)
.jvmInline()
.build()
}
private fun SqlDelightJavaTypeName.type(): TypeName? {
return try {
parameterizedJavaType.type()
} catch (e: IllegalArgumentException) {
// Found an invalid type.
null
}
}
private fun SqlDelightJavaType.type(): ClassName {
parentOfType<SqlDelightStmtList>().importStmtList.importStmtList.forEach { import ->
val typePrefix = text.substringBefore('.')
if (import.javaType.text.endsWith(".$typePrefix")) {
return text.split(".").drop(1).fold(import.javaType.type()) { current, nested ->
current.nestedClass(nested)
}
}
}
return ClassName.bestGuess(text)
}
private fun SqlDelightParameterizedJavaType.type(): TypeName {
if (javaTypeNameList.isNotEmpty() || javaTypeName2List.isNotEmpty()) {
var parameters = javaTypeNameList.mapNotNull { it.type() }.toTypedArray()
if (javaTypeList.size == 2) {
// Hack to get around '>>' character.
parameters += javaTypeList[1].type()
.parameterizedBy(*javaTypeName2List.map { it.javaType.type() }.toTypedArray())
}
return javaTypeList[0].type().parameterizedBy(*parameters)
}
return javaTypeList[0].type()
}
private fun SqlDelightAnnotation.spec(): AnnotationSpec {
val annotation = AnnotationSpec.builder(javaType.type())
val identifiers = children.filterIsInstance<SqlIdentifier>()
if (identifiers.isEmpty() && annotationValueList.isNotEmpty()) {
annotation.addMember(annotationValueList[0].value())
}
annotationValueList.zip(
identifiers,
{ annotation_value, identifier ->
annotation.addMember(
CodeBlock.builder()
.add("${identifier.text} = ")
.add(annotation_value.value())
.build()
)
}
)
return annotation.build()
}
private fun SqlDelightAnnotationValue.value(): CodeBlock {
javaTypeName?.let {
return CodeBlock.of("%T::class", it.type())
}
annotation?.let {
return CodeBlock.of("%L", it.spec())
}
if (annotationValueList.isNotEmpty()) {
return annotationValueList.map { it.value() }.joinToCode(",", "[", "]")
}
return CodeBlock.of(text)
}
override fun annotate(annotationHolder: SqlAnnotationHolder) {
javaTypeName?.let { javaType ->
if (javaType.type() == null) {
annotationHolder.createErrorAnnotation(javaType, "Unknown type ${javaType.text}")
}
}
val children = node.getChildren(TokenSet.create(SqlTypes.ID))
children.filter { (it.text == "as" || it.text == "As") && it.prevVisibleSibling?.psi is SqlTypeName }
.forEach {
annotationHolder.createErrorAnnotation(it.psi, "Expected 'AS', got '${it.text}'")
}
}
internal inner class ValueTypeDialectType(
name: String,
val wrappedType: DialectType
) : DialectType by wrappedType {
override val javaType: TypeName by lazy {
val tableName = PsiTreeUtil.getParentOfType(this@ColumnTypeMixin, Queryable::class.java)!!.tableExposed().tableName
ClassName(tableName.sqFile().packageName!!, allocateName(tableName).capitalize(), name)
}
override fun encode(value: CodeBlock): CodeBlock {
val columnName = (parent as SqlColumnDef).columnName
return wrappedType.encode(CodeBlock.of("%L.${columnName.text}", value))
}
override fun decode(value: CodeBlock) = CodeBlock.of("%T(%L)", javaType, wrappedType.decode(value))
}
private val ASTNode.prevVisibleSibling: ASTNode?
get() = generateSequence(treePrev) { it.treePrev }
.firstOrNull { it.psi !is PsiWhiteSpace }
companion object {
private val columnAdapterType = ClassName("app.cash.sqldelight", "ColumnAdapter")
}
}