Search code examples
iosswiftcore-datagroup-bynsfetchrequest

Core Data exception error - Invalid fetch request: HAVING with no GROUP BY with userInfo of (null)


I am getting a runtime error saying:

Invalid fetch request: HAVING with no GROUP BY with userInfo of (null)

At the place in my code that says "// error here":

let request = NSFetchRequest<NSFetchRequestResult>(entityName: CoreDataStrings.entityAffirmation)
let predicate = NSPredicate(format:"recordName == %@", privateRecord.recordID.recordName)
request.havingPredicate = predicate

print("predicte =", predicate)

do {
    let affirmationEntityInstances: [Affirmation] = try managedObjectContext.fetch(request) as! [Affirmation] // error here
    print("result =", affirmationEntityInstances)
    ...
} catch {
    ...
}

The code never reaches the print statement after the line with the comment "// error here". The error is not an error caught by the catch statement.

Here is the results of the debug window starting at the print statement to print the predicate.

predicte = recordName == "F9DB2EE8-B693-44B7-BA2B-3EAB689A9940"
2019-07-17 14:05:50.409279-0500 Affirmations[68672:14476409] [error] error: SQLCore dispatchRequest: exception handling request: <NSSQLFetchRequestContext: 0x6000019402a0> , Invalid fetch request: HAVING with no GROUP BY with userInfo of (null)
CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLFetchRequestContext: 0x6000019402a0> , Invalid fetch request: HAVING with no GROUP BY with userInfo of (null)
2019-07-17 14:05:50.625355-0500 Affirmations[68672:14476409] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid fetch request: HAVING with no GROUP BY'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010fb596fb __exceptionPreprocess + 331
    1   libobjc.A.dylib                     0x000000010eb7cac5 objc_exception_throw + 48
    2   CoreData                            0x000000010f61aeb0 -[NSSQLGenerator newSQLStatementForRequest:ignoreInheritance:countOnly:nestingLevel:nestIsWhereScoped:requestContext:] + 1584
    3   CoreData                            0x000000010f62549e -[NSSQLiteAdapter _statementForFetchRequestContext:ignoreInheritance:countOnly:nestingLevel:] + 142
    4   CoreData                            0x000000010f4d32e4 -[NSSQLiteAdapter newSelectStatementWithFetchRequestContext:ignoreInheritance:] + 116
    5   CoreData                            0x000000010f670843 -[NSSQLFetchRequestContext _createStatement] + 67
    6   CoreData                            0x000000010f6707de -[NSSQLFetchRequestContext fetchStatement] + 142
    7   CoreData                            0x000000010f6717cb -[NSSQLFetchRequestContext executeRequestCore:] + 27
    8   CoreData                            0x000000010f6db010 -[NSSQLStoreRequestContext executeRequestUsingConnection:] + 208
    9   CoreData                            0x000000010f6af9eb __52-[NSSQLDefaultConnectionManager handleStoreRequest:]_block_invoke + 75
    10  libdispatch.dylib                   0x0000000111cb1db5 _dispatch_client_callout + 8
    11  libdispatch.dylib                   0x0000000111cbfd08 _dispatch_lane_barrier_sync_invoke_and_complete + 132
    12  CoreData                            0x000000010f6af8d0 -[NSSQLDefaultConnectionManager handleStoreRequest:] + 336
    13  CoreData                            0x000000010f6b7504 -[NSSQLCoreDispatchManager routeStoreRequest:] + 308
    14  CoreData                            0x000000010f5ffc38 -[NSSQLCore dispatchRequest:withRetries:] + 232
    15  CoreData                            0x000000010f5fc9ad -[NSSQLCore processFetchRequest:inContext:] + 93
    16  CoreData                            0x000000010f4d27ee -[NSSQLCore executeRequest:withContext:error:] + 574
    17  CoreData                            0x000000010f5e1007 __65-[NSPersistentStoreCoordinator executeRequest:withContext:error:]_block_invoke + 2039
    18  CoreData                            0x000000010f5d9220 -[NSPersistentStoreCoordinator _routeHeavyweightBlock:] + 288
    19  CoreData                            0x000000010f4d1fc0 -[NSPersistentStoreCoordinator executeRequest:withContext:error:] + 1296
    20  CoreData                            0x000000010f4d0295 -[NSManagedObjectContext executeFetchRequest:error:] + 933
    21  Affirmations                        0x000000010dfd8230 $s12Affirmations14UTIAffirmationC6recordACSo8CKRecordC_tcfc + 13072
    22  Affirmations                        0x000000010dfd4f10 $s12Affirmations14UTIAffirmationC6recordACSo8CKRecordC_tcfC + 64
    23  Affirmations                        0x000000010df95584 $s12Affirmations25initDataModelFromCloudKityyFyycfU_ySaySo8CKRecordCGSg_s5Error_pSgtcfU_ + 1252
    24  Affirmations                        0x000000010df8fde6 $sSaySo8CKRecordCGSgs5Error_pSgIeggg_So7NSArrayCSgSo7NSErrorCSgIeyByy_TR + 230
    25  CloudKit                            0x000000010e3cbb0d -[CKQueryOperation _finishOnCallbackQueueWithError:] + 613
    26  CloudKit                            0x000000010e3c4c1a -[CKOperation _finishInternalOnCallbackQueueWithError:] + 582
    27  CloudKit                            0x000000010e3c49ba -[CKOperation _handleCompletionCallback:] + 148
    28  CloudKit                            0x000000010e3cb7e1 -[CKQueryOperation _handleCompletionCallback:] + 197
    29  CloudKit                            0x000000010e43a6c5 __68-[CKOperationCallbackManager _performCallbackForOperation:callback:]_block_invoke + 278
    30  libdispatch.dylib                   0x0000000111cbf725 _dispatch_block_async_invoke2 + 83
    31  libdispatch.dylib                   0x0000000111cb1db5 _dispatch_client_callout + 8
    32  libdispatch.dylib                   0x0000000111cb9225 _dispatch_lane_serial_drain + 778
    33  libdispatch.dylib                   0x0000000111cb9ed0 _dispatch_lane_invoke + 477
    34  libdispatch.dylib                   0x0000000111cc3ea3 _dispatch_workloop_worker_thread + 733
    35  libsystem_pthread.dylib             0x000000011209a611 _pthread_wqthread + 421
    36  libsystem_pthread.dylib             0x000000011209a3fd start_wqthread + 13
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

Here is my subclass of NSManagedObject:

public class Affirmation: NSManagedObject {

}

extension Affirmation {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Affirmation> {
        return NSFetchRequest<Affirmation>(entityName: "Affirmation")
    }

    @NSManaged public var body: String
    @NSManaged public var count: Int64
    @NSManaged public var days: NSData
    @NSManaged public var frequency: Int64
    @NSManaged public var notificationIdentifiers: NSObject
    @NSManaged public var recordName: String?
    @NSManaged public var time: NSDate
    @NSManaged public var timestamp: NSDate
    @NSManaged public var title: String

}

Solution

  • You are using a standard query without a GROUP BY directive – that's what the error says – so use the standard API

    request.predicate = predicate
    

    And you can get rid of the type cast and the type annotation if you specify the generic type of the request

    let request = NSFetchRequest<Affirmation>(entityName: CoreDataStrings.entityAffirmation)
    
    ...
    
    let affirmationEntityInstances = try managedObjectContext.fetch(request)