Room database migration if only new table is added

前端 未结 6 1095
不思量自难忘°
不思量自难忘° 2020-12-07 09:07

Let\'t assume, I have a simple Room database:

@Database(entities = {User.class}, version = 1)
abstract class AppDatabase extends RoomDatabase {
    public ab         


        
6条回答
  •  南笙
    南笙 (楼主)
    2020-12-07 10:06

    You can add the following gradle command to your defaultConfig in your app.gradle:

    javaCompileOptions {
            annotationProcessorOptions {
                arguments = ["room.schemaLocation":
                                     "$projectDir/schemas".toString()]
            }
        }
    

    When you run this it will compile a list of table names with their relevant CREATE TABLE statements from which you can just copy and paste into your migration objects. You might have to change the table names.

    For example this is from my generated schema:

    "tableName": "assets",
    "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`asset_id` INTEGER NOT NULL, `type` INTEGER NOT NULL, `base` TEXT NOT NULL, `name` TEXT NOT NULL, PRIMARY KEY(`asset_id`))"
    

    And so I copy paste the createSql statement and change the '${TABLE_NAME}' to 'assets' the table name, and voila auto generated Room create statements.

提交回复
热议问题