Search code examples
kotlinormkotlin-exposed

Change the name of the ID in Exposed ORM


i have defined a table and a row in Kotlin:

    object Countries : UUIDTable("country") {
        val uuid: Column<UUID> = uuid("uuid").autoGenerate()
        val name: Column<String> = varchar("name", 255)
        val code: Column<String> = varchar("code", 2)
        override val primaryKey = PrimaryKey(uuid, name = "country_pk")
    }

    class Country(uuid: EntityID<UUID>) : UUIDEntity(uuid) {
        companion object : UUIDEntityClass<Country>(Countries)
        var uuid by Countries.uuid
        var name by Countries.name
        var code by Countries.code
    }

As you can see i use a UUID with the column name "uuid" as my primary key.

When i do a select:

var country = Country.find { Countries.code eq "GB" }.first()

the query fails with the following error:

org.jetbrains.exposed.exceptions.ExposedSQLException: org.postgresql.util.PSQLException: ERROR: column country.id does not exist

The reason is simple. The generated SQL query looks like:

SELECT country.id, country.uuid, country."name", country.code FROM country WHERE country.code = ?

So my question now is: Where is the ID Column coming from?

Thanks.


Solution

  • id column is declared in UUIDTable class :

    open class UUIDTable(name: String = "", columnName: String = "id") : IdTable<UUID>(name) {
        override val id: Column<EntityID<UUID>> = uuid(columnName)
                .autoGenerate()
                .entityId()
        override val primaryKey by lazy { super.primaryKey ?: PrimaryKey(id) }
    }
    

    If you use uuid column as a primary key then you could just remove it from declaration and provide uuid as a name for an id column like:

    object Countries : UUIDTable("country", "uuid") {
        val name: Column<String> = varchar("name", 255)
        val code: Column<String> = varchar("code", 2)
    }