6

When working with Room for sqlite libraries on Android, I notices that while the tables for the first version of the DB are created automatically, I saw only tutorials on how to migrate to a newer version by manually writing the sql-commands for the Migration-classes.

This seems really odd as it is possible to auto-generate these migrations (e.g. like django) and it's suprising that the create-commands for V1 are autogenerated, but if I add a table later, I have to manually type the commands.

So did I just miss it or do I really have to write the migrations?

FooTheBar
  • 818
  • 1
  • 9
  • 20
  • 1
    [This](https://stackoverflow.com/questions/48399852/room-database-migration-if-only-new-table-is-added/54045368#54045368) might help – musooff Aug 12 '19 at 02:57

5 Answers5

6

It is supported now from room 2.4.0.

For now beta version only available 2.4.0-beta01. I have tested in my project its working fine.

// Database class before the version update.
@Database(
  version = 1,
  entities = {User.class}
)
public abstract class AppDatabase extends RoomDatabase {
  ...
}

// Database class after the version update.
@Database(
  version = 2,
  entities = {User.class},
  autoMigrations = {
    @AutoMigration (from = 1, to = 2)
  }
)
public abstract class AppDatabase extends RoomDatabase {
  ...
}

See doc

Kamal
  • 335
  • 3
  • 10
2

In my experience, you have to manually create the migrations for Google Room. Maybe one of the reasons why you are going to migrate is to preserve/handle the data saved safely on your SQLite database.

For instance that you do destructive migration:

Room.databaseBuilder(context.getApplicationContext(),
                    UsersDatabase.class, "Sample.db")
            .fallbackToDestructiveMigration()
            .build();

This will try to delete your database, will recreate your schema and also your data will be gone.

So for migration, like

Room.databaseBuilder(context.getApplicationContext(),
    UsersDatabase.class, "Sample.db")
    .addMigrations(MIGRATION_1_2)
    .build();

You are manually managing your database migration and you'll be responsible for all the data. For example, you added a new property/column to User table, you'll have to create a migration for that saying alter the user table and add the new property with a default value of blah blah blah...

I also give some advise, if you'll do migrations, do it carefully, or else it will give you a headache, and your app will produce migration-related crashes.

Jaype Sison
  • 61
  • 1
  • 1
1

No it can not, You have to write Room migrations.

Check this tutorial to write migrations.

I noticed Room does not have a good Migration System

Mahmoud Waked
  • 357
  • 2
  • 8
1

Automigration is supported from version 2.4.0

https://developer.android.com/reference/androidx/room/AutoMigration

Mr.G
  • 1,275
  • 1
  • 18
  • 48
0

Presently, with Room, you really have to write the migrations.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491