I have a question about room and using foreign keys. I'd like to add more than one foreign key to a table or set a foreign key as a null but i can't. Every time when I'm trying to insert object to database I got the android.database.sqlite.SQLiteConstraintException: FOREIGN KEY constraint failed (code 787).
I found that the parent object doesn't exist and that's why exceptions occurs. But sometime I don't need parent object and 'complex data may exist without a task object'.
Or second scenario. What if I'd like to add another one foreign key, and every time one of them would be a null??
Is it possible to make them nullable and avoid this exception?
@Entity(
tableName = "complex",
foreignKeys = [ForeignKey(entity = Task::class, parentColumns = ["id"], childColumns = ["task_id"], onDelete = CASCADE)],
indices = [Index(name = "complex_task_id_index", value = ["task_id"], unique = false)]
)
data class Complex(@PrimaryKey(autoGenerate = true) var id: Long?,
@ColumnInfo(name = "instance_id") var instanceId: Long?,
@ColumnInfo(name = "definition_id") var definitionId: Long,
@ColumnInfo(name = "task_id") var taskId: Long? = null)
@Test
fun updateComplexDefinitionTest() {
val complex = Complex(id = null, instanceId = null, definitionId = 1L, taskId = null)
complexDao.insert(complex)
}
The error occurs when I'm trying to insert object to the database