Add SwiftData relationship integrity and validation
- Dominant language
- Swift
- Stars
- 0
- Forks
- 0
- Avg merge
- 1h 41m
- Merged PRs (30d)
- 1
Description
### Problem
Current SwiftData models lack proper relationship delete rules and validation, leading to:
- Orphaned references (causing crashes)
- Data inconsistency
- No referential integrity guarantees
### Current State Analysis
#### Missing Delete Rules
```swift
// Stream.swift
var source: Thought? // ⚠️ No delete rule - causes orphaning
@Relationship(deleteRule: .cascade, inverse: \Thought.stream) var thoughts: [Thought] // ✅ Good
// Thought.swift
var stream: Stream? // ⚠️ No delete rule specified
```
### Proposed Solutions
#### 1. Add Delete Rules
```swift
// Stream.swift
@Relationship(deleteRule: .nullify) var source: Thought?
@Relationship(deleteRule: .cascade, inverse: \Thought.stream) var thoughts: [Thought]
// Thought.swift
@Relationship(deleteRule: .nullify, inverse: \Stream.thoughts) var stream: Stream?
```
#### 2. Add Model Validation Protocol
```swift
protocol ValidatableModel {
var isValid: Bool { get }
func validate() throws
}
extension Stream: ValidatableModel {
var isValid: Bool {
if let source = source {
guard !source.isDeleted, source.modelContext != nil else { return false }
}
return thoughts.allSatisfy { !$0.isDeleted && $0.modelContext != nil }
}
}
```
#### 3. Add Computed Properties for Safety
```swift
extension Stream {
@Transient var safeSource: Thought? {
guard let source = source, !source.isDeleted else { return nil }
return source
}
@Transient var validThoughts: [Thought] {
thoughts.filter { !$0.isDeleted }
}
}
```
### Implementation Checklist
- [ ] Add `@Relationship(deleteRule: .nullify)` to `Stream.source`
- [ ] Add `@Relationship(deleteRule: .nullify)` to `Thought.stream`
- [ ] Create `ValidatableModel` protocol
- [ ] Implement validation on models
- [ ] Add safe access computed properties
- [ ] Add `validateDataIntegrity()` to `PersistenceController`
- [ ] Add unit tests for validation logic
### Files to Modify
- `Stream.swift`
- `Thought.swift`
- `Profile.swift`
- `PersistenceController.swift`
- New file: `ModelValidation.swift`
Contributor guide
No contributing guide indexed for this repository
Research direction
Start by reading Stream.swift, Thought.swift, Profile.swift, PersistenceController.swift, and the proposed new ModelValidation.swift to understand the existing SwiftData relationships and persistence flow. Implement the checklist across those files, including relationship rules, validation, safe accessors, integrity checking, and unit tests; done means the listed orphan and consistency cases are covered and tests pass.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- swift
- Domain
- database
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100