LocalHealthKitSQLiteReader.swift 21.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
import Foundation
import HealthKit
import SQLite3

enum LocalHealthKitSQLiteError: LocalizedError {
  case databaseNotFound
  case databaseOpenFailed(String)
  case queryFailed(String)

  var errorDescription: String? {
    switch self {
    case .databaseNotFound:
      return "未找到本地健康数据 export.sqlite"
    case .databaseOpenFailed(let message):
      return "打开本地健康数据库失败:\(message)"
    case .queryFailed(let message):
      return "查询本地健康数据库失败:\(message)"
    }
  }
}

final class LocalHealthKitSQLiteReader {
  private let databaseURL: URL

  init(databaseURL: URL? = nil) throws {
    guard let databaseURL = databaseURL ?? Self.defaultDatabaseURL() else {
      throw LocalHealthKitSQLiteError.databaseNotFound
    }
    self.databaseURL = databaseURL
  }

  func fetchData(
    for dataType: NativeHealthDataType,
    startDate: Date,
    endDate: Date
  ) async throws -> [NativeHealthDataPoint] {
    switch dataType {
    case .sleep:
      return []
    case .activeEnergy:
      return try await fetchActivitySummaryData(
        dataType: .activeEnergy,
        valueColumn: "active_energy_burned",
        multiplier: 1,
        startDate: startDate,
        endDate: endDate
      )
    case .exercise:
      return try await fetchActivitySummaryData(
        dataType: .exercise,
        valueColumn: "apple_exercise_time",
        multiplier: 60,
        startDate: startDate,
        endDate: endDate
      )
    case .stand:
      return try await fetchActivitySummaryData(
        dataType: .stand,
        valueColumn: "apple_stand_hours",
        multiplier: 1,
        startDate: startDate,
        endDate: endDate
      )
    case .irregularHeartRhythm:
      return try await fetchRawCategoryData(
        type: healthKitIdentifier(for: dataType),
        dataType: dataType,
        startDate: startDate,
        endDate: endDate
      ).map { NativeHealthDataPoint(dataType: $0.dataType, time: $0.endTime, value: $0.value) }
    default:
      return try await fetchRawQuantityData(
        type: healthKitIdentifier(for: dataType),
        dataType: dataType,
        startDate: startDate,
        endDate: endDate
      ).map { point in
        let value = dataType == .oxygenSaturation ? point.value * 100 : point.value
        return NativeHealthDataPoint(dataType: point.dataType, time: point.endTime, value: value)
      }
    }
  }

  func fetchRawData(
    for dataType: NativeHealthDataType,
    startDate: Date,
    endDate: Date
  ) async throws -> [NativeHealthRawDataPoint] {
    switch dataType {
    case .sleep:
      return []
    case .irregularHeartRhythm:
      return try await fetchRawCategoryData(
        type: healthKitIdentifier(for: dataType),
        dataType: dataType,
        startDate: startDate,
        endDate: endDate
      )
    default:
      let points = try await fetchRawQuantityData(
        type: healthKitIdentifier(for: dataType),
        dataType: dataType,
        startDate: startDate,
        endDate: endDate
      )
      guard dataType == .oxygenSaturation else {
        return points
      }
      return points.map {
        NativeHealthRawDataPoint(
          dataType: $0.dataType,
          startTime: $0.startTime,
          endTime: $0.endTime,
          value: $0.value * 100,
          isMotionLike: nil
        )
      }
    }
  }

  func fetchSleepData(startDate: Date, endDate: Date) async throws -> [NativeSleepInterval] {
    try await fetchSleepIntervals(startDate: startDate, endDate: endDate)
  }

  func fetchActivityTargetData(startDate: Date, endDate: Date) async throws -> NativeActivityTarget? {
    try await fetchActivityTargetDataList(startDate: startDate, endDate: endDate).last
  }

  func fetchActivityTargetDataList(startDate: Date, endDate: Date) async throws -> [NativeActivityTarget] {
    try await fetchActivitySummaryRows(startDate: startDate, endDate: endDate)
      .map { row in
        NativeActivityTarget(
          healthValueTimestamp: row.day.timeIntervalSince1970,
          move: row.activeEnergyBurnedGoal.map(Int.init),
          stand: row.appleStandHoursGoal.map(Int.init),
          activityMoveMode: nil,
          activeEnergyBurned: row.activeEnergyBurned,
          activeEnergyBurnedGoal: row.activeEnergyBurnedGoal,
          appleMoveTime: row.appleMoveTime.map { $0 * 60 },
          appleMoveTimeGoal: row.appleMoveTimeGoal.map { $0 * 60 },
          appleExerciseTime: row.appleExerciseTime.map { $0 * 60 },
          exerciseTimeGoal: row.appleExerciseTimeGoal.map { $0 * 60 },
          appleStandHours: row.appleStandHours,
          standHoursGoal: row.appleStandHoursGoal
        )
      }
  }

  func fetchWorkoutDataList(startDate: Date, endDate: Date) async throws -> [NativeWorkoutInterval] {
    let endDateText = Self.makeDateFormatter().string(from: endDate)
    let startDateText = Self.makeDateFormatter().string(from: startDate)

    return try await Task.detached(priority: .utility) { [databaseURL] in
      let dateFormatter = Self.makeDateFormatter()
      let database = try Self.openDatabase(at: databaseURL)
      defer { sqlite3_close(database) }

      let sql = """
      SELECT workout_activity_type, start_date, end_date
      FROM workouts
      WHERE start_date <= ?
        AND end_date >= ?
      ORDER BY end_date ASC
      """
      return try Self.readRows(
        database: database,
        sql: sql,
        values: [endDateText, startDateText]
      ) { statement in
        guard
          let workoutTypeText = Self.textColumn(statement, index: 0),
          let startText = Self.textColumn(statement, index: 1),
          let endText = Self.textColumn(statement, index: 2),
          let start = dateFormatter.date(from: startText),
          let end = dateFormatter.date(from: endText)
        else {
          return nil
        }
        return NativeWorkoutInterval(
          workoutType: Self.workoutActivityTypeRawValue(for: workoutTypeText),
          startTime: start.timeIntervalSince1970,
          endTime: end.timeIntervalSince1970
        )
      }
    }.value
  }

  private func fetchRawQuantityData(
    type: String,
    dataType: NativeHealthDataType,
    startDate: Date,
    endDate: Date
  ) async throws -> [NativeHealthRawDataPoint] {
    let records: [NativeHealthRawDataPoint] = try await fetchRecords(
      type: type,
      startDate: startDate,
      endDate: endDate,
      columns: "value, start_date, end_date"
    ) { statement, dateFormatter in
      guard
        let valueText = Self.textColumn(statement, index: 0),
        let value = Double(valueText),
        let startText = Self.textColumn(statement, index: 1),
        let endText = Self.textColumn(statement, index: 2),
        let start = dateFormatter.date(from: startText),
        let end = dateFormatter.date(from: endText)
      else {
        return nil
      }
      return NativeHealthRawDataPoint(
        dataType: dataType,
        startTime: start.timeIntervalSince1970,
        endTime: end.timeIntervalSince1970,
        value: value,
        isMotionLike: nil
      )
    }
    return records
  }

  private func fetchRawCategoryData(
    type: String,
    dataType: NativeHealthDataType,
    startDate: Date,
    endDate: Date
  ) async throws -> [NativeHealthRawDataPoint] {
    try await fetchRecords(
      type: type,
      startDate: startDate,
      endDate: endDate,
      columns: "value, start_date, end_date"
    ) { statement, dateFormatter in
      guard
        let startText = Self.textColumn(statement, index: 1),
        let endText = Self.textColumn(statement, index: 2),
        let start = dateFormatter.date(from: startText),
        let end = dateFormatter.date(from: endText)
      else {
        return nil
      }
      return NativeHealthRawDataPoint(
        dataType: dataType,
        startTime: start.timeIntervalSince1970,
        endTime: end.timeIntervalSince1970,
        value: Double(Self.textColumn(statement, index: 0) ?? "") ?? 1,
        isMotionLike: nil
      )
    }
  }

  private func fetchSleepIntervals(startDate: Date, endDate: Date) async throws -> [NativeSleepInterval] {
    try await fetchRecords(
      type: "HKCategoryTypeIdentifierSleepAnalysis",
      startDate: startDate,
      endDate: endDate,
      columns: "value, start_date, end_date"
    ) { statement, dateFormatter in
      guard
        let startText = Self.textColumn(statement, index: 1),
        let endText = Self.textColumn(statement, index: 2),
        let start = dateFormatter.date(from: startText),
        let end = dateFormatter.date(from: endText)
      else {
        return nil
      }
      return NativeSleepInterval(
        dataType: Int(Double(Self.textColumn(statement, index: 0) ?? "") ?? 0),
        fromTime: start.timeIntervalSince1970,
        toTime: end.timeIntervalSince1970
      )
    }
  }

  private func fetchRecords<T>(
    type: String,
    startDate: Date,
    endDate: Date,
    columns: String,
    transform: @escaping (OpaquePointer?, DateFormatter) -> T?
  ) async throws -> [T] {
    let endDateText = Self.makeDateFormatter().string(from: endDate)
    let startDateText = Self.makeDateFormatter().string(from: startDate)

    return try await Task.detached(priority: .utility) { [databaseURL] in
      let dateFormatter = Self.makeDateFormatter()
      let database = try Self.openDatabase(at: databaseURL)
      defer { sqlite3_close(database) }

      let sql = """
      SELECT \(columns)
      FROM records
      WHERE type = ?
        AND start_date <= ?
        AND end_date >= ?
      ORDER BY end_date ASC
      """
      return try Self.readRows(
        database: database,
        sql: sql,
        values: [type, endDateText, startDateText]
      ) { statement in
        transform(statement, dateFormatter)
      }
    }.value
  }

  private func fetchActivitySummaryData(
    dataType: NativeHealthDataType,
    valueColumn: String,
    multiplier: Double,
    startDate: Date,
    endDate: Date
  ) async throws -> [NativeHealthDataPoint] {
    try await fetchActivitySummaryRows(startDate: startDate, endDate: endDate)
      .compactMap { row in
        guard let value = row.value(for: valueColumn) else {
          return nil
        }
        return NativeHealthDataPoint(
          dataType: dataType,
          time: Self.uploadTimeForDailyPoint(day: row.day, endDate: endDate).timeIntervalSince1970,
          value: value * multiplier
        )
      }
  }

  private func fetchActivitySummaryRows(
    startDate: Date,
    endDate: Date
  ) async throws -> [LocalActivitySummaryRow] {
    let startDayText = Self.makeDayFormatter().string(from: Calendar.current.startOfDay(for: startDate))
    let endDayText = Self.makeDayFormatter().string(from: Calendar.current.startOfDay(for: endDate))

    return try await Task.detached(priority: .utility) { [databaseURL] in
      let dayFormatter = Self.makeDayFormatter()
      let database = try Self.openDatabase(at: databaseURL)
      defer { sqlite3_close(database) }

      let sql = """
      SELECT date_components,
             active_energy_burned,
             active_energy_burned_goal,
             apple_move_time,
             apple_move_time_goal,
             apple_exercise_time,
             apple_exercise_time_goal,
             apple_stand_hours,
             apple_stand_hours_goal
      FROM activity_summaries
      WHERE date_components >= ?
        AND date_components <= ?
      ORDER BY date_components ASC
      """
      return try Self.readRows(database: database, sql: sql, values: [startDayText, endDayText]) { statement in
        guard
          let dayText = Self.textColumn(statement, index: 0),
          let day = dayFormatter.date(from: dayText)
        else {
          return nil
        }
        return LocalActivitySummaryRow(
          day: day,
          activeEnergyBurned: Self.doubleColumn(statement, index: 1),
          activeEnergyBurnedGoal: Self.doubleColumn(statement, index: 2),
          appleMoveTime: Self.doubleColumn(statement, index: 3),
          appleMoveTimeGoal: Self.doubleColumn(statement, index: 4),
          appleExerciseTime: Self.doubleColumn(statement, index: 5),
          appleExerciseTimeGoal: Self.doubleColumn(statement, index: 6),
          appleStandHours: Self.doubleColumn(statement, index: 7),
          appleStandHoursGoal: Self.doubleColumn(statement, index: 8)
        )
      }
    }.value
  }

  private func healthKitIdentifier(for dataType: NativeHealthDataType) -> String {
    switch dataType {
    case .hrv: return "HKQuantityTypeIdentifierHeartRateVariabilitySDNN"
    case .heartRate, .sleepingHeartRate: return "HKQuantityTypeIdentifierHeartRate"
    case .oxygenSaturation: return "HKQuantityTypeIdentifierOxygenSaturation"
    case .activeEnergy: return "HKQuantityTypeIdentifierActiveEnergyBurned"
    case .exercise: return "HKQuantityTypeIdentifierAppleExerciseTime"
    case .stand: return "HKQuantityTypeIdentifierAppleStandTime"
    case .steps: return "HKQuantityTypeIdentifierStepCount"
    case .walkingHeartRate: return "HKQuantityTypeIdentifierWalkingHeartRateAverage"
    case .restingHeartRate: return "HKQuantityTypeIdentifierRestingHeartRate"
    case .sleepingWristTemperature: return "HKQuantityTypeIdentifierAppleSleepingWristTemperature"
    case .respiratoryRate: return "HKQuantityTypeIdentifierRespiratoryRate"
    case .irregularHeartRhythm: return "HKCategoryTypeIdentifierIrregularHeartRhythmEvent"
    case .sleep: return "HKCategoryTypeIdentifierSleepAnalysis"
    }
  }

  private static func defaultDatabaseURL() -> URL? {
    let bundle = Bundle.main
    if let url = bundle.url(forResource: "export", withExtension: "sqlite") {
      return url
    }
    let sourceURL = URL(fileURLWithPath: #filePath)
      .deletingLastPathComponent()
      .appendingPathComponent("export.sqlite")
    if FileManager.default.fileExists(atPath: sourceURL.path) {
      return sourceURL
    }
    return nil
  }

  private nonisolated static func makeDateFormatter() -> DateFormatter {
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
    return formatter
  }

  private nonisolated static func makeDayFormatter() -> DateFormatter {
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.dateFormat = "yyyy-MM-dd"
    return formatter
  }

  private nonisolated static func uploadTimeForDailyPoint(day: Date, endDate: Date) -> Date {
    let calendar = Calendar.current
    let start = calendar.startOfDay(for: day)
    let nextDay = calendar.date(byAdding: .day, value: 1, to: start) ?? endDate
    return min(nextDay.addingTimeInterval(-1), endDate)
  }

  private nonisolated static func workoutActivityTypeRawValue(for identifier: String) -> Int {
    if let rawValue = Int(identifier) {
      return rawValue
    }
    if let type = workoutActivityTypeByIdentifier[identifier] {
      return Int(type.rawValue)
    }
    return 0
  }

  private nonisolated static let workoutActivityTypeByIdentifier: [String: HKWorkoutActivityType] = [
    "HKWorkoutActivityTypeAmericanFootball": .americanFootball,
    "HKWorkoutActivityTypeArchery": .archery,
    "HKWorkoutActivityTypeAustralianFootball": .australianFootball,
    "HKWorkoutActivityTypeBadminton": .badminton,
    "HKWorkoutActivityTypeBaseball": .baseball,
    "HKWorkoutActivityTypeBasketball": .basketball,
    "HKWorkoutActivityTypeBowling": .bowling,
    "HKWorkoutActivityTypeBoxing": .boxing,
    "HKWorkoutActivityTypeClimbing": .climbing,
    "HKWorkoutActivityTypeCricket": .cricket,
    "HKWorkoutActivityTypeCrossTraining": .crossTraining,
    "HKWorkoutActivityTypeCurling": .curling,
    "HKWorkoutActivityTypeCycling": .cycling,
    "HKWorkoutActivityTypeDance": .dance,
    "HKWorkoutActivityTypeDanceInspiredTraining": .danceInspiredTraining,
    "HKWorkoutActivityTypeElliptical": .elliptical,
    "HKWorkoutActivityTypeEquestrianSports": .equestrianSports,
    "HKWorkoutActivityTypeFencing": .fencing,
    "HKWorkoutActivityTypeFishing": .fishing,
    "HKWorkoutActivityTypeFunctionalStrengthTraining": .functionalStrengthTraining,
    "HKWorkoutActivityTypeGolf": .golf,
    "HKWorkoutActivityTypeGymnastics": .gymnastics,
    "HKWorkoutActivityTypeHandball": .handball,
    "HKWorkoutActivityTypeHiking": .hiking,
    "HKWorkoutActivityTypeHockey": .hockey,
    "HKWorkoutActivityTypeHunting": .hunting,
    "HKWorkoutActivityTypeLacrosse": .lacrosse,
    "HKWorkoutActivityTypeMartialArts": .martialArts,
    "HKWorkoutActivityTypeMindAndBody": .mindAndBody,
    "HKWorkoutActivityTypeMixedMetabolicCardioTraining": .mixedMetabolicCardioTraining,
    "HKWorkoutActivityTypePaddleSports": .paddleSports,
    "HKWorkoutActivityTypePlay": .play,
    "HKWorkoutActivityTypePreparationAndRecovery": .preparationAndRecovery,
    "HKWorkoutActivityTypeRacquetball": .racquetball,
    "HKWorkoutActivityTypeRowing": .rowing,
    "HKWorkoutActivityTypeRugby": .rugby,
    "HKWorkoutActivityTypeRunning": .running,
    "HKWorkoutActivityTypeSailing": .sailing,
    "HKWorkoutActivityTypeSkatingSports": .skatingSports,
    "HKWorkoutActivityTypeSnowSports": .snowSports,
    "HKWorkoutActivityTypeSoccer": .soccer,
    "HKWorkoutActivityTypeSoftball": .softball,
    "HKWorkoutActivityTypeSquash": .squash,
    "HKWorkoutActivityTypeStairClimbing": .stairClimbing,
    "HKWorkoutActivityTypeSurfingSports": .surfingSports,
    "HKWorkoutActivityTypeSwimming": .swimming,
    "HKWorkoutActivityTypeTableTennis": .tableTennis,
    "HKWorkoutActivityTypeTennis": .tennis,
    "HKWorkoutActivityTypeTrackAndField": .trackAndField,
    "HKWorkoutActivityTypeTraditionalStrengthTraining": .traditionalStrengthTraining,
    "HKWorkoutActivityTypeVolleyball": .volleyball,
    "HKWorkoutActivityTypeWalking": .walking,
    "HKWorkoutActivityTypeWaterFitness": .waterFitness,
    "HKWorkoutActivityTypeWaterPolo": .waterPolo,
    "HKWorkoutActivityTypeWaterSports": .waterSports,
    "HKWorkoutActivityTypeWrestling": .wrestling,
    "HKWorkoutActivityTypeYoga": .yoga,
    "HKWorkoutActivityTypeBarre": .barre,
    "HKWorkoutActivityTypeCoreTraining": .coreTraining,
    "HKWorkoutActivityTypeCrossCountrySkiing": .crossCountrySkiing,
    "HKWorkoutActivityTypeDownhillSkiing": .downhillSkiing,
    "HKWorkoutActivityTypeFlexibility": .flexibility,
    "HKWorkoutActivityTypeHighIntensityIntervalTraining": .highIntensityIntervalTraining,
    "HKWorkoutActivityTypeJumpRope": .jumpRope,
    "HKWorkoutActivityTypeKickboxing": .kickboxing,
    "HKWorkoutActivityTypePilates": .pilates,
    "HKWorkoutActivityTypeSnowboarding": .snowboarding,
    "HKWorkoutActivityTypeStairs": .stairs,
    "HKWorkoutActivityTypeStepTraining": .stepTraining,
    "HKWorkoutActivityTypeWheelchairWalkPace": .wheelchairWalkPace,
    "HKWorkoutActivityTypeWheelchairRunPace": .wheelchairRunPace,
    "HKWorkoutActivityTypeTaiChi": .taiChi,
    "HKWorkoutActivityTypeMixedCardio": .mixedCardio,
    "HKWorkoutActivityTypeHandCycling": .handCycling,
    "HKWorkoutActivityTypeDiscSports": .discSports,
    "HKWorkoutActivityTypeFitnessGaming": .fitnessGaming,
    "HKWorkoutActivityTypeCardioDance": .cardioDance,
    "HKWorkoutActivityTypeSocialDance": .socialDance,
    "HKWorkoutActivityTypePickleball": .pickleball,
    "HKWorkoutActivityTypeCooldown": .cooldown,
    "HKWorkoutActivityTypeSwimBikeRun": .swimBikeRun,
    "HKWorkoutActivityTypeTransition": .transition,
    "HKWorkoutActivityTypeUnderwaterDiving": .underwaterDiving,
    "HKWorkoutActivityTypeOther": .other,
  ]

  private nonisolated static func openDatabase(at url: URL) throws -> OpaquePointer? {
    var database: OpaquePointer?
    let uri = url.absoluteString + "?immutable=1"
    let flags = SQLITE_OPEN_READONLY | SQLITE_OPEN_URI
    guard sqlite3_open_v2(uri, &database, flags, nil) == SQLITE_OK else {
      let message = database.map { String(cString: sqlite3_errmsg($0)) } ?? "unknown"
      sqlite3_close(database)
      throw LocalHealthKitSQLiteError.databaseOpenFailed("\(message), path=\(url.path)")
    }
    return database
  }

  private nonisolated static func readRows<T>(
    database: OpaquePointer?,
    sql: String,
    values: [String],
    transform: (OpaquePointer?) -> T?
  ) throws -> [T] {
    var statement: OpaquePointer?
    guard sqlite3_prepare_v2(database, sql, -1, &statement, nil) == SQLITE_OK else {
      throw LocalHealthKitSQLiteError.queryFailed(String(cString: sqlite3_errmsg(database)))
    }
    defer { sqlite3_finalize(statement) }

    let transient = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
    for (index, value) in values.enumerated() {
      sqlite3_bind_text(statement, Int32(index + 1), value, -1, transient)
    }

    var rows: [T] = []
    while true {
      let step = sqlite3_step(statement)
      if step == SQLITE_ROW {
        if let row = transform(statement) {
          rows.append(row)
        }
      } else if step == SQLITE_DONE {
        return rows
      } else {
        throw LocalHealthKitSQLiteError.queryFailed(String(cString: sqlite3_errmsg(database)))
      }
    }
  }

  private nonisolated static func textColumn(_ statement: OpaquePointer?, index: Int32) -> String? {
    guard let text = sqlite3_column_text(statement, index) else {
      return nil
    }
    return String(cString: text)
  }

  private nonisolated static func doubleColumn(_ statement: OpaquePointer?, index: Int32) -> Double? {
    guard let text = textColumn(statement, index: index) else {
      return nil
    }
    return Double(text)
  }
}

private struct LocalActivitySummaryRow {
  let day: Date
  let activeEnergyBurned: Double?
  let activeEnergyBurnedGoal: Double?
  let appleMoveTime: Double?
  let appleMoveTimeGoal: Double?
  let appleExerciseTime: Double?
  let appleExerciseTimeGoal: Double?
  let appleStandHours: Double?
  let appleStandHoursGoal: Double?

  func value(for column: String) -> Double? {
    switch column {
    case "active_energy_burned":
      return activeEnergyBurned
    case "apple_exercise_time":
      return appleExerciseTime
    case "apple_stand_hours":
      return appleStandHours
    default:
      return nil
    }
  }
}