2 * Copyright (c) 2016 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
26 #import <XCTest/XCTest.h>
27 #import "CloudKitMockXCTest.h"
29 #import "keychain/ckks/CKKS.h"
30 #import "keychain/ckks/CKKSKey.h"
31 #import "keychain/ckks/CKKSOutgoingQueueEntry.h"
32 #import "keychain/ckks/CKKSZoneStateEntry.h"
33 #import "keychain/ckks/CKKSDeviceStateEntry.h"
34 #import "keychain/ckks/CKKSRateLimiter.h"
36 #include <securityd/SecItemServer.h>
38 @interface CloudKitKeychainSQLTests : CloudKitMockXCTest
41 @implementation CloudKitKeychainSQLTests
54 SecCKKSResetSyncing();
57 - (void)addTestZoneEntries {
58 CKKSOutgoingQueueEntry* one = [[CKKSOutgoingQueueEntry alloc] initWithCKKSItem:
59 [[CKKSItem alloc] initWithUUID:[[NSUUID UUID] UUIDString]
60 parentKeyUUID:[[NSUUID UUID] UUIDString]
61 zoneID:self.testZoneID
62 encItem:[@"nonsense" dataUsingEncoding:NSUTF8StringEncoding]
63 wrappedkey:[[CKKSWrappedAESSIVKey alloc]initWithBase64: @"KFfL58XtugiYNoD859EjG0StfrYd6eakm0CQrgX7iO+DEo4kio3WbEeA1kctCU0GaeTGsRFpbdy4oo6jXhVu7cZqB0svhUPGq55aGnszUjI="]
66 action:SecCKKSActionAdd
67 state:SecCKKSStateError
72 CKKSOutgoingQueueEntry* two = [[CKKSOutgoingQueueEntry alloc] initWithCKKSItem:
73 [[CKKSItem alloc] initWithUUID:[[NSUUID UUID] UUIDString]
74 parentKeyUUID:[[NSUUID UUID] UUIDString]
75 zoneID:self.testZoneID
76 encItem:[@"nonsense" dataUsingEncoding:NSUTF8StringEncoding]
77 wrappedkey:[[CKKSWrappedAESSIVKey alloc]initWithBase64: @"KFfL58XtugiYNoD859EjG0StfrYd6eakm0CQrgX7iO+DEo4kio3WbEeA1kctCU0GaeTGsRFpbdy4oo6jXhVu7cZqB0svhUPGq55aGnszUjI="]
80 action:SecCKKSActionAdd
85 CKKSOutgoingQueueEntry* three = [[CKKSOutgoingQueueEntry alloc] initWithCKKSItem:
86 [[CKKSItem alloc] initWithUUID:[[NSUUID UUID] UUIDString]
87 parentKeyUUID:[[NSUUID UUID] UUIDString]
88 zoneID:self.testZoneID
89 encItem:[@"nonsense" dataUsingEncoding:NSUTF8StringEncoding]
90 wrappedkey:[[CKKSWrappedAESSIVKey alloc]initWithBase64: @"KFfL58XtugiYNoD859EjG0StfrYd6eakm0CQrgX7iO+DEo4kio3WbEeA1kctCU0GaeTGsRFpbdy4oo6jXhVu7cZqB0svhUPGq55aGnszUjI="]
93 action:SecCKKSActionModify
94 state:SecCKKSStateError
99 [one saveToDatabase:&error];
100 [two saveToDatabase: &error];
101 [three saveToDatabase: &error];
102 XCTAssertNil(error, "no error saving ZoneStateEntries to database");
105 - (void)testCKKSOutgoingQueueEntry {
106 NSString* testUUID = @"157A3171-0677-451B-9EAE-0DDC4D4315B0";
107 NSUUID* testKeyUUID = [[NSUUID alloc] init];
110 __block CFErrorRef error = NULL;
112 CKKSOutgoingQueueEntry* shouldFail = [CKKSOutgoingQueueEntry fromDatabase:testUUID state:SecCKKSStateInFlight zoneID:self.testZoneID error: &nserror];
113 XCTAssertNil(shouldFail, "Can't find a nonexisting object");
114 XCTAssertNotNil(nserror, "NSError exists when things break");
116 __weak __typeof(self) weakSelf = self;
117 kc_with_dbt(true, &error, ^bool (SecDbConnectionRef dbconn) {
118 __strong __typeof(weakSelf) strongSelf = weakSelf;
119 XCTAssertNotNil(strongSelf, "called while self still exists");
121 NSString * sql = @"insert INTO outgoingqueue (UUID, parentKeyUUID, ckzone, action, state, accessgroup, gencount, encitem, wrappedkey, encver) VALUES (?,?,?,?,?,?,?,?,?,?);";
122 SecDbPrepare(dbconn, (__bridge CFStringRef) sql, &error, ^void (sqlite3_stmt *stmt) {
123 SecDbBindText(stmt, 1, [testUUID UTF8String], strlen([testUUID UTF8String]), NULL, &error);
124 SecDbBindText(stmt, 2, [[testKeyUUID UUIDString] UTF8String], strlen([[testKeyUUID UUIDString] UTF8String]), NULL, &error);
125 SecDbBindObject(stmt, 3, (__bridge CFStringRef) weakSelf.testZoneID.zoneName, &error);
126 SecDbBindText(stmt, 4, "newitem", strlen("newitem"), NULL, &error);
127 SecDbBindText(stmt, 5, "unprocessed", strlen("unprocessed"), NULL, &error);
128 SecDbBindText(stmt, 6, "com.apple.access", strlen("com.apple.access"), NULL, &error);
129 SecDbBindText(stmt, 7, "0", strlen("0"), NULL, &error);
130 SecDbBindText(stmt, 8, "bm9uc2Vuc2UK", strlen("bm9uc2Vuc2UK"), NULL, &error);
131 SecDbBindObject(stmt, 9, CFSTR("KFfL58XtugiYNoD859EjG0StfrYd6eakm0CQrgX7iO+DEo4kio3WbEeA1kctCU0GaeTGsRFpbdy4oo6jXhVu7cZqB0svhUPGq55aGnszUjI="), &error);
132 SecDbBindText(stmt, 10, "0", strlen("0"), NULL, &error);
134 SecDbStep(dbconn, stmt, &error, ^(bool *stop) {
135 // don't do anything, I guess?
138 XCTAssertNil((__bridge NSError*)error, @"no error occurred while adding row to database");
140 CFReleaseNull(error);
142 XCTAssertNil((__bridge NSError*)error, @"no error occurred preparing sql");
144 CFReleaseNull(error);
148 // Create another oqe with different values
149 CKKSItem* baseitem = [[CKKSItem alloc] initWithUUID: [[NSUUID UUID] UUIDString]
150 parentKeyUUID:[[NSUUID UUID] UUIDString]
151 zoneID:self.testZoneID
152 encItem:[@"nonsense" dataUsingEncoding:NSUTF8StringEncoding]
153 wrappedkey:[[CKKSWrappedAESSIVKey alloc]initWithBase64: @"KFfL58XtugiYNoD859EjG0StfrYd6eakm0CQrgX7iO+DEo4kio3WbEeA1kctCU0GaeTGsRFpbdy4oo6jXhVu7cZqB0svhUPGq55aGnszUjI="]
156 CKKSOutgoingQueueEntry* other = [[CKKSOutgoingQueueEntry alloc] initWithCKKSItem:baseitem
157 action:SecCKKSActionAdd
158 state:SecCKKSStateError
159 waitUntil:[NSDate date]
160 accessGroup:@"nope"];
161 [other saveToDatabase:&nserror];
162 XCTAssertNil(nserror, "no error occurred saving to database");
164 CKKSOutgoingQueueEntry * oqe = [CKKSOutgoingQueueEntry fromDatabase:testUUID state:@"unprocessed" zoneID:self.testZoneID error: &nserror];
165 XCTAssertNil(nserror, "no error occurred creating from database");
167 XCTAssertNotNil(oqe, "load outgoing queue entry from database");
168 XCTAssertEqualObjects(oqe.state, @"unprocessed", "state matches what was in the DB");
170 oqe.item.parentKeyUUID = @"not a parent key either";
171 oqe.action = @"null";
172 oqe.state = @"savedtocloud";
173 oqe.accessgroup = @"com.evil.access";
174 oqe.item.generationCount = (NSInteger) 1;
175 oqe.item.base64encitem = @"bW9yZW5vbnNlbnNlCg==";
178 XCTAssertTrue([oqe saveToDatabase: &nserror], "saving to database");
180 CKKSOutgoingQueueEntry * oqe2 = [CKKSOutgoingQueueEntry fromDatabase:testUUID state:@"savedtocloud" zoneID:self.testZoneID error: &nserror];
181 XCTAssertNil(nserror, "no error occurred");
183 XCTAssertEqualObjects(oqe2.item.parentKeyUUID, @"not a parent key either", @"parent key uuid persisted through db save and load");
184 XCTAssertEqualObjects(oqe2.item.zoneID , self.testZoneID , @"zone id persisted through db save and load");
185 XCTAssertEqualObjects(oqe2.action , @"null" , @"action persisted through db save and load");
186 XCTAssertEqualObjects(oqe2.state , @"savedtocloud" , @"state persisted through db save and load");
187 XCTAssertEqual( oqe2.waitUntil , nil , @"no date when none given");
188 XCTAssertEqualObjects(oqe2.accessgroup , @"com.evil.access" , @"accessgroup persisted through db save and load");
189 XCTAssertEqual( oqe2.item.generationCount, (NSUInteger) 1 , @"generationCount persisted through db save and load");
190 XCTAssertEqualObjects(oqe2.item.base64encitem, @"bW9yZW5vbnNlbnNlCg==" , @"encitem persisted through db save and load");
191 XCTAssertEqual( oqe2.item.encver, 1 , @"encver persisted through db save and load");
192 XCTAssertEqualObjects([oqe2.item.wrappedkey base64WrappedKey], @"KFfL58XtugiYNoD859EjG0StfrYd6eakm0CQrgX7iO+DEo4kio3WbEeA1kctCU0GaeTGsRFpbdy4oo6jXhVu7cZqB0svhUPGq55aGnszUjI=",
193 @"wrapped key persisted through db save and load");
195 // Test 'all' methods
196 NSArray<CKKSOutgoingQueueEntry*>* oqes = [CKKSOutgoingQueueEntry all:&nserror];
197 XCTAssertNil(nserror, "no error occurred");
198 XCTAssertNotNil(oqes, "receive oqes from database");
199 XCTAssert([oqes count] == 2, "received 2 oqes from all");
201 NSArray<CKKSOutgoingQueueEntry*>* oqeswhere = [CKKSOutgoingQueueEntry allWhere: @{@"state": @"savedtocloud"} error:&nserror];
202 XCTAssertNil(nserror, "no error occurred");
203 XCTAssertNotNil(oqeswhere, "receive oqes from database");
204 XCTAssert([oqeswhere count] == 1, "received 1 oqe from allWhere");
208 [oqe2 deleteFromDatabase:&nserror];
209 XCTAssertNil(nserror, "No NSError exists when deleting existing item");
210 oqe2 = [CKKSOutgoingQueueEntry fromDatabase:testUUID state:@"savedtocloud" zoneID:self.testZoneID error: &nserror];
211 XCTAssertNil(oqe2, "Can't find a nonexisting object");
212 XCTAssertNotNil(nserror, "NSError exists when things break");
214 // Test loading other
216 CKKSOutgoingQueueEntry* other2 = [CKKSOutgoingQueueEntry fromDatabase: other.item.uuid state:SecCKKSStateError zoneID:self.testZoneID error:&nserror];
217 XCTAssertNil(nserror, "No error loading other2 from database");
218 XCTAssertNotNil(other2, "Able to re-load other.");
219 XCTAssertEqualObjects(other, other2, "loaded object is equal to object");
222 -(void)testCKKSZoneStateEntrySQL {
223 CKKSZoneStateEntry* zse = [[CKKSZoneStateEntry alloc] initWithCKZone: @"sqltest"
226 changeToken: [@"nonsense" dataUsingEncoding:NSUTF8StringEncoding]
227 lastFetch: [NSDate date]
228 encodedRateLimiter:nil];
229 zse.rateLimiter = [[CKKSRateLimiter alloc] init];
231 CKKSZoneStateEntry* zseClone = [[CKKSZoneStateEntry alloc] initWithCKZone: @"sqltest"
234 changeToken: [@"nonsense" dataUsingEncoding:NSUTF8StringEncoding]
235 lastFetch: zse.lastFetchTime
236 encodedRateLimiter:zse.encodedRateLimiter];
238 CKKSZoneStateEntry* zseDifferent = [[CKKSZoneStateEntry alloc] initWithCKZone: @"sqltest"
241 changeToken: [@"allnonsense" dataUsingEncoding:NSUTF8StringEncoding]
242 lastFetch: zse.lastFetchTime
243 encodedRateLimiter:zse.encodedRateLimiter];
244 XCTAssertEqualObjects(zse, zseClone, "CKKSZoneStateEntry isEqual of equal objects seems sane");
245 XCTAssertNotEqualObjects(zse, zseDifferent, "CKKSZoneStateEntry isEqual of nonequal objects seems sane");
247 NSError* error = nil;
248 CKKSZoneStateEntry* loaded = [CKKSZoneStateEntry tryFromDatabase: @"sqltest" error:&error];
249 XCTAssertNil(error, "No error trying to load nonexistent record");
250 XCTAssertNil(loaded, "No record saved in database");
252 [zse saveToDatabase: &error];
253 XCTAssertNil(error, "no error saving CKKSZoneStateEntry to database");
255 loaded = [CKKSZoneStateEntry tryFromDatabase: @"sqltest" error:&error];
256 XCTAssertNil(error, "No error trying to load saved record");
257 XCTAssertNotNil(loaded, "CKKSZoneStateEntry came back out of database");
259 XCTAssertEqualObjects(zse.ckzone, loaded.ckzone, "ckzone persisted through db save and load");
260 XCTAssertEqual (zse.ckzonecreated, loaded.ckzonecreated, "ckzonecreated persisted through db save and load");
261 XCTAssertEqual (zse.ckzonesubscribed, loaded.ckzonesubscribed, "ckzonesubscribed persisted through db save and load");
262 XCTAssertEqualObjects(zse.encodedChangeToken, loaded.encodedChangeToken, "encodedChangeToken persisted through db save and load");
264 XCTAssert([[NSCalendar currentCalendar] isDate:zse.lastFetchTime equalToDate: loaded.lastFetchTime toUnitGranularity:NSCalendarUnitSecond],
265 "lastFetchTime persisted through db save and load");
268 -(void)testRoundtripCKKSDeviceStateEntry {
269 // Very simple test: can these objects roundtrip through the db?
270 NSString* testUUID = @"157A3171-0677-451B-9EAE-0DDC4D4315B0";
271 CKKSDeviceStateEntry* cdse = [[CKKSDeviceStateEntry alloc] initForDevice:testUUID
273 circleStatus:kSOSCCInCircle
274 keyState:SecCKKSZoneKeyStateReady
275 currentTLKUUID:@"tlk"
276 currentClassAUUID:@"classA"
277 currentClassCUUID:@"classC"
278 zoneID:self.testZoneID
279 encodedCKRecord:nil];
280 XCTAssertNotNil(cdse, "Constructor works");
281 NSError* saveError = nil;
282 [cdse saveToDatabase:&saveError];
283 XCTAssertNil(saveError, "No error saving cdse to database");
285 NSError* loadError = nil;
286 CKKSDeviceStateEntry* loadedCDSE = [CKKSDeviceStateEntry fromDatabase:testUUID zoneID:self.testZoneID error:&loadError];
287 XCTAssertNil(loadError, "No error loading CDSE");
288 XCTAssertNotNil(loadedCDSE, "Received a CDSE back");
290 XCTAssertEqualObjects(cdse, loadedCDSE, "Roundtripping CKKSDeviceStateEntry ends up with equivalent objects");
293 // disabled, as CKKS syncing is disabled in this class.
294 // To re-enable, need to add flags CKKS syncing to perform queue actions but not automatically start queue processing operations
295 -(void)disabledtestItemAddCreatesCKKSOutgoingQueueEntry {
296 CFMutableDictionaryRef attrs;
301 NSArray* oqes = [CKKSOutgoingQueueEntry all: &error];
302 XCTAssertEqual([oqes count], 0ul, @"Nothing in outgoing queue");
303 XCTAssertNil(error, @"No error loading queue");
305 attrs = CFDictionaryCreateMutable( NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks );
306 CFDictionarySetValue( attrs, kSecClass, kSecClassGenericPassword );
307 CFDictionarySetValue( attrs, kSecAttrAccessible, kSecAttrAccessibleAlways );
308 CFDictionarySetValue( attrs, kSecAttrLabel, CFSTR( "TestLabel" ) );
309 CFDictionarySetValue( attrs, kSecAttrDescription, CFSTR( "TestDescription" ) );
310 CFDictionarySetValue( attrs, kSecAttrAccount, CFSTR( "TestAccount" ) );
311 CFDictionarySetValue( attrs, kSecAttrService, CFSTR( "TestService" ) );
312 CFDictionarySetValue( attrs, kSecAttrAccessGroup, CFSTR("com.apple.lakitu"));
313 data = CFDataCreate( NULL, (const uint8_t *) "important data", strlen("important data"));
314 CFDictionarySetValue( attrs, kSecValueData, data );
317 XCTAssertEqual(SecItemAdd(attrs, NULL), errSecSuccess, @"Adding item works flawlessly");
319 oqes = [CKKSOutgoingQueueEntry all: &error];
320 XCTAssertEqual([oqes count], 1ul, @"Single entry in outgoing queue after adding item");
321 XCTAssertNil(error, @"No error loading queue");
323 CFDictionarySetValue( attrs, kSecAttrLabel, CFSTR( "TestLabel2" ) );
324 CFDictionarySetValue( attrs, kSecAttrAccount, CFSTR( "TestAccount2" ) );
325 CFDictionarySetValue( attrs, kSecAttrService, CFSTR( "TestService2" ) );
326 XCTAssertEqual(SecItemAdd(attrs, NULL), errSecSuccess);
329 oqes = [CKKSOutgoingQueueEntry all: &error];
330 XCTAssertEqual([oqes count], 2ul, @"Two entries in outgoing queue after adding item");
331 XCTAssertNil(error, @"No error loading queue");
334 - (void)testCKKSKey {
336 NSString* testUUID = @"157A3171-0677-451B-9EAE-0DDC4D4315B0";
337 NSString* testParentUUID = @"f5e7f20f-0885-48f9-b75d-9f0cfd2171b6";
339 NSData* testCKRecord = [@"nonsense" dataUsingEncoding:NSUTF8StringEncoding];
341 CKKSWrappedAESSIVKey* wrappedkey = [[CKKSWrappedAESSIVKey alloc] initWithBase64:@"KFfL58XtugiYNoD859EjG0StfrYd6eakm0CQrgX7iO+DEo4kio3WbEeA1kctCU0GaeTGsRFpbdy4oo6jXhVu7cZqB0svhUPGq55aGnszUjI="];
343 NSError* error = nil;
345 key = [CKKSKey fromDatabase:testUUID zoneID:self.testZoneID error:&error];
346 XCTAssertNil(key, "key does not exist yet");
347 XCTAssertNotNil(error, "error exists when things go wrong");
350 key = [[CKKSKey alloc] initWithWrappedAESKey: wrappedkey
352 parentKeyUUID:testParentUUID
353 keyclass:SecCKKSKeyClassA
354 state: SecCKKSProcessedStateLocal
355 zoneID:self.testZoneID
356 encodedCKRecord:testCKRecord
358 XCTAssertNotNil(key, "could create key");
360 [key saveToDatabase: &error];
361 XCTAssertNil(error, "could save key to database");
364 CKKSKey* key2 = [CKKSKey fromDatabase:testUUID zoneID:self.testZoneID error:&error];
365 XCTAssertNil(error, "no error exists when loading key");
366 XCTAssertNotNil(key2, "key was fetched properly");
368 XCTAssertEqualObjects(key.uuid, key2.uuid, "key uuids match");
369 XCTAssertEqualObjects(key.parentKeyUUID, key2.parentKeyUUID, "parent key uuids match");
370 XCTAssertEqualObjects(key.state, key2.state, "key states match");
371 XCTAssertEqualObjects(key.encodedCKRecord, key2.encodedCKRecord, "encodedCKRecord match");
372 XCTAssertEqualObjects(key.wrappedkey, key2.wrappedkey, "wrapped keys match");
373 XCTAssertEqual(key.currentkey, key2.currentkey, "currentkey match");
377 NSError* error = nil;
379 NSData* testCKRecord = [@"nonsense" dataUsingEncoding:NSUTF8StringEncoding];
381 CKKSKey* tlk = [[CKKSKey alloc] initSelfWrappedWithAESKey: [[CKKSAESSIVKey alloc] initWithBase64: @"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="]
382 uuid:@"8b2aeb7f-4af3-43e9-b6e6-70d5c728ebf7"
383 keyclass:SecCKKSKeyClassTLK
384 state: SecCKKSProcessedStateLocal
385 zoneID:self.testZoneID
386 encodedCKRecord: testCKRecord
388 XCTAssertTrue([tlk saveToDatabase: &error], "TLK saved to database");
389 XCTAssertNil(error, "no error saving TLK to database");
391 CKKSKey* wrappedKey = [[CKKSKey alloc] initWrappedBy: tlk
392 AESKey:[CKKSAESSIVKey randomKey]
393 uuid:@"157A3171-0677-451B-9EAE-0DDC4D4315B0"
394 keyclass:SecCKKSKeyClassC
395 state: SecCKKSProcessedStateLocal
396 zoneID:self.testZoneID
397 encodedCKRecord:testCKRecord
399 XCTAssertTrue([wrappedKey saveToDatabase: &error], "key saved to database");
400 XCTAssertNil(error, "no error saving key to database");
402 NSArray<CKKSKey*>* tlks = [CKKSKey allWhere: @{@"UUID": @"8b2aeb7f-4af3-43e9-b6e6-70d5c728ebf7"} error: &error];
403 XCTAssertNotNil(tlks, "Returned some array from allWhere");
404 XCTAssertNil(error, "no error back from allWhere");
405 XCTAssertEqual([tlks count], 1ul, "Received one row (and expected one row)");
407 NSArray<CKKSKey*>* selfWrapped = [CKKSKey allWhere: @{@"parentKeyUUID": [CKKSSQLWhereObject op:@"=" string:@"uuid"]} error: &error];
408 XCTAssertNotNil(selfWrapped, "Returned some array from allWhere");
409 XCTAssertNil(error, "no error back from allWhere");
410 XCTAssertEqual([selfWrapped count], 1ul, "Received one row (and expected one row)");
413 - (void)testGroupBy {
414 [self addTestZoneEntries];
415 NSError* error = nil;
417 __block NSMutableDictionary<NSString*, NSString*>* results = [[NSMutableDictionary alloc] init];
418 NSDictionary* expectedResults = nil;
420 [CKKSSQLDatabaseObject queryDatabaseTable: [CKKSOutgoingQueueEntry sqlTable]
422 columns: @[@"action", @"count(rowid)"]
423 groupBy: @[@"action"]
426 processRow: ^(NSDictionary* row) {
427 results[row[@"action"]] = row[@"count(rowid)"];
431 XCTAssertNil(error, "no error doing group by query");
433 SecCKKSActionAdd: @"2",
434 SecCKKSActionModify: @"1"
436 XCTAssertEqualObjects(results, expectedResults, "Recieved correct group by result");
438 // Now test with a where clause:
439 results = [[NSMutableDictionary alloc] init];
440 [CKKSSQLDatabaseObject queryDatabaseTable: [CKKSOutgoingQueueEntry sqlTable]
441 where: @{@"state": SecCKKSStateError}
442 columns: @[@"action", @"count(rowid)"]
443 groupBy: @[@"action"]
446 processRow: ^(NSDictionary* row) {
447 results[row[@"action"]] = row[@"count(rowid)"];
451 XCTAssertNil(error, "no error doing where+group by query");
453 SecCKKSActionAdd: @"1",
454 SecCKKSActionModify: @"1"
456 XCTAssertEqualObjects(results, expectedResults, "Recieved correct where+group by result");
459 - (void)testOrderBy {
460 [self addTestZoneEntries];
461 NSError* error = nil;
463 __block NSMutableArray* rows = [[NSMutableArray alloc] init];
465 [CKKSSQLDatabaseObject queryDatabaseTable: [CKKSOutgoingQueueEntry sqlTable]
467 columns: @[@"action", @"uuid"]
471 processRow: ^(NSDictionary* row) {
472 [rows addObject:row];
476 XCTAssertNil(error, "no error doing order by query");
477 XCTAssertEqual(rows.count, 3u, "got three items");
479 XCTAssertEqual([rows[0][@"uuid"] compare: rows[1][@"uuid"]], NSOrderedAscending, "first order is fine");
480 XCTAssertEqual([rows[1][@"uuid"] compare: rows[2][@"uuid"]], NSOrderedAscending, "second order is fine");
482 // Check that order-by + limit works to page
483 __block NSString* lastUUID = nil;
484 __block NSString* uuid = nil;
487 while(count == 0 || uuid != nil) {
489 [CKKSSQLDatabaseObject queryDatabaseTable: [CKKSOutgoingQueueEntry sqlTable]
490 where: lastUUID ? @{@"UUID": [CKKSSQLWhereObject op:@">" stringValue:lastUUID]} : nil
491 columns: @[@"action", @"UUID"]
495 processRow: ^(NSDictionary* row) {
496 XCTAssertNil(uuid, "Only one row returned");
500 XCTAssertNil(error, "No error doing SQL");
501 if(uuid && lastUUID) {
502 XCTAssertEqual([lastUUID compare:uuid], NSOrderedAscending, "uuids returning in right order");
507 XCTAssertEqual(count, 4u, "Received 3 objects (and 1 nil)");
511 [self addTestZoneEntries];
512 NSError* error = nil;
514 __block NSMutableDictionary<NSString*, NSString*>* results = [[NSMutableDictionary alloc] init];
516 [CKKSSQLDatabaseObject queryDatabaseTable: [CKKSOutgoingQueueEntry sqlTable]
518 columns: @[@"uuid", @"action"]
522 processRow: ^(NSDictionary* row) {
523 results[row[@"uuid"]] = row[@"action"];
527 XCTAssertNil(error, "no error doing vanilla query");
528 XCTAssertEqual(results.count, 3u, "Received three elements in normal query");
529 results = [[NSMutableDictionary alloc] init];
531 [CKKSSQLDatabaseObject queryDatabaseTable: [CKKSOutgoingQueueEntry sqlTable]
533 columns: @[@"uuid", @"action"]
537 processRow: ^(NSDictionary* row) {
538 results[row[@"uuid"]] = row[@"action"];
542 XCTAssertNil(error, "no error doing limit query");
543 XCTAssertEqual(results.count, 1u, "Received one element in limited query");
544 results = [[NSMutableDictionary alloc] init];
546 // Now test with a where clause:
547 results = [[NSMutableDictionary alloc] init];
548 [CKKSSQLDatabaseObject queryDatabaseTable: [CKKSOutgoingQueueEntry sqlTable]
549 where: @{@"state": SecCKKSStateError}
550 columns: @[@"uuid", @"action"]
554 processRow: ^(NSDictionary* row) {
555 results[row[@"uuid"]] = row[@"action"];
559 XCTAssertNil(error, "no error doing limit+where query");
560 XCTAssertEqual(results.count, 2u, "Received two elements in where+limited query");
561 results = [[NSMutableDictionary alloc] init];
563 results = [[NSMutableDictionary alloc] init];
564 [CKKSSQLDatabaseObject queryDatabaseTable: [CKKSOutgoingQueueEntry sqlTable]
565 where: @{@"state": SecCKKSStateError}
566 columns: @[@"uuid", @"action"]
570 processRow: ^(NSDictionary* row) {
571 results[row[@"uuid"]] = row[@"action"];
575 XCTAssertNil(error, "no error doing limit+where query");
576 XCTAssertEqual(results.count, 1u, "Received one element in where+limited query");
577 results = [[NSMutableDictionary alloc] init];