Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

  • How to execute migration for altering table structure?
  • How to manage migration history similar to other what RoR or liquibase does?
    • RoR manages migration history in database table for maintenance purpose
    • liquibase provides a similar feature

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

Additional Details:

  • Ktor version : 2.3.7
  • Kotlin version : 2.3.7
  • Exposed version : 0.45.0

Any guidance is much appreciated.

like image 524
JustAProgrammer Avatar asked Apr 15 '26 21:04

JustAProgrammer


1 Answers

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.

like image 160
Mike Dirven Avatar answered Apr 19 '26 12:04

Mike Dirven