I have two entities in my Room database:
@Entity(
tableName = "user",
primaryKeys = ["id"],
)
data class User(
@ColumnInfo(name = "id")
val userId: Long,
// Other columns here
)
@Entity(
tableName = "entry",
primaryKeys = ["id"],
foreignKeys = [
ForeignKey(
entity = User::class,
parentColumns = ["id"],
childColumns = ["user_id"],
onDelete = ForeignKey.CASCADE,
),
],
)
data class Entry(
@ColumnInfo(name = "id")
val id: Long,
@ColumnInfo(name = "user_id")
val userId: Long,
@ColumnInfo(name = "active")
val active: Boolean,
)
I also have DAOs to operate on these. The relevant DAO method is this one that updates the “active” column for entries:
@Query("SELECT * FROM entry WHERE id = :id")
suspend fun getEntry(id: Long): Entry?
@Update
suspend fun updateEntry(entry: Entry)
Then, I have this code that updates the active status:
suspend fun setActive(entryId: Long) {
val entry = dao.getEntry(entryId)
entry?.let {
dao.updateEntry(entry.copy(active = true))
}
}
However, in production on some users, calls to the setActive()
function throw a SQLiteConstraintException: error code 19: FOREIGN KEY constraint failed
. What could be causing this? To my knowledge, the onDelete = CASCADE should delete the entries if a user is deleted. My logs don’t seem to indicate whether the throw happens on the getEntry()
call or the updateEntry()
call.