To prevent the deletion of a parent row which has one or more related child rows in my Room database, I've set my ForeignKey onDelete method to RESTRICT.
My database has two tables: products and document_products which has the ForeignKey on products, during the application usage, the user is able to delete all items from the products table but I need to still keep the items in document_products but the RESTRICT seems not to be working as even with it I'm getting:
FOREIGN KEY constraint failed (code 1811 SQLITE_CONSTRAINT_TRIGGER)
My DocumentProduct entity looks like this:
@JsonClass(generateAdapter = true)
@Entity(
tableName = "document_products",
foreignKeys = [
ForeignKey(
entity = Document::class,
parentColumns = ["id"],
childColumns = ["documentId"],
onDelete = CASCADE
),
ForeignKey(
entity = Product::class,
parentColumns = ["products_id"],
childColumns = ["document_products_productIdMap"],
onDelete = RESTRICT
)
],
indices = [Index("document_products_productIdMap"), Index("documentId"), Index(
value = ["document_products_productIdMap", "documentId", "labelType"],
unique = true
)]
)
data class DocumentProduct(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "document_products_id")
var id: Long,
@ColumnInfo(name = "document_products_productIdMap")
var productId: String,
@ColumnInfo(name = "document_products_quantity")
var quantity: Float,
var orderQuantity: Float,
@ColumnInfo(name = "document_products_purchase")
var purchase: Float,
var documentId: Long,
var labelType: String?,
var timestamp: Long?
)
While Product:
@Entity(tableName = "products")
open class Product(
@PrimaryKey(autoGenerate = false)
@ColumnInfo(name = "products_id")
open var id: String,
open var description: String?,
@ColumnInfo(defaultValue = "PZ")
open var unitOfMeasure: String,
@ColumnInfo(name = "products_purchase")
open var purchase: Float,
open var price: Float,
@ColumnInfo(name = "products_quantity")
open var quantity: Float
)
And in the application settings the user is able to run the following query from ProductDAO:
@Query("DELETE FROM products")
suspend fun deleteAll(): Int
What I'm looking for is a solution in which I can keep the parent rows which has one or more related child rows OR where I can keep the ForeignKey without a real relation.