Created
April 11, 2018 04:45
-
-
Save markchristopherng/f7730153b75b2d99920dd4e851eae850 to your computer and use it in GitHub Desktop.
AuspostDatabaseProvider
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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