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

com.dbobjekts.metadata.Catalog.kt Maven / Gradle / Ivy

There is a newer version: 0.6.0-RC2
Show newest version
package com.dbobjekts.metadata

import com.dbobjekts.api.AnyTable
import com.dbobjekts.api.exception.DBObjektsException
import com.dbobjekts.vendors.Vendor

/**
 * Represents a single database, consisting of collection of [Schema] object and generated by the [com.dbobjekts.codegen.CodeGenerator]
 *
 * You must provide an appropriate [Catalog] implementation when setting up the [com.dbobjekts.api.TransactionManager]. Example:
 * ```kotlin
 *  TransactionManager.builder()
 *      .withDataSource(dataSource)
 *      .withCatalog(AcmeCatalog)
 *      .build()
 * ```
 */
open class Catalog(
    val version: Int,
    val vendor: String,
    val schemas: List = listOf()
) {

    constructor(vendor: Vendor, schemas: List = listOf()) : this(0, vendor.name, schemas)

    internal val tables: List
    private val aliases: TableAliases

    init {
        schemas.forEach { it.withCatalog(this) }
        val builder = TableAliasesBuilder()
        schemas.forEach { builder.addSchema(it) }
        aliases = builder.build()
        tables = schemas.flatMap { it.tables }
    }

    internal fun assertContainsTable(table: AnyTable): AnyTable {
        table.ensureSchema()
        if (tables.none { it.schemaAndName() == table.schemaAndName() }) {
            throw DBObjektsException("Table ${table.schemaAndName()} does not belong to the Catalog associated with the current TransactionManager")
        }
        return table
    }

    internal fun schemaByName(name: String): Schema? = schemas.find { it.schemaName.value.contentEquals(name, true) }

    internal fun aliasForTable(table: AnyTable): String = aliases.aliasForSchemaAndTable(table.schemaName(), table.tableName)

    override fun toString(): String = this::class.java.canonicalName

    internal fun serialize(): String = "$vendor " + tables.map { it.serialize() }.joinToString(",")

}

internal object DefaultNoVendorCatalog : Catalog(0, "")




© 2015 - 2024 Weber Informatics LLC | Privacy Policy