Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement SuperTableClass annotation #562

Open
wants to merge 7 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package org.ktorm.ksp.annotation

import org.ktorm.schema.BaseTable
import kotlin.reflect.KClass

/**
* Be used on Entity interface, to specify the super table class for the table class generated.
* @property value the super table class.
* if not specified, the super table class will be determined by the kind of the entity class.
* `org.ktorm.schema.Table` for interface, `org.ktorm.schema.BaseTable` for class.
*
* if there are multiple `SuperTableClass` on the inheritance hierarchy of entity,
* and they have an inheritance relationship, the super table class will be the last one of them.
* and they don't have an inheritance relationship, an error will be reported.
*/
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.SOURCE)
public annotation class SuperTableClass(
public val value: KClass<out BaseTable<out Any>>
)
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,7 @@ internal object TableClassGenerator {
}

private fun TypeSpec.Builder.configureSuperClass(table: TableMetadata): TypeSpec.Builder {
qumn marked this conversation as resolved.
Show resolved Hide resolved
if (table.entityClass.classKind == ClassKind.INTERFACE) {
superclass(Table::class.asClassName().parameterizedBy(table.entityClass.toClassName()))
} else {
superclass(BaseTable::class.asClassName().parameterizedBy(table.entityClass.toClassName()))
}
superclass(table.superClass.parameterizedBy(table.entityClass.toClassName()))

addSuperclassConstructorParameter("%S", table.name)
addSuperclassConstructorParameter("alias")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ import org.ktorm.ksp.spi.ColumnMetadata
import org.ktorm.ksp.spi.DatabaseNamingStrategy
import org.ktorm.ksp.spi.TableMetadata
import org.ktorm.schema.TypeReference
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.asClassName
import com.squareup.kotlinpoet.ksp.KotlinPoetKspPreview
import com.squareup.kotlinpoet.ksp.toClassName
import java.lang.reflect.InvocationTargetException
import java.util.*
import kotlin.reflect.jvm.jvmName
Expand Down Expand Up @@ -93,6 +97,9 @@ internal class MetadataParser(resolver: Resolver, environment: SymbolProcessorEn

_logger.info("[ktorm-ksp-compiler] parse table metadata from entity: $className")
val table = cls.getAnnotationsByType(Table::class).first()
val (superClass, superTableClasses) = parseSuperTableClass(cls)
val allPropertyNamesOfSuperTables = superTableClasses.flatMap { it.getProperties(emptySet()) }.map { it.simpleName.asString() }

val tableMetadata = TableMetadata(
entityClass = cls,
name = table.name.ifEmpty { _databaseNamingStrategy.getTableName(cls) },
Expand All @@ -101,8 +108,9 @@ internal class MetadataParser(resolver: Resolver, environment: SymbolProcessorEn
schema = table.schema.ifEmpty { _options["ktorm.schema"] }?.takeIf { it.isNotEmpty() },
tableClassName = table.className.ifEmpty { _codingNamingStrategy.getTableClassName(cls) },
entitySequenceName = table.entitySequenceName.ifEmpty { _codingNamingStrategy.getEntitySequenceName(cls) },
ignoreProperties = table.ignoreProperties.toSet(),
columns = ArrayList()
ignoreProperties = table.ignoreProperties.toSet() + allPropertyNamesOfSuperTables, // ignore properties of super tables
columns = ArrayList(),
superClass = superClass
)

val columns = tableMetadata.columns as MutableList
Expand Down Expand Up @@ -274,6 +282,51 @@ internal class MetadataParser(resolver: Resolver, environment: SymbolProcessorEn
)
}

/**
* @return the super table class and all class be annotated with [SuperTableClass] in the inheritance hierarchy.
*/
@OptIn(KotlinPoetKspPreview::class)
private fun parseSuperTableClass(cls: KSClassDeclaration): Pair<ClassName, Set<KSClassDeclaration>> {
val superTableClassAnnPair = cls.findAllAnnotationsInInheritanceHierarchy(SuperTableClass::class.qualifiedName!!)

// if there is no SuperTableClass annotation, return the default super table class based on the class kind.
if (superTableClassAnnPair.isEmpty()) {
return if (cls.classKind == INTERFACE) {
org.ktorm.schema.Table::class.asClassName() to emptySet()
} else {
org.ktorm.schema.BaseTable::class.asClassName() to emptySet()
}
}

// SuperTableClass annotation can only be used on interface
if (superTableClassAnnPair.map { it.first }.any { it.classKind != INTERFACE }) {
val msg = "SuperTableClass annotation can only be used on interface."
throw IllegalArgumentException(msg)
}

// find the last annotation in the inheritance hierarchy
val superTableClasses = superTableClassAnnPair
.map { it.second }
.map { it.arguments.single { it.name?.asString() == SuperTableClass::value.name } }
.map { it.value as KSType }
.map { it.declaration as KSClassDeclaration }

var lowestSubClass = superTableClasses.first()
for (i in 1 until superTableClasses.size) {
val cur = superTableClasses[i]
if (cur.isSubclassOf(lowestSubClass)) {
lowestSubClass = cur
} else if (!lowestSubClass.isSubclassOf(cur)) {
val msg =
"There are multiple SuperTableClass annotations in the inheritance hierarchy of class ${cls.qualifiedName?.asString()}," +
"but the values of annotation are not in the same inheritance hierarchy."
throw IllegalArgumentException(msg)
}
}
//TODO: to check All constructor parameters owned by `BaseTable` should also be owned by lowestSubClass.
return lowestSubClass.toClassName() to superTableClasses.toSet()
}

private fun TableMetadata.checkCircularRef(ref: KSClassDeclaration, stack: LinkedList<String> = LinkedList()) {
val className = this.entityClass.qualifiedName?.asString()
val refClassName = ref.qualifiedName?.asString()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,13 @@ internal inline fun <reified T : Any> KSClassDeclaration.isSubclassOf(): Boolean
return findSuperTypeReference(T::class.qualifiedName!!) != null
}

/**
* Check if this class is a subclass of declaration.
*/
internal fun KSClassDeclaration.isSubclassOf(declaration: KSClassDeclaration): Boolean {
return findSuperTypeReference(declaration.qualifiedName!!.asString()) != null
}

/**
* Find the specific super type reference for this class.
*/
Expand All @@ -76,6 +83,24 @@ internal fun KSClassDeclaration.findSuperTypeReference(name: String): KSTypeRefe
return null
}

/**
* Find all annotations with the given name in the inheritance hierarchy of this class.
*
* @param name the qualified name of the annotation.
*/
internal fun KSClassDeclaration.findAllAnnotationsInInheritanceHierarchy(name: String): List<Pair<KSClassDeclaration, KSAnnotation>> {
val rst = mutableListOf<Pair<KSClassDeclaration, KSAnnotation>>()

fun KSClassDeclaration.collectAnnotations() {
rst += annotations.filter { it.annotationType.resolve().declaration.qualifiedName?.asString() == name }.map { this to it }
superTypes.forEach { (it.resolve().declaration as KSClassDeclaration).collectAnnotations() }
}

collectAnnotations()
return rst
}


/**
* Check if the given symbol is valid.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ abstract class BaseKspTest {

private fun compile(@Language("kotlin") code: String, options: Map<String, String>): KotlinCompilation.Result {
@Language("kotlin")
val header = """
val source = """
import java.math.*
import java.sql.*
import java.time.*
Expand All @@ -73,12 +73,13 @@ abstract class BaseKspTest {
import org.ktorm.entity.*
import org.ktorm.ksp.annotation.*

$code

lateinit var database: Database


""".trimIndent()

val source = header + code
printFile(source, "Source.kt")

val compilation = createCompilation(SourceFile.kotlin("Source.kt", source), options)
Expand Down
Loading