Doing a batch delete on a many-to-one relationship seems to throw this error
CoreData: error: Unhandled opt lock error from executeBatchDeleteRequest Constraint trigger violation: Batch delete failed due to mandatory OTO nullify inverse on Student/school and userInfo {
NSExceptionOmitCallstacks = 1;
NSLocalizedFailureReason = "Constraint trigger violation: Batch delete failed due to mandatory OTO nullify inverse on Student/school";
"_NSCoreDataOptimisticLockingFailureConflictsKey" = (
);
}
If I try to delete the School
in the one-to-many relationship, both the school and the students are deleted as expected.
However, If I try to delete all students the error is thrown. I would expect all students to be removed, while keeping the School intact.
Do SwiftData support this?
import XCTest
import SwiftData
@Model
class School {
var name: String
@Relationship(deleteRule: .cascade, inverse: \Student.school)
var students: [Student] = []
init(name: String) {
self.name = name
}
}
@Model
class Student {
var name: String
var school: School?
init(name: String) {
self.name = name
}
}
final class Test: XCTestCase {
func testScenario() throws {
let config = ModelConfiguration(isStoredInMemoryOnly: true)
let modelContainer = try ModelContainer(for:
School.self,
Student.self,
configurations: config
)
let context = ModelContext(modelContainer)
context.autosaveEnabled = false
let school = School(name: "school")
context.insert(school)
let student1 = Student(name: "1")
let student2 = Student(name: "2")
context.insert(student1)
context.insert(student2)
student1.school = school
student2.school = school
XCTAssertEqual(school.students.count, 2)
XCTAssertEqual(student1.school?.id, school.id)
XCTAssertEqual(student2.school?.id, school.id)
try context.save()
let newContext = ModelContext(modelContainer)
// try newContext.delete(model: School.self) // This works
try newContext.delete(model: Student.self) // This one fails
}
}