Skip to content Skip to sidebar Skip to footer

Room's `ondelete = Cascade` Not Working During A Migration

I have the following tables: @Entity( tableName = 'users' ) class Users { @PrimaryKey(autoGenerate = true) var id: Long? = null @NonNull var name: String? = nu

Solution 1:

As @sergiytikhonov indicates in his comment, enabling the foreign_keys constraint in a migration function has no effect. This is because migrations are executed as part of a transaction and the pragma is a no-op inside a transaction.

I don't see any way to get control and enable foreign_keys before the migration is executed. I think your only option is to delete the pets explicitly as part of the migration:

override fun migrate(database: SupportSQLiteDatabase) {
    database.execSQL("""
        DELETE FROM pets WHERE owner_id IN (SELECT id FROM users)
    """)

    database.execSQL("""
        DELETE FROM users
    """)
}

Post a Comment for "Room's `ondelete = Cascade` Not Working During A Migration"