https://kotlinlang.org logo
#komapper
Title
# komapper
d

dave08

10/10/2023, 6:40 AM
@Toshihiro Nakamura Wondering how hard it would be to add a gradle task or some kind of utility to check Entity definitions against a real db...? I don't want to generate them from the db since there's a lot of fields I don't need, but validation would avoid having to manually check if something changed in the db structure maybe as part of integration tests or a CI pipeline... it would be very useful!
Field/table names, types, primary keys, maybe even relations...
t

Toshihiro Nakamura

10/10/2023, 10:03 AM
For validation, the
java.sql.DatabaseMetaData
class may be useful. For example, you can validate the primary key using the following method: https://docs.oracle.com/en/java/javase/17/docs/api//java.sql/java/sql/DatabaseMetaData.html#getPrimaryKeys(java.lang.S[…]ng.String,java.lang.String)
d

dave08

10/10/2023, 10:21 AM
You always use generation from the db? Maybe this kind of feature would be useful in Komapper itself, since it would be non-trivial to manage a separate library to go through all those annotations w/o breaking on newer Komapper releases... or maybe you find this to not be too useful in your situation? I just came across a typo in my entities, and my unit tests use h2 and QueryDSL.createSchema... which won't show such problems... I could always try to find a way to put up a real db with testcontainers, but I'd rather keep my tests fast, and I don't need the extra fields in the real db (which could be a solution to my problem in my next comment...)
t

Toshihiro Nakamura

10/13/2023, 11:47 PM
You always use generation from the db?
No. I meant to say that it is easy for users to perform arbitrary validations. Here is the test code to validate primary keys:
Copy code
val db = JdbcDatabase("jdbc:h2:mem:example;DB_CLOSE_DELAY=-1")

@Test
fun test() {
    for (m in Meta.all()) {
        validateMetamodel(m)
    }
}

private fun validateMetamodel(m: EntityMetamodel<*, *, *>) {
    db.config.session.useConnection { connection ->
        val metaData = connection.metaData
        val columns = metaData.getPrimaryKeys(m.catalogName(), m.schemaName(), m.tableName()).use { rs ->
            buildList {
                while (rs.next()) {
                    add(rs.getString("COLUMN_NAME"))
                }
            }
        }
        assertEquals(m.idProperties().map { it.columnName }, columns)
    }
}
9 Views