android – Room: Transaction with deferred foreign key constraint violation is not ended-ThrowExceptions

Exception or error:

I have a Room Database with two entities, let’s call them A and B. B references A through a foreign key. The foreign key is set to be deferred until the transaction has ended:

@ForeignKey(entity = A.class, deferred = true, parentColumns = "_id", childColumns = "A_id")

When I now try do delete a row in A that is referenced by a row in B while running in a transaction (e.g. using RoomDatabase.runInTransaction()), the transaction fails and an SQLiteConstraintException is thrown, as expected. However, when I try to start another transaction on the same database object, I get the following exception:

android.database.sqlite.SQLiteException: cannot start a transaction within a transaction (code 1 SQLITE_ERROR)

In addition, the following is printed to Logcat:

E/SQLiteLog: (1) statement aborts at 3: [BEGIN EXCLUSIVE;] cannot start a transaction within a transaction

So it looks like the initial transaction was not actually ended properly in the underlying SQLite layer when the SQLiteConstraintException was thrown.
Is this intended behaviour?
From this state, there does not seem to be a way to end the underlying transaction. Calling RoomDatabase.inTransaction() actually yields false, and RoomDatabase.endTransaction() (which is marked as obsolete anyways) does not end the transaction.

I am using Room version 2.1.0.

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *