-
-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathQueryHistoryStorage.swift
More file actions
69 lines (59 loc) · 2.15 KB
/
QueryHistoryStorage.swift
File metadata and controls
69 lines (59 loc) · 2.15 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
import Foundation
struct QueryHistoryItem: Identifiable, Codable, Hashable {
let id: UUID
let query: String
let timestamp: Date
let connectionId: UUID
init(id: UUID = UUID(), query: String, timestamp: Date = Date(), connectionId: UUID) {
self.id = id
self.query = query
self.timestamp = timestamp
self.connectionId = connectionId
}
}
struct QueryHistoryStorage {
private static let maxEntries = 200
private var fileURL: URL? {
guard let dir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else {
return nil
}
let appDir = dir.appendingPathComponent("TableProMobile", isDirectory: true)
try? FileManager.default.createDirectory(at: appDir, withIntermediateDirectories: true)
return appDir.appendingPathComponent("query-history.json")
}
func save(_ item: QueryHistoryItem) {
var items = loadAll()
if items.last?.query == item.query && items.last?.connectionId == item.connectionId {
return
}
items.append(item)
if items.count > Self.maxEntries {
items.removeFirst(items.count - Self.maxEntries)
}
writeAll(items)
}
func loadAll() -> [QueryHistoryItem] {
guard let fileURL, let data = try? Data(contentsOf: fileURL),
let items = try? JSONDecoder().decode([QueryHistoryItem].self, from: data) else {
return []
}
return items
}
func load(for connectionId: UUID) -> [QueryHistoryItem] {
loadAll().filter { $0.connectionId == connectionId }
}
func delete(_ id: UUID) {
var items = loadAll()
items.removeAll { $0.id == id }
writeAll(items)
}
func clearAll(for connectionId: UUID) {
var items = loadAll()
items.removeAll { $0.connectionId == connectionId }
writeAll(items)
}
private func writeAll(_ items: [QueryHistoryItem]) {
guard let fileURL, let data = try? JSONEncoder().encode(items) else { return }
try? data.write(to: fileURL, options: [.atomic, .completeFileProtection])
}
}