I am having unique constraint in one of my table in my old database. While migrating to room, I have created new table as per instruction given on [link][1] and applied unique constraint using "indices" keyword in "TaskDetail" entity class. And provided empty migration. while running migration test i get error related to unique constraint as mentioned below. Am I doing any thing wrong??
Database Schema
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)";
Room Entity Tables
@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 class
@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;
}
}
Error
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=[]}
You have to define unix index for your tables. For task_master
if your unique key is task_id
add something like:
database.execSQL("CREATE UNIQUE INDEX `index_task_master_task_id` ON `task_master` (`task_id`)");
Same as for the task_detail
table
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With