All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sxtanna.db.struct.Table.kt Maven / Gradle / Ivy

There is a newer version: 1.6
Show newest version
package com.sxtanna.db.struct

import com.sxtanna.db.ext.PrimaryKey
import com.sxtanna.db.type.Named
import kotlin.reflect.KClass
import kotlin.reflect.KProperty1
import kotlin.reflect.full.findAnnotation
import kotlin.reflect.jvm.jvmName
import kotlin.reflect.jvm.kotlinProperty

/**
 * Describes an SQL Table, based on a JVM Object [T]
 */
class Table @PublishedApi internal constructor(val clazz : KClass) : Named {

    override val name = clazz.simpleName ?: clazz.jvmName

    internal val fields by lazy {
        clazz.java.declaredFields
              .filter { it.getAnnotation(Transient::class.java) == null }
              .mapNotNull { it.kotlinProperty as? KProperty1 }
    }

    internal val columns = mutableMapOf()


    init {
        fields.forEach {
            columns[it.name] = Resolver.SqlO[it]
        }
    }


    /**
     * Retrieve the Primary Key of this table, or null if none
     */
    fun getPrimaryKey() = fields.find { it.findAnnotation() != null }

    /**
     * Get the rows of this table represents as properties
     */
    fun getAllRows() = fields

    /**
     * Get the names of the rows of this table
     */
    fun getAllRowNames() = columns.keys.toList()


    override fun equals(other : Any?) : Boolean {
        if (this === other) return true
        if (other !is Table<*>) return false

        if (clazz != other.clazz) return false
        if (columns != other.columns) return false

        return true
    }

    override fun hashCode() : Int {
        var result = clazz.hashCode()
        result = 31 * result + columns.hashCode()
        return result
    }


    companion object {

        /**
         * Create a table from a field
         */
        inline fun  of() = Table(T::class)

    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy