由于房间中的唯一约束,数据库迁移失败

时间:2017-12-07 06:28:07

标签: android android-room android-architecture-components

我在旧数据库中的一个表中有唯一约束。 在迁移到房间时,我根据[link] [1]上给出的指令创建了新表,并使用" indices"来应用唯一约束。 " TaskDetail"中的关键字实体类。 并提供空迁移。在运行迁移测试时,我得到与唯一约束相关的错误,如下所述。 我做错了什么?

  

数据库架构

String CREATE_TABLE_TASK = "CREATE TABLE IF NOT EXISTS "+TASK+
            " (`task_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," +
            "`task_note` TEXT," +
            "`status` INTEGER NOT NULL)";


    String CREATE_TABLE_TASK_DETAIL = "CREATE TABLE IF NOT EXISTS "+TASK_DETAIL+
            " (`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," +
            "`detail` TEXT NOT NULL UNIQUE)";
  

房间实体表

@Entity(tableName = "task_master")
        public class Task {

            @ColumnInfo(name = "task_id")
            @PrimaryKey(autoGenerate = true)
            @NonNull
            private int taskId;

            @ColumnInfo(name = "task_note")
            private String task;

            private @TaskStatus
            int status;

        }

//TOKEN DETAIL TABLE
@Entity(tableName = "task_detail",indices ={@Index(name = "detail",value = "detail",unique = true)})
    public class TaskDetail {

        @PrimaryKey(autoGenerate = true)
        private int id;

        @NonNull
        private String detail;

    }
  

RoomDatabase类

@Database(entities = {Task.class, TaskDetail.class},version = 2,exportSchema = true)
public abstract class AppDatabase extends RoomDatabase{

    private static final Object sObject = new Object();
    private static AppDatabase sInstance;

    public abstract TaskDao getTaskDao();

    public static AppDatabase getInstance(Context context){

        if(sInstance == null){
            synchronized (sObject){
                if(sInstance == null){
                    sInstance = Room.databaseBuilder(context,AppDatabase.class,"task.db")
                            .allowMainThreadQueries()
                            .build();
                }
            }
        }
        return sInstance;
    }
}
  

错误

expacted:TableInfo{name='task_detail', columns={id=Column{name='id', type='INTEGER', notNull=true, primaryKeyPosition=1}, detail=Column{name='detail', type='TEXT', notNull=true, primaryKeyPosition=0}}, foreignKeys=[], indices=[Index{name='detail', unique=true, columns=[detail]}]}

found:TableInfo{name='task_detail', columns={id=Column{name='id', type='INTEGER', notNull=true, primaryKeyPosition=1}, detail=Column{name='detail', type='TEXT', notNull=true, primaryKeyPosition=0}}, foreignKeys=[], indices=[]}

1 个答案:

答案 0 :(得分:0)

您必须为表定义UNIX索引。对于task_master,如果您的唯一键是task_id,请添加以下内容:

database.execSQL("CREATE UNIQUE INDEX `index_task_master_task_id` ON `task_master` (`task_id`)");

task_detail表相同