Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ extension OCKStore {
switch order {
case .effectiveDate(let ascending): return NSSortDescriptor(keyPath: \OCKCDCarePlan.effectiveDate, ascending: ascending)
case .title(let ascending): return NSSortDescriptor(keyPath: \OCKCDCarePlan.title, ascending: ascending)
case .groupIdentifier(let ascending): return NSSortDescriptor(keyPath: \OCKCDCarePlan.groupIdentifier, ascending: ascending)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added groupIdentifier sort to all that was missing

}
} + query.defaultSortDescriptors()
}
Expand Down
1 change: 1 addition & 0 deletions CareKitStore/CareKitStore/CoreData/OCKStore+Contacts.swift
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ extension OCKStore {
case .effectiveDate(ascending: let ascending): return NSSortDescriptor(keyPath: \OCKCDContact.effectiveDate, ascending: ascending)
case .familyName(ascending: let ascending): return NSSortDescriptor(keyPath: \OCKCDContact.name.familyName, ascending: ascending)
case .givenName(ascending: let ascending): return NSSortDescriptor(keyPath: \OCKCDContact.name.givenName, ascending: ascending)
case .groupIdentifier(let ascending): return NSSortDescriptor(keyPath: \OCKCDContact.groupIdentifier, ascending: ascending)
}
} + query.defaultSortDescriptors()
}
Expand Down
7 changes: 6 additions & 1 deletion CareKitStore/CareKitStore/CoreData/OCKStore+Outcomes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,12 @@ extension OCKStore {
}

private func buildSortDescriptors(for query: OCKOutcomeQuery) -> [NSSortDescriptor] {
query.defaultSortDescriptors()
query.sortDescriptors.map { order -> NSSortDescriptor in
switch order {
case .effectiveDate(let ascending): return NSSortDescriptor(keyPath: \OCKCDOutcome.effectiveDate, ascending: ascending)
case .groupIdentifier(let ascending): return NSSortDescriptor(keyPath: \OCKCDOutcome.groupIdentifier, ascending: ascending)
}
} + query.defaultSortDescriptors()
}

private func doesEventForOutcomeOccur(in interval: DateInterval) -> NSPredicate {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -530,12 +530,23 @@ extension OCKHealthKitPassthroughStore {

func makeTaskQuery(from outcomeQuery: OCKOutcomeQuery) -> OCKTaskQuery {

let dateInterval = Calendar.current.dateInterval(of: .day, for: Date())!
// Search over the interval provided by OCKOutcomeQuery if present
// or else constrain sample query over the current day.
let dateInterval = outcomeQuery.dateInterval ??
Calendar.current.dateInterval(of: .day, for: Date())!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similar to

// We need to explicitly set the date interval in case it's nil
// to ensure that we fetch the most recent version of a task in a
// given date interval, and not all versions of the task
let dateInterval = latestTaskVersionsQuery.dateInterval ??
Calendar.current.dateInterval(of: .day, for: Date())!
latestTaskVersionsQuery.dateInterval = dateInterval


var taskQuery = OCKTaskQuery(dateInterval: dateInterval)
taskQuery.ids = outcomeQuery.taskIDs
taskQuery.remoteIDs = outcomeQuery.taskRemoteIDs
taskQuery.uuids = outcomeQuery.taskUUIDs
taskQuery.sortDescriptors = outcomeQuery.sortDescriptors.map { descriptor in

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pass relevant sort criteria to the task query.

switch descriptor {
case .effectiveDate(ascending: let ascending):
return OCKTaskQuery.SortDescriptor.effectiveDate(ascending: ascending)
case .groupIdentifier(ascending: let ascending):
return OCKTaskQuery.SortDescriptor.groupIdentifier(ascending: ascending)
}
}

return taskQuery
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ public extension OCKAnyReadOnlyCarePlanStore {
completion: @escaping OCKResultClosure<OCKAnyCarePlan>) {
var query = OCKCarePlanQuery(for: Date())
query.limit = 1
query.sortDescriptors = [.effectiveDate(ascending: true)]
query.sortDescriptors = [.effectiveDate(ascending: false)]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All of these should be false to always get the newest version related to today, similar to how the fetching task was set up.

query.ids = [id]

fetchAnyCarePlans(query: query, callbackQueue: callbackQueue, completion:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ public extension OCKReadableCarePlanStore {
func fetchCarePlan(withID id: String, callbackQueue: DispatchQueue = .main, completion: @escaping OCKResultClosure<Plan>) {
var query = OCKCarePlanQuery(for: Date())
query.limit = 1
query.sortDescriptors = [.effectiveDate(ascending: true)]
query.sortDescriptors = [.effectiveDate(ascending: false)]
query.ids = [id]

fetchCarePlans(query: query, callbackQueue: callbackQueue, completion:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public extension OCKAnyReadOnlyContactStore {
completion: @escaping OCKResultClosure<OCKAnyContact>) {
var query = OCKContactQuery(for: Date())
query.limit = 1
query.sortDescriptors = [.effectiveDate(ascending: true)]
query.sortDescriptors = [.effectiveDate(ascending: false)]
query.ids = [id]

fetchAnyContacts(query: query, callbackQueue: callbackQueue, completion:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ public extension OCKReadableContactStore {
var query = OCKContactQuery(for: Date())
query.limit = 1
query.ids = [id]
query.sortDescriptors = [.effectiveDate(ascending: true)]
query.sortDescriptors = [.effectiveDate(ascending: false)]

fetchContacts(query: query, callbackQueue: callbackQueue, completion:
chooseFirst(then: completion, replacementError: .fetchFailed(reason: "No contact with matching ID")))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ public extension OCKAnyReadOnlyPatientStore {
) {
var query = OCKPatientQuery(for: Date())
query.limit = 1
query.sortDescriptors = [.effectiveDate(ascending: true)]
query.sortDescriptors = [.effectiveDate(ascending: false)]
query.ids = [id]

fetchAnyPatients(query: query, callbackQueue: callbackQueue, completion:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ public extension OCKReadablePatientStore {
var query = OCKPatientQuery(for: Date())
query.limit = 1
query.ids = [id]
query.sortDescriptors = [.effectiveDate(ascending: true)]
query.sortDescriptors = [.effectiveDate(ascending: false)]

fetchPatients(query: query, callbackQueue: callbackQueue, completion:
chooseFirst(then: completion, replacementError: .fetchFailed(reason: "No patient with matching ID")))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ public protocol OCKAnyTaskStore: OCKAnyReadOnlyTaskStore {

public extension OCKAnyReadOnlyTaskStore {
func fetchAnyTask(withID id: String, callbackQueue: DispatchQueue = .main, completion: @escaping OCKResultClosure<OCKAnyTask>) {
var query = OCKTaskQuery(id: id)
var query = OCKTaskQuery(for: Date())

@cbaker6 cbaker6 Mar 3, 2025

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Switched this so it's aligned with the other Entity fetches. It was setting the id twice instead of querying the current version for today. Without the change, it's possible for this fetch to return a future version of the task since it would have a future effectiveDate.

query.sortDescriptors = [.effectiveDate(ascending: false)]
query.ids = [id]
query.limit = 1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ public protocol OCKTaskStore: OCKReadableTaskStore, OCKAnyTaskStore {
public extension OCKReadableTaskStore {
func fetchTask(withID id: String, callbackQueue: DispatchQueue = .main, completion: @escaping OCKResultClosure<Task>) {
var query = OCKTaskQuery(for: Date())
query.sortDescriptors = [.effectiveDate(ascending: true)]
query.sortDescriptors = [.effectiveDate(ascending: false)]
query.ids = [id]
query.limit = 1

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,11 @@ extension OCKStoreCoordinator {
sequences: outcomesStreams,
makeSortDescriptors: {

let sortDescriptor = NSSortDescriptor(
keyPath: \OCKCDOutcome.id,
ascending: true
)
let sortDescriptors = query
.sortDescriptors
.map(\.nsSortDescriptor)

return [sortDescriptor]
return sortDescriptors
}
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,16 @@ public struct OCKCarePlanQuery: Equatable, Sendable, OCKQueryProtocol {

case title(ascending: Bool)
case effectiveDate(ascending: Bool)
case groupIdentifier(ascending: Bool)

var nsSortDescriptor: NSSortDescriptor {
switch self {
case let .effectiveDate(ascending):
return NSSortDescriptor(keyPath: \OCKCDCarePlan.effectiveDate, ascending: ascending)
case let .title(ascending):
return NSSortDescriptor(keyPath: \OCKCDCarePlan.title, ascending: ascending)
case let .groupIdentifier(ascending):
return NSSortDescriptor(keyPath: \OCKCDCarePlan.groupIdentifier, ascending: ascending)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,18 @@ public struct OCKContactQuery: Equatable, Sendable, OCKQueryProtocol {
case givenName(ascending: Bool)
case familyName(ascending: Bool)
case effectiveDate(ascending: Bool)
case groupIdentifier(ascending: Bool)

var nsSortDescriptor: NSSortDescriptor {
switch self {
case let .effectiveDate(ascending):
return NSSortDescriptor(keyPath: \OCKCDContact.effectiveDate, ascending: ascending)
case let .givenName(ascending):
return NSSortDescriptor(keyPath: \OCKCDContact.name.givenName, ascending: ascending)
case let .familyName(ascending):
return NSSortDescriptor(keyPath: \OCKCDContact.name.familyName, ascending: ascending)
case let .effectiveDate(ascending):
return NSSortDescriptor(keyPath: \OCKCDContact.effectiveDate, ascending: ascending)
case let .groupIdentifier(ascending):
return NSSortDescriptor(keyPath: \OCKCDContact.groupIdentifier, ascending: ascending)
}
}
}
Expand Down
19 changes: 19 additions & 0 deletions CareKitStore/CareKitStore/Structs/Queries/OCKOutcomeQuery.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,22 @@ import Foundation
/// A query that limits which outcomes will be returned when fetching.
public struct OCKOutcomeQuery: Equatable, Sendable, OCKQueryProtocol {

/// Specifies the order in which query results will be sorted.
public enum SortDescriptor: Equatable, Sendable {

case effectiveDate(ascending: Bool)
case groupIdentifier(ascending: Bool)

var nsSortDescriptor: NSSortDescriptor {
switch self {
case let .effectiveDate(ascending):
return NSSortDescriptor(keyPath: \OCKCDOutcome.effectiveDate, ascending: ascending)
case let .groupIdentifier(ascending):
return NSSortDescriptor(keyPath: \OCKCDOutcome.groupIdentifier, ascending: ascending)
}
}
}

/// An array of task identifiers to match against.
public var taskIDs: [String] = []

Expand All @@ -42,6 +58,9 @@ public struct OCKOutcomeQuery: Equatable, Sendable, OCKQueryProtocol {
/// An array of remote IDs of tasks for which outcomes should be returned.
public var taskRemoteIDs: [String] = []

/// The order in which the results will be sorted when returned from the query.
public var sortDescriptors: [SortDescriptor] = []

// MARK: OCKQuery
public var ids: [String] = []
public var uuids: [UUID] = []
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public struct OCKTaskQuery: Equatable, Sendable, OCKQueryProtocol {
/// The remote IDs of the care plans for which tasks should match.
public var carePlanRemoteIDs: [String] = []

/// Determines if tasks with no events should be included in the query results or not. False be default.
/// Determines if tasks with no events should be included in the query results or not. False by default.
public var excludesTasksWithNoEvents = false

/// The order in which the results will be sorted when returned from the query.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,58 @@ class TestHealthKitPassthroughStoreOutcomes: XCTestCase {
try passthroughStore.checkAbilityToDelete(outcomes: outcomes)
}

func testTaskQueryDefaultsToCurrentDayDateInterval() async throws {
let outcomeTaskQuery = OCKOutcomeQuery()
let taskQuery = passthroughStore.makeTaskQuery(from: outcomeTaskQuery)
let currentDayDateInterval = Calendar.current.dateInterval(of: .day, for: Date())!

XCTAssertEqual(
taskQuery.dateInterval?.start,
currentDayDateInterval.start
)
XCTAssertEqual(
taskQuery.dateInterval?.end,
currentDayDateInterval.end
)
XCTAssertEqual(taskQuery.ids, outcomeTaskQuery.taskIDs)
XCTAssertEqual(taskQuery.remoteIDs, outcomeTaskQuery.taskRemoteIDs)
XCTAssertEqual(taskQuery.uuids, outcomeTaskQuery.taskUUIDs)
XCTAssertTrue(taskQuery.sortDescriptors.isEmpty)
}

func testTaskQueryPropertiesAdoptsOutcomeQueryProperties() async throws {
let yesterday = Calendar.current.date(
byAdding: .day,
value: -1,
to: Date()
)!
let yesterdayDateInterval = Calendar.current.dateInterval(
of: .day,
for: yesterday
)!
var outcomeTaskQuery = OCKOutcomeQuery(
dateInterval: yesterdayDateInterval
)
outcomeTaskQuery.taskIDs = ["id"]
outcomeTaskQuery.taskRemoteIDs = ["remoteID"]
outcomeTaskQuery.taskUUIDs = [UUID()]
outcomeTaskQuery.sortDescriptors = [
.effectiveDate(ascending: true),
.groupIdentifier(ascending: true)
]
let taskQuery = passthroughStore.makeTaskQuery(from: outcomeTaskQuery)
let expectedTaskSortDescriptors: [OCKTaskQuery.SortDescriptor] = [
.effectiveDate(ascending: true),
.groupIdentifier(ascending: true)
]

XCTAssertEqual(taskQuery.dateInterval, outcomeTaskQuery.dateInterval)
XCTAssertEqual(taskQuery.ids, outcomeTaskQuery.taskIDs)
XCTAssertEqual(taskQuery.remoteIDs, outcomeTaskQuery.taskRemoteIDs)
XCTAssertEqual(taskQuery.uuids, outcomeTaskQuery.taskUUIDs)
XCTAssertEqual(taskQuery.sortDescriptors, expectedTaskSortDescriptors)
}

// MARK: - Utilities

private func makeStepsTask() -> OCKHealthKitTask {
Expand Down
14 changes: 14 additions & 0 deletions CareKitStore/CareKitStoreTests/OCKStore/TestStore+CarePlans.swift
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,20 @@ class TestStoreCarePlans: XCTestCase {
XCTAssertEqual(fetched.previousVersionUUIDs.first, versionA.uuid)
}

func testCarePlanQueryByIdConvenienceMethodReturnsLatestVersionOfACarePlan() async throws {
let versionA = try await store.addCarePlan(OCKCarePlan(id: "A", title: "Amy", patientUUID: nil))
let versionB = try await store.updateCarePlan(OCKCarePlan(id: "A", title: "Jared", patientUUID: nil))
let fetched = try await store.fetchCarePlan(withID: versionA.id)
XCTAssertEqual(fetched.title, versionB.title)
}

func testAnyCarePlanQueryByIdConvenienceMethodReturnsLatestVersionOfACarePlan() async throws {
let versionA = try await store.addCarePlan(OCKCarePlan(id: "A", title: "Amy", patientUUID: nil))
let versionB = try await store.updateCarePlan(OCKCarePlan(id: "A", title: "Jared", patientUUID: nil))
let fetched = try await store.fetchAnyCarePlan(withID: versionA.id)
XCTAssertEqual(fetched.title, versionB.title)
}

func testCarePlanQueryOnPastDateReturnsPastVersionOfACarePlan() async throws {
let dateA = Date().addingTimeInterval(-100)
var versionA = OCKCarePlan(id: "A", title: "a", patientUUID: nil)
Expand Down
17 changes: 17 additions & 0 deletions CareKitStore/CareKitStoreTests/OCKStore/TestStore+Contacts.swift
Original file line number Diff line number Diff line change
Expand Up @@ -252,11 +252,28 @@ class TestStoreContacts: XCTestCase {
XCTAssertEqual(fetched.name, versionD.name)
}

func testContactQueryByIdConvenienceMethodReturnsLatestVersionOfAContact() async throws {
let versionA = try await store.addContact(OCKContact(id: "contact", givenName: "A", familyName: "", carePlanUUID: nil))
let versionB = try await store.updateContact(OCKContact(id: "contact", givenName: "B", familyName: "", carePlanUUID: nil))

let fetched = try await store.fetchContact(withID: versionA.id)
XCTAssertEqual(fetched.name.givenName, versionB.name.givenName)
}

func testAnyContactQueryByIdConvenienceMethodReturnsLatestVersionOfAContact() async throws {
let versionA = try await store.addContact(OCKContact(id: "contact", givenName: "A", familyName: "", carePlanUUID: nil))
let versionB = try await store.updateContact(OCKContact(id: "contact", givenName: "B", familyName: "", carePlanUUID: nil))

let fetched = try await store.fetchContact(withID: versionA.id)
XCTAssertEqual(fetched.name.givenName, versionB.name.givenName)
}

func testContactQueryWithDateOnlyReturnsLatestVersionOfAContact() async throws {
try await store.addContact(OCKContact(id: "contact", givenName: "A", familyName: "", carePlanUUID: nil))
try await store.updateContact(OCKContact(id: "contact", givenName: "B", familyName: "", carePlanUUID: nil))
try await store.updateContact(OCKContact(id: "contact", givenName: "C", familyName: "", carePlanUUID: nil))
try await store.updateContact(OCKContact(id: "contact", givenName: "D", familyName: "", carePlanUUID: nil))

let fetched = try await store.fetchContacts(query: OCKContactQuery(for: Date()))
XCTAssertEqual(fetched.count, 1)
XCTAssertEqual(fetched.first?.name.givenName, "D")
Expand Down
14 changes: 14 additions & 0 deletions CareKitStore/CareKitStoreTests/OCKStore/TestStore+Patients.swift
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,20 @@ class TestStorePatients: XCTestCase {
XCTAssertEqual(fetched, versionB)
}

func testPatientQueryByIdConvenienceMethodReturnsLatestVersionOfAPatient() async throws {
let versionA = try await store.addPatient(OCKPatient(id: "A", givenName: "Jared", familyName: "Gosler"))
let versionB = try await store.updatePatient(OCKPatient(id: "A", givenName: "John", familyName: "Appleseed"))
let fetched = try await store.fetchPatient(withID: versionA.id)
XCTAssertEqual(fetched.name.familyName, versionB.name.familyName)
}

func testAnyPatientQueryByIdConvenienceMethodReturnsLatestVersionOfAPatient() async throws {
let versionA = try await store.addPatient(OCKPatient(id: "A", givenName: "Jared", familyName: "Gosler"))
let versionB = try await store.updatePatient(OCKPatient(id: "A", givenName: "John", familyName: "Appleseed"))
let fetched = try await store.fetchPatient(withID: versionA.id)
XCTAssertEqual(fetched.name.familyName, versionB.name.familyName)
}

func testPatientQueryOnPastDateReturnsPastVersionOfAPatient() async throws {
let dateA = Date().addingTimeInterval(-100)
var versionA = OCKPatient(id: "A", givenName: "Jared", familyName: "Gosler")
Expand Down
20 changes: 18 additions & 2 deletions CareKitStore/CareKitStoreTests/OCKStore/TestStore+Tasks.swift
Original file line number Diff line number Diff line change
Expand Up @@ -374,11 +374,27 @@ class TestStoreTasks: XCTestCase {

var taskV2 = taskV1
taskV2.title = "V2"
taskV2.effectiveDate = Calendar.current.date(byAdding: .year, value: 1, to: Date())!

@cbaker6 cbaker6 Mar 3, 2025

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adjusted this test based on #723 (comment). This effectiveDate essentially could have been next year and it would have returned next years task today, which would be unexpected

taskV2 = try await store.updateTask(taskV2)

let task = try await store.fetchTask(withID: "task")
XCTAssertEqual(task.title, taskV2.title)
}

func testFetchAnyTaskByIdConvenienceMethodReturnsNewestVersionOfTask() async throws {
let coordinator = OCKStoreCoordinator()
let store = OCKStore(name: "test", type: .inMemory)
coordinator.attach(store: store)

let schedule = OCKSchedule.dailyAtTime(hour: 0, minutes: 0, start: Date(), end: nil, text: nil)
var taskV1 = OCKTask(id: "task", title: "V1", carePlanUUID: nil, schedule: schedule)
taskV1 = try await store.addTask(taskV1)

var taskV2 = taskV1
taskV2.title = "V2"
taskV2 = try await store.updateTask(taskV2)

let fetchedTask = try await store.fetchAnyTask(withID: "task")
XCTAssertEqual(fetchedTask.title, "V2")
XCTAssertEqual(fetchedTask.title, taskV2.title)
}

func testTaskQueryStartingExactlyOnEffectiveDateOfNewVersion() async throws {
Expand Down