带有ForeignKey.CASCADE的Room onDelete不会删除引用的行

问题描述

我在两个表之间具有典型的一对一关系

一个实体/表中包含文档

@Entity(
    tableName = "documents",foreignKeys = [
        (ForeignKey(
            entity = Document::class,parentColumns = ["id"],childColumns = ["parentId"],onDelete = ForeignKey.CASCADE
        )),(ForeignKey(
            entity = Attachment::class,childColumns = ["attachmentId"],onDelete = ForeignKey.CASCADE
        ))
    ],indices = [
        Index(value = ["parentId"],unique = true),Index(value = ["attachmentId"])
    ]
)
class Document(
    @PrimaryKey(autoGenerate = true)
    val id: Long = 0,@Nullable
    val parentId: Long? = null,val title: String,val description: String? = "",@Nullable
    var attachmentId: Long? = null
)

然后有这个附件

@Entity(tableName = "attachments")
class Attachment(
    @PrimaryKey(autoGenerate = true)
    val id: Long,val type: FileType = FileType.RAW,val title: String? = "",@ColumnInfo(typeAffinity = ColumnInfo.BLOB)
    val data: ByteArray? = null
)

enum class FileType {
    RAW,PDF,IMAGE
}

我的文档DAO是这样的:

@Dao
interface DocumentDao {
    @Query("SELECT * FROM documents")
    fun getAll(): LiveData<List<Document>>

    @Insert(onConflict = OnConflictStrategy.ABORT)
    suspend fun insert(doc: Document)

    @Insert(onConflict = OnConflictStrategy.ABORT)
    suspend fun insert(attachment: Attachment): Long

    @Transaction
    suspend fun insert(doc: Document,attachment: Attachment) {
        val id = insert(attachment)
        doc.attachmentId= id
        insert(doc)
    }

    @Update
    suspend fun update(vararg doc: Document?)

    @Update
    suspend fun update(vararg attachment: Attachment?)

    @Transaction
    suspend fun update(doc: Document,attachment: Attachment) {
        if (attachment.id == 0L) {
            val id = insert(attachment)
            doc.attachmentId= id
        } else {
            update(attachment)
        }
        update(doc)
    }

    @Delete
    suspend fun delete(doc: Document)

    @Delete
    suspend fun delete(attachment: Attachment)
}

我可以添加带有附件的文档,对其进行更新,添加子文档(为此我使用parentId外键)。

我的问题是,即使删除父文档,附件也不会删除,即使我在表中可以清楚地看到附件的ID已正确添加parentId引用的子级文档根据onDelete = ForeignKey.CASCADE规则删除,但附件未删除

生成的用于创建表的sql如下所示:

CREATE TABLE `documents` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,`parentId` INTEGER,`title` TEXT NOT NULL,`description` TEXT,`attachmentId` INTEGER,FOREIGN KEY(`parentId`) REFERENCES `documents`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE,FOREIGN KEY(`attachmentId`) REFERENCES `attachments`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )

我真的不明白为什么删除父行时一个外键(parentId)有效,而另一个外键(attachmentId)无效

解决方法

假设您拥有:

  1. Attachment,第一行与id = 1,第二行与id = 2
  2. Document,带有id = 1attachmentId = 2的行。

据我了解,您希望在删除Document表中的行之后,也要删除Attachment表中具有id = 2的行。但是为此,您必须更改数据库结构。而是将外键documentId添加到Attachment表中。

@Entity(tableName = "attachments",foreignKeys = [
        (ForeignKey(
            entity = Document::class,parentColumns = ["id"],childColumns = ["documentId"],onDelete = ForeignKey.CASCADE
        )]
)
class Attachment(
    @PrimaryKey(autoGenerate = true)
    val id: Long,val documentId: Long,// <-- Foreign key to Document Entity
    val type: FileType = FileType.RAW,val title: String? = "",@ColumnInfo(typeAffinity = ColumnInfo.BLOB)
    val data: ByteArray? = null
)

由于在删除某些行时,Sqlite会在绑定到该行的所有其他表中查找所有外键,然后将其删除。

更新:以下添加内容具有误导性,不应予以考虑

此外,您确定删除父行后确实删除了子行吗?看来您必须更改parentColumschildColumns

ForeignKey(
            entity = Document::class,// <-- should be childColumns instead?
            childColumns = ["parentId"],// <-- should be parentColumns instead?
            onDelete = ForeignKey.CASCADE
        ))
,

我最终删除了附件的外键,并在交易中将其删除

@Query("DELETE FROM attachments WHERE id = :attachmentId")
fun deleteAttachment(attachmentId: Long)

@Transaction
suspend fun deleteWithAttachment(doc: Document) {
    if (doc.attachmentId != null) {
        deleteAttachment(doc.attachmentId!!)
    }
    delete(doc)
}