Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afaucogney/1d08309196aa31a00ca6b6fa3e3f5993 to your computer and use it in GitHub Desktop.
Save afaucogney/1d08309196aa31a00ca6b6fa3e3f5993 to your computer and use it in GitHub Desktop.
AuspostDatabaseProvider
package au.com.auspost.android
import android.arch.persistence.db.SupportSQLiteDatabase
import android.arch.persistence.room.Room
import android.arch.persistence.room.migration.Migration
import android.content.Context
import android.support.annotation.VisibleForTesting
import io.reactivex.Observable
import timber.log.Timber
import toothpick.ProvidesSingletonInScope
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
@Singleton
@ProvidesSingletonInScope
class AuspostDatabaseProvider : Provider<AuspostDatabase> {
@Inject
lateinit var context: Context
companion object {
@VisibleForTesting
val MIGRATION_1_2 : Migration = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
Timber.d("Start Migration 1 - 2")
//Create temporary branch location table
database.execSQL(""" CREATE TABLE branch_location_copy(
id INTEGER PRIMARY KEY NOT NULL,
postcode TEXT,
locality TEXT,
state TEXT,
delivery TEXT,
category TEXT) """.trimIndent())
//Copy data into temporary branch_location table and rename table
database.execSQL(""" INSERT INTO branch_location_copy(id,
postcode,
locality,
state,
delivery,
category)
SELECT id,
postcode,
locality,
state,
delivery,
category
FROM branch_location """.trimIndent())
Observable.fromIterable("""
DROP TABLE branch_location;
ALTER TABLE branch_location_copy RENAME TO branch_location;
""".trimIndent().split(";"))
.subscribe({ database.execSQL(it)})
Timber.d("migrated branch_location")
Timber.d("End Migration 1 - 2")
}
}
}
override fun get(): AuspostDatabase {
return Room.databaseBuilder(context.applicationContext,
AuspostDatabase::class.java, AuspostDatabase.DB_NAME)
.addMigrations(MIGRATION_1_2)
.fallbackToDestructiveMigration()
.build()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment