-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathCloudKit+StructuredQueries.swift
More file actions
380 lines (346 loc) · 12.8 KB
/
CloudKit+StructuredQueries.swift
File metadata and controls
380 lines (346 loc) · 12.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
#if canImport(CloudKit)
import CloudKit
import CryptoKit
import StructuredQueriesCore
extension CKRecord {
public typealias _AllFieldsRepresentation = SQLiteData._AllFieldsRepresentation<CKRecord>
public typealias SystemFieldsRepresentation = _SystemFieldsRepresentation<CKRecord>
}
extension CKShare {
public typealias _AllFieldsRepresentation = SQLiteData._AllFieldsRepresentation<CKShare>
public typealias SystemFieldsRepresentation = _SystemFieldsRepresentation<CKShare>
}
extension Optional where Wrapped: CKRecord {
public typealias _AllFieldsRepresentation = SQLiteData._AllFieldsRepresentation<Wrapped>?
public typealias SystemFieldsRepresentation = _SystemFieldsRepresentation<Wrapped>?
}
public struct _SystemFieldsRepresentation<Record: CKRecord>: QueryBindable, QueryRepresentable {
public let queryOutput: Record
public var queryBinding: QueryBinding {
let archiver = NSKeyedArchiver(requiringSecureCoding: true)
queryOutput.encodeSystemFields(with: archiver)
if isTesting {
archiver.encode(queryOutput._recordChangeTag, forKey: "_recordChangeTag")
}
return archiver.encodedData.queryBinding
}
public init(queryOutput: Record) {
self.queryOutput = queryOutput
}
public init?(queryBinding: QueryBinding) {
guard case .blob(let bytes) = queryBinding else { return nil }
try? self.init(data: Data(bytes))
}
public init(decoder: inout some StructuredQueriesCore.QueryDecoder) throws {
try self.init(data: try Data(decoder: &decoder))
}
private init(data: Data) throws {
let coder = try NSKeyedUnarchiver(forReadingFrom: data)
coder.requiresSecureCoding = true
guard let queryOutput = Record(coder: coder) else {
throw DecodingError()
}
if isTesting {
queryOutput._recordChangeTag =
coder
.decodeObject(of: NSString.self, forKey: "_recordChangeTag") as? String
}
self.init(queryOutput: queryOutput)
}
private struct DecodingError: Error {}
}
public struct _AllFieldsRepresentation<Record: CKRecord>: QueryBindable, QueryRepresentable {
public let queryOutput: Record
public var queryBinding: QueryBinding {
let archiver = NSKeyedArchiver(requiringSecureCoding: true)
queryOutput.encode(with: archiver)
if isTesting {
archiver.encode(queryOutput._recordChangeTag, forKey: "_recordChangeTag")
}
return archiver.encodedData.queryBinding
}
public init(queryOutput: Record) {
self.queryOutput = queryOutput
}
public init?(queryBinding: QueryBinding) {
guard case .blob(let bytes) = queryBinding else { return nil }
try? self.init(data: Data(bytes))
}
public init(decoder: inout some StructuredQueriesCore.QueryDecoder) throws {
try self.init(data: try Data(decoder: &decoder))
}
private init(data: Data) throws {
let coder = try NSKeyedUnarchiver(forReadingFrom: data)
coder.requiresSecureCoding = true
guard let queryOutput = Record(coder: coder) else {
throw DecodingError()
}
if isTesting {
queryOutput._recordChangeTag =
coder
.decodeObject(of: NSString.self, forKey: "_recordChangeTag") as? String
}
self.init(queryOutput: queryOutput)
}
private struct DecodingError: Error {}
}
extension CKDatabase.Scope {
public struct RawValueRepresentation: QueryBindable, QueryRepresentable {
public let queryOutput: CKDatabase.Scope
public var queryBinding: QueryBinding {
queryOutput.rawValue.queryBinding
}
public init(queryOutput: CKDatabase.Scope) {
self.queryOutput = queryOutput
}
public init?(queryBinding: QueryBinding) {
guard case .int(let rawValue) = queryBinding else { return nil }
try? self.init(rawValue: Int(rawValue))
}
public init(decoder: inout some QueryDecoder) throws {
try self.init(rawValue: Int(decoder: &decoder))
}
private init(rawValue: Int) throws {
guard let queryOutput = CKDatabase.Scope(rawValue: rawValue) else {
throw DecodingError()
}
self.init(queryOutput: queryOutput)
}
private struct DecodingError: Error {}
}
}
@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
extension CKRecordKeyValueSetting {
package subscript(at key: String) -> Int64 {
get {
self["\(CKRecord.userModificationTimeKey)_\(key)"] as? Int64 ?? -1
}
set {
self["\(CKRecord.userModificationTimeKey)_\(key)"] = max(self[at: key], newValue)
}
}
fileprivate subscript(hash key: String) -> Data? {
get { self["\(key)_hash"] as? Data }
set { self["\(key)_hash"] = newValue }
}
}
@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
extension CKRecord {
@discardableResult
package func setValue(
_ newValue: some CKRecordValueProtocol & Equatable,
forKey key: CKRecord.FieldKey,
at userModificationTime: Int64
) -> Bool {
guard
encryptedValues[at: key] <= userModificationTime,
encryptedValues[key] != newValue
else { return false }
encryptedValues[key] = newValue
encryptedValues[at: key] = userModificationTime
self.userModificationTime = userModificationTime
return true
}
@discardableResult
package func setAsset(
_ newValue: CKAsset,
forKey key: CKRecord.FieldKey,
at userModificationTime: Int64
) -> Bool {
@Dependency(\.dataManager) var dataManager
guard
let fileURL = newValue.fileURL,
let hash = dataManager.sha256(of: fileURL)
else { return false }
guard
encryptedValues[at: key] <= userModificationTime,
encryptedValues[hash: key] != hash
else { return false }
self[key] = newValue
encryptedValues[hash: key] = hash
encryptedValues[at: key] = userModificationTime
self.userModificationTime = userModificationTime
return true
}
@discardableResult
package func setValue(
_ newValue: [UInt8],
forKey key: CKRecord.FieldKey,
at userModificationTime: Int64
) -> Bool {
guard encryptedValues[at: key] <= userModificationTime
else { return false }
@Dependency(\.dataManager) var dataManager
let hash = newValue.sha256
let fileURL = dataManager.temporaryDirectory.appending(
component:
hash
.compactMap { String(format: "%02hhx", $0) }
.joined()
)
let asset = CKAsset(fileURL: fileURL)
return withErrorReporting(.sqliteDataCloudKitFailure) {
try dataManager.save(Data(newValue), to: fileURL)
self[key] = asset
encryptedValues[at: key] = userModificationTime
encryptedValues[hash: key] = hash
self.userModificationTime = userModificationTime
return true
}
?? false
}
@discardableResult
package func removeValue(
forKey key: CKRecord.FieldKey,
at userModificationTime: Int64
) -> Bool {
guard encryptedValues[at: key] <= userModificationTime
else {
return false
}
if encryptedValues[key] != nil {
encryptedValues[key] = nil
encryptedValues[at: key] = userModificationTime
self.userModificationTime = userModificationTime
return true
} else if self[key] != nil {
self[key] = nil
encryptedValues[at: key] = userModificationTime
self.userModificationTime = userModificationTime
return true
}
return false
}
func update<T: PrimaryKeyedTable>(with row: T, userModificationTime: Int64) {
for column in T.TableColumns.writableColumns {
func open<Root, Value>(_ column: some WritableTableColumnExpression<Root, Value>) {
let keyPath = column.keyPath as! KeyPath<T, Value.QueryOutput>
let column = column as! any WritableTableColumnExpression<T, Value>
let value = Value(queryOutput: row[keyPath: keyPath])
switch value.queryBinding {
case .blob(let value):
setValue(value, forKey: column.name, at: userModificationTime)
case .bool(let value):
setValue(value, forKey: column.name, at: userModificationTime)
case .double(let value):
setValue(value, forKey: column.name, at: userModificationTime)
case .date(let value):
setValue(value, forKey: column.name, at: userModificationTime)
case .int(let value):
setValue(value, forKey: column.name, at: userModificationTime)
case .null:
removeValue(forKey: column.name, at: userModificationTime)
case .text(let value):
setValue(value, forKey: column.name, at: userModificationTime)
case .uint(let value):
setValue(value, forKey: column.name, at: userModificationTime)
case .uuid(let value):
setValue(
value.uuidString.lowercased(),
forKey: column.name,
at: userModificationTime
)
case .invalid(let error):
reportIssue(error)
}
}
open(column)
}
}
func update<T: PrimaryKeyedTable>(
with other: CKRecord,
row: T,
columnNames: inout [String],
parentForeignKey: ForeignKey?
) {
typealias EquatableCKRecordValueProtocol = CKRecordValueProtocol & Equatable
self.userModificationTime = other.userModificationTime
for column in T.TableColumns.writableColumns {
func open<Root, Value>(_ column: some WritableTableColumnExpression<Root, Value>) {
let key = column.name
let keyPath = column.keyPath as! KeyPath<T, Value.QueryOutput>
let didSet: Bool
if let value = other[key] as? CKAsset {
didSet = setAsset(value, forKey: key, at: other.encryptedValues[at: key])
} else if let value = other.encryptedValues[key] as? any EquatableCKRecordValueProtocol {
didSet = setValue(value, forKey: key, at: other.encryptedValues[at: key])
} else if other.encryptedValues[key] == nil {
didSet = removeValue(forKey: key, at: other.encryptedValues[at: key])
} else {
didSet = false
}
/// The row value has been modified more recently than the last known record.
var isRowValueModified: Bool {
switch Value(queryOutput: row[keyPath: keyPath]).queryBinding {
case .blob(let value):
return other.encryptedValues[hash: key] != value.sha256
case .bool(let value):
return other.encryptedValues[key] != value
case .double(let value):
return other.encryptedValues[key] != value
case .date(let value):
return other.encryptedValues[key] != value
case .int(let value):
return other.encryptedValues[key] != value
case .null:
return other.encryptedValues[key] != nil
case .text(let value):
return other.encryptedValues[key] != value
case .uint(let value):
return other.encryptedValues[key] != value
case .uuid(let value):
return other.encryptedValues[key] != value.uuidString.lowercased()
case .invalid(let error):
reportIssue(error)
return false
}
}
if didSet || isRowValueModified {
columnNames.removeAll(where: { $0 == key })
if didSet, let parentForeignKey, key == parentForeignKey.from {
self.parent = other.parent
}
}
}
open(column)
}
}
package var userModificationTime: Int64 {
get { encryptedValues[Self.userModificationTimeKey] as? Int64 ?? -1 }
set {
encryptedValues[Self.userModificationTimeKey] = Swift.max(userModificationTime, newValue)
}
}
package static let userModificationTimeKey =
"\(String.sqliteDataCloudKitSchemaName)_userModificationTime"
}
extension __CKRecordObjCValue {
var queryFragment: QueryFragment {
if let value = self as? Int64 {
return value.queryFragment
} else if let value = self as? Double {
return value.queryFragment
} else if let value = self as? String {
return value.queryFragment
} else if let value = self as? Data {
return value.queryFragment
} else if let value = self as? Date {
return value.queryFragment
} else {
return "\(.invalid(Unbindable()))"
}
}
}
private struct Unbindable: Error {}
extension CKRecord {
package var _recordChangeTag: String? {
get { self[#function] }
set { self[#function] = newValue }
}
}
extension DataProtocol {
fileprivate var sha256: Data {
Data(SHA256.hash(data: self))
}
}
#endif