https://kotlinlang.org logo
#exposed
Title
# exposed
a

Andreas Scheja

01/24/2022, 6:27 PM
Hi, I stumbled upon a rather strange error the other day (see discussion for example code). In retrospect I should have taken a better look at what the IDE imported, but still the effect was very confusing...
Copy code
import TableA.nullable
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.Table
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.transactions.transaction

object TableA : Table("a") {
    val id = integer("id")
}

object TableB : Table("b") {
    val id = integer("id")
    val columnInB = varchar("only_in_table_b", 20)
}

private val db = Database.connect("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1")

object RepositoryA {
    fun findEntries(): List<Int> {
        return transaction(db) {
            TableA.selectAll().map { row -> row[TableA.id] }
        }
    }
}

object RepositoryB {
    fun findEntries(): List<Pair<Int, String>> {
        return transaction(db) {
            TableB.selectAll().map { row ->
                val nullableColumnInB = TableB.columnInB.nullable() // what is the proper way to do this?
                Pair(row[TableB.id], row[nullableColumnInB] ?: "")
            }
        }
    }
}

fun main() {
    transaction(db) {
        exec("CREATE TABLE a(id INT NOT NULL)")
        exec("CREATE TABLE b(id INT NOT NULL, only_in_table_b VARCHAR(20) NULL)")
        exec("INSERT INTO b VALUES (1, 'foo'), (2, NULL)")
    }
    println(RepositoryA.findEntries())
    println(RepositoryB.findEntries())
    println(RepositoryA.findEntries())
}
It all started with me adding a
nullable()
to a column on use site (the table in the actual project was part of a library, wanted to do a quick-fix just in one project)
The tricky part is that when executing the code above the
only_in_table_b
column is somehow added to the columnset of
TableA
, effectively crashing on the second invocation of
RepositoryA.findEntries()
with a "no such column" error
only by grepping through my projects I found the completely unrelated
import TableA.nullable
statement.
Although I see it is entirely my error, isn't there something that can be improved in exposed, i.e. fail when calling
nullable()
on a table that doesn't contain the non-nullable column