I want to count the number of models that match my filters (Predicate). To do this, I don't need all the fields of the Item model, but only the Information field. Therefore, I add propertiesToFetch to optimize (?). Most likely, this is unnecessary with context.fetchCount, but the error is reproduced when I configure a similar descriptor for Query.
Code to reproduce:
import SwiftUI
import SwiftData
struct Information: Codable, Hashable {
var field: Int
var field2: Double
var field3: Date
init() {
self.field = 0
self.field2 = 0.0
self.field3 = Date()
}
}
@Model
class Item {
@Attribute(.unique) let id: UUID
var information: Information
init() {
self.id = UUID()
self.information = Information()
}
static func count(context: ModelContext) -> Int {
var descriptor = FetchDescriptor<Item>()
descriptor.propertiesToFetch = [\.information]
do {
return try context.fetchCount(descriptor)
} catch {
return 0
}
}
}
struct ContentView: View {
@Environment(\.modelContext) var context
@State private var count: Int = 0
var body: some View {
Text("\(count)")
.onAppear {
count = Item.count(context: context)
}
}
}
I want to see the number of created models, now it is 0, and I am getting a huge number and an error in the console:
error: (1) I/O error for database at ... near ".": syntax error in "SELECT COUNT(*) from (SELECT t0.ZFIELDt0.ZFIELD2t0.ZFIELD3 FROM ZITEM t0 )"
If I remove the descriptor.propertiesToFetch = [.information], there are no problems. In the context of counting the number of models, this may not be important, but in Query I would like to leave it for optimization.