diff --git a/Sources/CoreDataRepository/CoreDataRepository+Aggregate.swift b/Sources/CoreDataRepository/CoreDataRepository+Aggregate.swift index d5dd8f8..77af4f0 100644 --- a/Sources/CoreDataRepository/CoreDataRepository+Aggregate.swift +++ b/Sources/CoreDataRepository/CoreDataRepository+Aggregate.swift @@ -25,13 +25,14 @@ extension CoreDataRepository { private func request( function: AggregateFunction, - predicate _: NSPredicate, + predicate: NSPredicate, entityDesc: NSEntityDescription, attributeDesc: NSAttributeDescription, groupBy: NSAttributeDescription? = nil ) -> NSFetchRequest { let expDesc = NSExpressionDescription.aggregate(function: function, attributeDesc: attributeDesc) let request = NSFetchRequest(entityName: entityDesc.managedObjectClassName) + request.predicate = predicate request.entity = entityDesc request.returnsObjectsAsFaults = false request.resultType = .dictionaryResultType diff --git a/Tests/CoreDataRepositoryTests/AggregateRepositoryTests.swift b/Tests/CoreDataRepositoryTests/AggregateRepositoryTests.swift index 1cf7456..b41e445 100644 --- a/Tests/CoreDataRepositoryTests/AggregateRepositoryTests.swift +++ b/Tests/CoreDataRepositoryTests/AggregateRepositoryTests.swift @@ -135,4 +135,48 @@ final class AggregateRepositoryTests: CoreDataXCTestCase { XCTFail("Not expecting failure") } } + + func testCountWithPredicate() async throws { + let result: Result<[[String: Int]], CoreDataRepositoryError> = try await repository() + .count(predicate: NSComparisonPredicate( + leftExpression: NSExpression(forKeyPath: \RepoMovie.title), + rightExpression: NSExpression(forConstantValue: "A"), + modifier: .direct, + type: .notEqualTo + ), entityDesc: RepoMovie.entity()) + switch result { + case let .success(values): + let firstValue = try XCTUnwrap(values.first?.values.first) + XCTAssertEqual(firstValue, 4, "Result value (count) should equal number of movies not titled 'A'.") + case .failure: + XCTFail("Not expecting failure") + } + } + + func testSumWithPredicate() async throws { + let result: Result<[[String: Decimal]], CoreDataRepositoryError> = try await repository().sum( + predicate: NSComparisonPredicate( + leftExpression: NSExpression(forKeyPath: \RepoMovie.title), + rightExpression: NSExpression(forConstantValue: "A"), + modifier: .direct, + type: .notEqualTo + ), + entityDesc: RepoMovie.entity(), + attributeDesc: XCTUnwrap( + RepoMovie.entity().attributesByName.values + .first(where: { $0.name == "boxOffice" }) + ) + ) + switch result { + case let .success(values): + let firstValue = try XCTUnwrap(values.first?.values.first) + XCTAssertEqual( + firstValue, + 140, + "Result value should equal sum of movies box office that are not titled 'A'." + ) + case .failure: + XCTFail("Not expecting failure") + } + } }