kotlinktorkotlin-exposed

Ktor-Exposed database migration


Question:

How to maintain database migration history using Exposed framework's SchemaUtils?

Background:

Recently, we have started evaluating API development using Ktor with Exposed. and noticed that exposed offers database migration feature built-in using SchemaUtils.

transaction(database) {
            SchemaUtils.create(Articles)
        }

I was able to find out the basic documentation from here but I could not find how answers to following?

The only thing, I could confirm are the console logs by expose indicating which tables are created.

Additional Details:

Any guidance is much appreciated.


Solution

  • Kotlin exposed give you a function that can migrate youre database for you on start-up.

    the function SchemaUtils.createMissingTablesAndColumns can receive multiple tables as parameter to actualize multiple at once

    Example:

    object ClientTable : LongIdTable() {
        val clientId: Column<String> = varchar("clientId", 255)
        val clientName: Column<String> = varchar("clientName", 255)
    }
    
    transaction(database) {
        SchemaUtils.createMissingTablesAndColumns(ClientTable)
    }
    

    Everytime this code runs it will check the database and alters if possible. If its not possible it will spit out the sql statement neccary for the migration in the console.