com.dailystudio.devbricksx.ksp.utils.RoomCompanionUtils.kt Maven / Gradle / Ivy
package com.dailystudio.devbricksx.ksp.utils
import com.dailystudio.devbricksx.annotations.data.RoomCompanion
import com.dailystudio.devbricksx.ksp.helper.underlineCaseName
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.google.devtools.ksp.symbol.KSType
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.ksp.toTypeName
object RoomCompanionUtils {
fun findPrimaryKeyNames(symbol: KSClassDeclaration): Set {
return findPrimaryKeys(symbol).keys
}
fun findPrimaryKeys(symbol: KSClassDeclaration): Map {
val allPropertiesInSymbol = symbol.getAllProperties()
val roomCompanion = symbol.getAnnotation(RoomCompanion::class)
?: return emptyMap()
val namesOfPrimaryKeys = mutableListOf().apply {
roomCompanion.primaryKeys.forEach {
add(it)
}
}
if (namesOfPrimaryKeys.isEmpty()) {
val nameOfAllProps = allPropertiesInSymbol.map {
it.simpleName.getShortName()
}
val nameOfPropsInConstructor = mutableListOf()
symbol.primaryConstructor?.parameters?.forEach { param ->
val nameOfParam = param.name?.getShortName() ?: return@forEach
nameOfPropsInConstructor.add(nameOfParam)
}
val defaultPrimaryKey = if (nameOfPropsInConstructor.isNotEmpty()) {
nameOfPropsInConstructor.first()
} else {
nameOfAllProps.first()
}
namesOfPrimaryKeys.add(defaultPrimaryKey)
}
val mapOfPrimaryKeys = mutableMapOf()
allPropertiesInSymbol.forEach {
val nameOfProp = it.simpleName.getShortName()
if (namesOfPrimaryKeys.contains(nameOfProp)) {
mapOfPrimaryKeys[nameOfProp] = it.type.resolve()
}
}
return mapOfPrimaryKeys
}
fun attachPrimaryKeysToMethodParameters(methodBuilder: FunSpec.Builder,
primaryKeys: Map) {
primaryKeys.forEach {
methodBuilder.addParameter(it.key, it.value.toTypeName())
}
}
fun primaryKeysToSQLiteWhereClause(primaryKeys: Map): String {
return primaryKeyNamesToSQLiteWhereClause(primaryKeys.keys)
}
fun primaryKeyNamesToSQLiteWhereClause(namesOfPrimaryKeys: Set): String {
return buildString {
append("where ")
for ((i, nameOfPrimaryKey) in namesOfPrimaryKeys.withIndex()) {
append(nameOfPrimaryKey.underlineCaseName())
append(" = :")
append(nameOfPrimaryKey)
if (i < namesOfPrimaryKeys.size - 1) {
append(" and ")
}
}
}
}
fun primaryKeysToFuncCallParameters(primaryKeys: Map): String {
return primaryKeyNamesToFuncCallParameters(primaryKeys.keys)
}
fun primaryKeyNamesToFuncCallParameters(namesOfPrimaryKeys: Set): String {
return namesOfPrimaryKeys.joinToString(separator = ", ")
}
}