From 50d572b72d0b52370f8b76bb41cf3f8c3e249c8e Mon Sep 17 00:00:00 2001 From: Christoph Hagen Date: Tue, 19 Mar 2024 11:28:44 +0100 Subject: [PATCH] Get stored workout types and frequencies --- .../HKDatabase/Database/HKDatabaseStore.swift | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/Sources/HKDatabase/Database/HKDatabaseStore.swift b/Sources/HKDatabase/Database/HKDatabaseStore.swift index 6635a33..b54d557 100644 --- a/Sources/HKDatabase/Database/HKDatabaseStore.swift +++ b/Sources/HKDatabase/Database/HKDatabaseStore.swift @@ -669,6 +669,39 @@ public final class HKDatabaseStore { // MARK: Workouts + /** + Get a list of all workout activity types in the database. + */ + public func storedWorkoutTypes() throws -> [HKWorkoutActivityType] { + let query = workoutActivities.table + .select(workoutActivities.activityType.distinct) + return try database.prepare(query).compactMap { row in + let raw = row[workoutActivities.activityType.distinct] + return HKWorkoutActivityType(rawValue: UInt(raw)) + } + } + + /** + Get a list of all workout activity types in the database including their count + */ + public func workoutTypeFrequencies() throws -> [HKWorkoutActivityType: Int] { + let query = workoutActivities.table + .select(workoutActivities.activityType) + return try database.prepare(query).reduce(into: [:]) { result, row in + let raw = row[workoutActivities.activityType] + guard raw >= 0 else { + print("Found unknown activity type \(raw)") + return + } + guard let type = HKWorkoutActivityType(rawValue: UInt(raw)) else { + print("Found unknown activity type \(raw)") + return + } + let oldCount = result[type] ?? 0 + result[type] = oldCount + 1 + } + } + /** All workouts in the database, regardless of type. - Parameter start: The start of the date range of interest