Skip to content

Commit

Permalink
orphaned sample adoption, for dealing with cases where i screw up the…
Browse files Browse the repository at this point in the history
… db during development #11
  • Loading branch information
sobri909 committed May 9, 2018
1 parent a112de6 commit ee4852a
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 6 deletions.
8 changes: 8 additions & 0 deletions LocoKit/Base/Helpers/MiscTools.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,11 @@ public extension Comparable {

}

public extension UUID {

public var shortString: String {
return String(uuidString.split(separator: "-")[0])
}

}

37 changes: 31 additions & 6 deletions LocoKit/LocalStore/PersistentTimelineStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ open class PersistentTimelineStore: TimelineStore {
migrateDatabase()
pool.add(transactionObserver: itemsObserver)
pool.setupMemoryManagement(in: UIApplication.shared)

adoptOrphanedSamples()
}

// MARK: - Adding Items / Samples to the store
Expand Down Expand Up @@ -159,7 +161,7 @@ open class PersistentTimelineStore: TimelineStore {
}
}

// MARK: Counting
// MARK: - Counting

public func countItems(where query: String, arguments: StatementArguments? = nil) -> Int {
return try! pool.read { db in
Expand All @@ -173,7 +175,7 @@ open class PersistentTimelineStore: TimelineStore {
}
}

// MARK: Saving
// MARK: - Saving

public func save(_ object: PersistentObject, immediate: Bool) {
mutex.sync {
Expand Down Expand Up @@ -224,16 +226,39 @@ open class PersistentTimelineStore: TimelineStore {
}
}

// MARK: Database housekeeping
// MARK: - Database housekeeping

open func hardDeleteSoftDeletedItems() {
let deadline = Date(timeIntervalSinceNow: -keepDeletedItemsFor)
try! pool.write { db in
try db.execute("DELETE FROM TimelineItem WHERE deleted = 1 AND endDate < ?", arguments: [deadline])
do {
try pool.write { db in
try db.execute("DELETE FROM TimelineItem WHERE deleted = 1 AND endDate < ?", arguments: [deadline])
}
} catch {
os_log("%@", error.localizedDescription)
}
}

private func adoptOrphanedSamples() {
process {
let orphans = self.samples(where: "timelineItemId IS NULL ORDER BY date DESC")

if orphans.count > 0 {
os_log("Found orphaned samples: %d", type: .error, orphans.count)
}

for orphan in orphans where orphan.timelineItem == nil {
if let item = self.item(where: "deleted = 0 AND startDate <= ? AND endDate >= ?",
arguments: [orphan.date, orphan.date]) {
os_log("ADOPTED AN ORPHAN (item: %@, sample: %@)", type: .error, item.itemId.shortString,
orphan.sampleId.shortString)
item.add(orphan)
}
}
}
}

// MARK: Database creation and migrations
// MARK: - Database creation and migrations

public var migrator = DatabaseMigrator()

Expand Down

0 comments on commit ee4852a

Please sign in to comment.