Search code examples
androidandroid-room

How can you get the version number of your Room Database?


I have some code that I would only like to run when I know for certain that the Room migrations I have have completed. Is there a way to find out which version number my Room instance is on? I have the latest code:

@Database(entities = [AnalyticsEvent::class, ListenItem::class, LastPositionHeard::class, 
DownloadItem::class], version = 3) //I would like to retrieve this information
@TypeConverters(RoomTypeConverters::class)
abstract class MyRoomDatabase : RoomDatabase() {

  abstract fun analyticsEventsDao(): AnalyticsEventsDao

  abstract fun listeningStatsDao(): ListeningStatsDao

  abstract fun lastPositionHeardDao(): LastPositionHeardDao

  abstract fun downloadsDao(): DownloadsDao

  companion object {
    // Singleton prevents multiple instances of database opening at the
    // same time.
    @Volatile
    private var INSTANCE: MyRoomDatabase? = null

    val MIGRATION_1_TO_2 = Migration1To2()
    val MIGRATION_2_TO_3 = Migration2To3()
    const val LUMINARY_DATABASE_NAME = "room_database"

    fun getDatabase(context: Context): MyRoomDatabase {
      val tempInstance = INSTANCE
      if (tempInstance != null) {
        return tempInstance
      }
      synchronized(this) {
        val instance = Room.databaseBuilder(
          context.applicationContext,
          LuminaryRoomDatabase::class.java,
          LUMINARY_DATABASE_NAME
        ).addMigrations(MIGRATION_1_TO_2, MIGRATION_2_TO_3)
        .build()
    INSTANCE = instance
    return instance
   }
  }
 }
}

But what I would like to do is something like this:

val instanceVersionNumber = MyRoomDatabase.getDatabase().versionNumber

Is it possible?


Solution

  • Here's an extension function in Kotlin to grab the version number. The key is to call openHelper from your Room database which returns a SupportSQLiteOpenHelper object where you can then get to the actual DB attributes.

    fun Context.getDBVersion() = RoomDatabase.getDatabase(this)?.openHelper?.readableDatabase?.version.toString()