Maryam Mirzaie
Maryam Mirzaie

Reputation: 596

Move tables to a new database migration Room Android

I'm using Room in Android for my databases. Recently I had to create an alternate for my main database so now I have 2 databases.

abstract class FirstDatabase : RoomDatabase() 
abstract class ScondDatabase : RoomDatabase() 

I have a table in the FirstDataBase that I want to copy to the SecondDataBase. I know I should write migration but I don't know how I should do that. This is my current migration with dagger for room:

fun provideDatabaseMigration56(): Migration {
        return object : Migration(DATABASE_VERSION_5, DATABASE_VERSION_6) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("DROP TABLE IF EXISTS `pins`")
                
            }
        }
    }

    fun provideDatabaseMigration45(): Migration {
        return object : Migration(DATABASE_VERSION_4, DATABASE_VERSION_5) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("CREATE TABLE IF NOT EXISTS `pins` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `slug` TEXT NOT NULL)")
            }
        }
    }

Upvotes: 0

Views: 274

Answers (1)

Henry Twist
Henry Twist

Reputation: 5990

What you're looking for is the SQLite ATTACH DATABASE statement. This allows you to attach an additional database to the current connection and then run queries referencing tables within both. There is some detailed documentation here which shows the syntax:

ATTACH DATABASE file_name AS database_name;

You can then run queries referencing tables from both databases, but make sure that when referencing a table from the attached database that you refer to it as

database_name.table_name

as opposed to just table_name.

Upvotes: 1

Related Questions