diff --git a/CoreZen/Database/DatabaseTable.h b/CoreZen/Database/DatabaseTable.h index 0490c01..5c14112 100644 --- a/CoreZen/Database/DatabaseTable.h +++ b/CoreZen/Database/DatabaseTable.h @@ -41,6 +41,10 @@ NS_ASSUME_NONNULL_BEGIN #pragma mark - Read +// A repository makes its objects from the rows of allRows:, rowByIdentifier: and +// its query fetches. Their first column must be the identifier: the repository +// reads it to find an object it already has, without making a DTO. + - (ZENDataTransferObject *)dtoFromRow:(ZENResultSet *)row; // nil if the query fails diff --git a/CoreZen/Domain/ObjectRepository.h b/CoreZen/Domain/ObjectRepository.h index 0199bd3..73db109 100644 --- a/CoreZen/Domain/ObjectRepository.h +++ b/CoreZen/Domain/ObjectRepository.h @@ -10,11 +10,18 @@ @protocol ZENDataModel; @protocol ZENDatabaseTable; +@class ZENDatabase; @class ZENDatabaseQueue; +@class ZENResultSet; @class ZENRepositoryWriteBatch; NS_ASSUME_NONNULL_BEGIN +// Returns the rows for a fetch, or nil if its query fails. It runs on the +// repository's database queue, and gets the repository's table, so it can call +// a query method of the table's own: declare the parameter as the table's class. +typedef ZENResultSet *_Nullable (^ZENRepositoryQuery)(__kindof NSObject *table, ZENDatabase *database); + typedef enum : NSUInteger { ZENObjectRepositoryCacheType_Weak = 0, ZENObjectRepositoryCacheType_Strong = 1 @@ -53,6 +60,8 @@ typedef enum : NSUInteger { #pragma mark - Fetch +// Every fetch returns the repository's one object for each identifier: the one +// in its cache, or else a new one made from the row, which joins the cache. // Fetched objects are delivered only after their async init has finished. Each // object's performAsyncInit runs once, when the repository first creates it // from the database; objects already in the cache aren't initialized again. @@ -73,6 +82,24 @@ typedef enum : NSUInteger { // Same as above, but resultsBlock happens on the main thread. - (void)fetchAllObjectsForUI:(ZENFetchResultsBlock)resultsBlock; +// Fetches the objects in the rows query returns, such as the ones that match a +// condition, in the order of their rows. Each object comes once, at its first +// row. The rows need the columns the table's dtoFromRow: reads, identifier +// first, as allRows: returns them. A failed query fetches no objects. With a +// table class that has a rowsInFolder:database: method, for example: +// +// [repository fetchObjectsWithQuery:^ZENResultSet *(MyTable *table, ZENDatabase *database) { +// return [table rowsInFolder:folder database:database]; +// } completion:^(NSArray *fetchedObjects) { ... }]; +// +// Runs asynchronously. Result callback block happens on a thread pool. +- (void)fetchObjectsWithQuery:(ZENRepositoryQuery)query + completion:(ZENFetchResultsBlock)resultsBlock; + +// Same as above, but uiCompletion block happens on the main thread. +- (void)fetchObjectsWithQuery:(ZENRepositoryQuery)query + uiCompletion:(ZENFetchResultsBlock)resultsBlock; + #pragma mark - Add, Update and Delete // Each write is a transaction of its own. Its completion gets nil once the change diff --git a/CoreZen/Domain/ObjectRepository.m b/CoreZen/Domain/ObjectRepository.m index 9dc01d1..307b602 100644 --- a/CoreZen/Domain/ObjectRepository.m +++ b/CoreZen/Domain/ObjectRepository.m @@ -58,12 +58,10 @@ @interface ZENObjectRepository () { @property (nonatomic, strong, readonly) ZENObjectCache *cache; @property (nonatomic, weak, readonly) id dataModel; -// Runs synchronously. To be called on database queue. -- (id)createObjectFromRow:(ZENResultSet *)row; - -// Runs synchronously. To be called on database queue. -- (id)fetchObjectByIdentifier:(ZENIdentifier)identifier - database:(ZENDatabase *)database; +// Runs synchronously. To be called on database queue. The objects in rows, in +// order and each once: the cached object for a row's identifier, or else a new +// one, which joins the cache and starts its async init. Closes rows. +- (NSArray *)objectsFromRows:(nullable ZENResultSet *)rows; // To be called on database queue, with objects that aren't cached yet. - (void)cacheAndStartAsyncInit:(NSArray *)objects; @@ -113,25 +111,38 @@ - (instancetype)initWithDataModel:(id)dataModel return self; } -#pragma mark - [private] Create - -- (id)createObjectFromRow:(ZENResultSet *)row { - ZENDataTransferObject *dto = [self.table dtoFromRow:row]; - id object = [[(Class)self.embryo alloc] initWithDTO:dto]; - return object; -} - #pragma mark - [private] Fetch -- (id)fetchObjectByIdentifier:(ZENIdentifier)identifier - database:(ZENDatabase *)database { - ZENResultSet *rs = [self.table rowByIdentifier:identifier database:database]; - id object = nil; - if ([rs next]) { - object = [self createObjectFromRow:rs]; +- (NSArray *)objectsFromRows:(ZENResultSet *)rows { + NSMutableArray *objects = [NSMutableArray array]; + NSMutableArray *newObjects = [NSMutableArray array]; + NSMutableSet *identifiers = [NSMutableSet set]; + while ([rows next]) { + // The identifier comes first, so finding a cached object needs no DTO + ZENIdentifier identifier = [rows longLongIntForColumnIndex:0]; + if ([identifiers containsObject:@(identifier)]) { + // A query that joins another table can return an object's row more than + // once. Making a second object for it would start a second init. + continue; + } + [identifiers addObject:@(identifier)]; + + id object = [self.cache cachedObject:identifier]; + if (!object) { + ZENDataTransferObject *dto = [self.table dtoFromRow:rows]; + object = [[(Class)self.embryo alloc] initWithDTO:dto]; + [newObjects addObject:object]; + } + [objects addObject:object]; } - [rs close]; - return object; + [rows close]; + + // Only objects new to the cache need async init; cached objects already had + // theirs, or are still waiting on it. Objects are only made and cached here, + // on the database queue, so no other fetch can make a second object for one + // of these identifiers in the meantime. + [self cacheAndStartAsyncInit:newObjects]; + return [objects copy]; } #pragma mark - [private] Async init @@ -250,32 +261,19 @@ - (void)sumColumn:(NSString *)columnName - (void)fetchObjectByIdentifier:(ZENIdentifier)identifier completion:(ZENFetchResultsBlock)resultsBlock { - // Check if this object is in the cache + // A cached object needs no trip to the database queue id object = [self.cache cachedObject:identifier]; if (object) { [self deliverObjects:@[object] whenInitialized:resultsBlock]; return; } - // Bounce to the database queue to fetch this object - [self.queue fetchAsync:^(ZENDatabase *database) { - // Check again if this object has shown up in the cache since we looked earlier - id object = [self.cache cachedObject:identifier]; - if (!object) { - // Create the object, cache it, then start its async init. This is safe because this runs - // on the database queue, and we only ever create and cache objects on this queue. If there - // was a race, only one instance can win and cache the object. The other instance would have - // a cache hit just before here. - object = [self fetchObjectByIdentifier:identifier database:database]; - if (!object) { - ZENCallFetchResultsBlockOnThreadPool(resultsBlock, @[]); - return; - } - [self cacheAndStartAsyncInit:@[object]]; - } - - [self deliverObjects:@[object] whenInitialized:resultsBlock]; - }]; + // If another fetch caches the object before this query runs, the row leads + // back to that one + [self fetchObjectsWithQuery:^ZENResultSet *(NSObject *table, ZENDatabase *database) { + return [table rowByIdentifier:identifier database:database]; + } + completion:resultsBlock]; } - (void)fetchObjectByIdentifier:(ZENIdentifier)identifier @@ -287,34 +285,11 @@ - (void)fetchObjectByIdentifier:(ZENIdentifier)identifier } - (void)fetchAllObjects:(ZENFetchResultsBlock)resultsBlock { - // We can't rely on the cache for early return like in objectByIdentifier: because we don't know - // the full list of the object identifiers without a query. - [self.queue fetchAsync:^(ZENDatabase *database) { - NSMutableArray *objects = [NSMutableArray array]; - NSMutableArray *newObjects = [NSMutableArray array]; - ZENResultSet *rs = [self.table allRows:database]; - while ([rs next]) { - // Check if an object with this identifier is in the cache - // TODO: Consider batching all identifiers together to a single cache call - int64_t identifier = [rs longLongIntForColumnIndex:0]; - id object = [self.cache cachedObject:identifier]; - - if (!object) { - ZENDataTransferObject *dto = [self.table dtoFromRow:rs]; - object = [[(Class)self.embryo alloc] initWithDTO:dto]; - [newObjects addObject:object]; - } - - [objects addObject:object]; - } - [rs close]; - - // Only objects new to the cache need async init; cached objects already - // had theirs, or are still waiting on it. See above for note on thread safety. - [self cacheAndStartAsyncInit:newObjects]; - - [self deliverObjects:[objects copy] whenInitialized:resultsBlock]; - }]; + // The cache can't answer this alone, since only the table knows every identifier + [self fetchObjectsWithQuery:^ZENResultSet *(NSObject *table, ZENDatabase *database) { + return [table allRows:database]; + } + completion:resultsBlock]; } - (void)fetchAllObjectsForUI:(ZENFetchResultsBlock)resultsBlock { @@ -324,6 +299,24 @@ - (void)fetchAllObjectsForUI:(ZENFetchResultsBlock)resultsBlock { }]; } +- (void)fetchObjectsWithQuery:(ZENRepositoryQuery)query + completion:(ZENFetchResultsBlock)resultsBlock { + [self.queue fetchAsync:^(ZENDatabase *database) { + // A failed query has no rows, and FMDB has logged why + NSArray *objects = [self objectsFromRows:query(self.table, database)]; + [self deliverObjects:objects whenInitialized:resultsBlock]; + }]; +} + +- (void)fetchObjectsWithQuery:(ZENRepositoryQuery)query + uiCompletion:(ZENFetchResultsBlock)resultsBlock { + // Bounce to main thread + [self fetchObjectsWithQuery:query + completion:^(NSArray *fetchedObjects) { + ZENCallFetchResultsBlockOnMainThread(resultsBlock, fetchedObjects); + }]; +} + #pragma mark - Add, Update and Delete - (void)write:(BOOL (^)(ZENDatabase *database))write diff --git a/CoreZenTests/Classes/TestDomainObject.h b/CoreZenTests/Classes/TestDomainObject.h index 8a1b53a..a0393fa 100644 --- a/CoreZenTests/Classes/TestDomainObject.h +++ b/CoreZenTests/Classes/TestDomainObject.h @@ -38,3 +38,18 @@ extern NSString *const ZENTestErrorDomain; @interface ZENSlowFailingInitDomainObject : ZENSlowInitDomainObject @end + +// The data model for ZENCountedInitDomainObjects. It calls repeatedInit when an +// identifier's async init starts for a second time. +@interface ZENInitCountingModel : NSObject + +@property (atomic, copy) void (^repeatedInit)(ZENIdentifier identifier); + +- (void)countInitOf:(ZENIdentifier)identifier; + +@end + +// Its performAsyncInit: tells its model, a ZENInitCountingModel +@interface ZENCountedInitDomainObject : ZENTestDomainObject + +@end diff --git a/CoreZenTests/Classes/TestDomainObject.m b/CoreZenTests/Classes/TestDomainObject.m index 77a1d07..e2bdeee 100644 --- a/CoreZenTests/Classes/TestDomainObject.m +++ b/CoreZenTests/Classes/TestDomainObject.m @@ -93,3 +93,39 @@ - (NSError *)asyncInitError { } @end + +@implementation ZENInitCountingModel { + NSCountedSet *_inits; +} + +- (instancetype)init { + self = [super init]; + if (self) { + _inits = [NSCountedSet set]; + } + return self; +} + +- (void)countInitOf:(ZENIdentifier)identifier { + NSUInteger count = 0; + @synchronized(self) { + [_inits addObject:@(identifier)]; + count = [_inits countForObject:@(identifier)]; + } + void (^repeatedInit)(ZENIdentifier) = self.repeatedInit; + if (count > 1 && repeatedInit) { + repeatedInit(identifier); + } +} + +@end + +@implementation ZENCountedInitDomainObject + +- (void)performAsyncInit:(id)model + completion:(ZENAsyncCompletionBlock)completion { + [(ZENInitCountingModel *)model countInitOf:self.identifier]; + completion(nil); +} + +@end diff --git a/CoreZenTests/Classes/TestTable.h b/CoreZenTests/Classes/TestTable.h index 4d7d586..ec22b60 100644 --- a/CoreZenTests/Classes/TestTable.h +++ b/CoreZenTests/Classes/TestTable.h @@ -8,6 +8,10 @@ @interface ZENTestTable : NSObject +// Rows whose name matches a LIKE pattern, by name from Z to A: a query of the +// table's own, for repository query fetches +- (ZENResultSet *)rowsWithNamesLike:(NSString *)pattern database:(ZENDatabase *)database; + @end // Same columns as ZENTestTable, stored in a separate table diff --git a/CoreZenTests/Classes/TestTable.m b/CoreZenTests/Classes/TestTable.m index 6bc86ba..7bc0ce8 100644 --- a/CoreZenTests/Classes/TestTable.m +++ b/CoreZenTests/Classes/TestTable.m @@ -60,6 +60,11 @@ - (ZENResultSet *)rowByIdentifier:(ZENIdentifier)identifier database:(ZENDatabas return [database executeQuery:sql withArgumentsInArray:@[@(identifier)]]; } +- (ZENResultSet *)rowsWithNamesLike:(NSString *)pattern database:(ZENDatabase *)database { + NSString *sql = [NSString stringWithFormat:@"SELECT identifier, name FROM %@ WHERE name LIKE ? ORDER BY name DESC;", self.tableName]; + return [database executeQuery:sql withArgumentsInArray:@[pattern]]; +} + - (NSUInteger)countAllRows:(ZENDatabase *)database { NSString *sql = [NSString stringWithFormat:@"SELECT COUNT(*) FROM %@;", self.tableName]; ZENResultSet *rs = [database executeQuery:sql]; diff --git a/CoreZenTests/DomainTests.m b/CoreZenTests/DomainTests.m index d9f57c6..3d85709 100644 --- a/CoreZenTests/DomainTests.m +++ b/CoreZenTests/DomainTests.m @@ -123,7 +123,12 @@ - (void)testDomainObjectIdentifierPassthrough { #pragma mark - Repository helpers - (ZENObjectRepository *)repositoryWithEmbryo:(Class)embryo { - return [[ZENObjectRepository alloc] initWithDataModel:nil + return [self repositoryWithEmbryo:embryo model:nil]; +} + +// The repository keeps only a weak reference to model +- (ZENObjectRepository *)repositoryWithEmbryo:(Class)embryo model:(id)model { + return [[ZENObjectRepository alloc] initWithDataModel:model tableClass:[ZENTestTable class] databaseQueue:self.queue domainObjectEmbryo:embryo @@ -206,6 +211,26 @@ - (NSArray *)fetchAllFromRepository:(ZENObjectRepository *)repo { return result; } +- (NSArray *)fetchFromRepository:(ZENObjectRepository *)repo withQuery:(ZENRepositoryQuery)query { + XCTestExpectation *fetched = [self expectationWithDescription:@"fetch with query"]; + __block NSArray *result = nil; + [repo fetchObjectsWithQuery:query + completion:^(NSArray *fetchedObjects) { + result = fetchedObjects; + [fetched fulfill]; + }]; + [self waitForExpectations:@[fetched] timeout:5.0]; + return result; +} + +// Fetches with a query method of the repository's table class +- (NSArray *)fetchFromRepository:(ZENObjectRepository *)repo namesLike:(NSString *)pattern { + return [self fetchFromRepository:repo + withQuery:^ZENResultSet *(ZENTestTable *table, ZENDatabase *database) { + return [table rowsWithNamesLike:pattern database:database]; + }]; +} + - (NSArray *)fetchObjectWithIdentifier:(ZENIdentifier)identifier fromRepository:(ZENObjectRepository *)repo { XCTestExpectation *fetched = [self expectationWithDescription:@"fetch"]; __block NSArray *result = nil; @@ -686,6 +711,118 @@ - (void)testAsyncInitAndAddReportsFailureWithoutAdding { XCTAssertEqualObjects([objects valueForKey:@"name"], (@[@"Beta"])); } +#pragma mark - Query fetches + +- (void)testQueryFetchReturnsMatchingObjectsInRowOrder { + ZENObjectRepository *repo = self.repository; + [self insertRowsNamed:@[@"Apple", @"Banana", @"Avocado"]]; + + NSArray *objects = [self fetchFromRepository:repo namesLike:@"A%"]; + XCTAssertEqualObjects([objects valueForKey:@"name"], (@[@"Avocado", @"Apple"])); +} + +- (void)testQueryFetchReturnsTheRepositorysObjects { + ZENObjectRepository *repo = self.repository; + ZENTestDomainObject *added = [self addObjectNamed:@"Apple" toRepository:repo]; + [self insertRowsNamed:@[@"Avocado"]]; + + // The object added through the repository is the one it returns + NSArray *objects = [self fetchFromRepository:repo namesLike:@"A%"]; + XCTAssertEqual(objects.count, 2u); + XCTAssertEqual(objects.lastObject, added); + + // The object the query made joins the cache, so other fetches return it too + ZENTestDomainObject *made = objects.firstObject; + XCTAssertEqualObjects(made.name, @"Avocado"); + XCTAssertEqual([self fetchObjectWithIdentifier:made.identifier fromRepository:repo].firstObject, made); +} + +- (void)testQueryFetchRunsAsyncInitOnce { + ZENObjectRepository *repo = [self repositoryWithEmbryo:[ZENSlowInitDomainObject class]]; + ZENIdentifier identifier = [self insertRowsNamed:@[@"Apple", @"Avocado"]].firstObject.longLongValue; + + // Start Apple's init with another fetch, then query while it runs + [repo fetchObjectByIdentifier:identifier completion:^(NSArray *fetchedObjects){}]; + NSArray *first = [self fetchFromRepository:repo namesLike:@"A%"]; + NSArray *second = [self fetchFromRepository:repo namesLike:@"A%"]; + + XCTAssertEqual(first.count, 2u); + XCTAssertEqualObjects(first, second, @"Second fetch should return the cached objects"); + for (ZENSlowInitDomainObject *object in second) { + XCTAssertTrue(object.initialized); + XCTAssertEqual(object.asyncInitCount, 1, @"Cached objects shouldn't be initialized again"); + } +} + +- (void)testQueryFetchLeavesOutObjectsWhoseInitFailed { + ZENObjectRepository *repo = [self repositoryWithEmbryo:[ZENFailableInitDomainObject class]]; + [self insertRowsNamed:@[@"Apple", @"Fail-Banana", @"Cherry"]]; + + NSArray *objects = [self fetchFromRepository:repo namesLike:@"%"]; + XCTAssertEqualObjects([objects valueForKey:@"name"], (@[@"Cherry", @"Apple"])); +} + +- (void)testQueryFetchInitializesAnObjectOnceWhenItsRowRepeats { + ZENInitCountingModel *model = [ZENInitCountingModel new]; + ZENObjectRepository *repo = [self repositoryWithEmbryo:[ZENCountedInitDomainObject class] model:model]; + XCTestExpectation *initializedAgain = [self expectationWithDescription:@"an object initialized again"]; + initializedAgain.inverted = YES; + model.repeatedInit = ^(ZENIdentifier identifier) { + [initializedAgain fulfill]; + }; + + // A query that joins another table returns an object's row once per match. + // Banana has two tags, so its row comes first and again last. + NSArray *identifiers = [self insertRowsNamed:@[@"Apple", @"Banana"]]; + [self.queue transactionSync:^(ZENDatabase *database) { + XCTAssertTrue([database executeUpdate:@"CREATE TABLE tags (object_identifier INTEGER, tag TEXT);"]); + NSArray *tags = @[@[identifiers[1], @"yellow"], @[identifiers[0], @"red"], @[identifiers[1], @"long"]]; + for (NSArray *tag in tags) { + XCTAssertTrue([database executeUpdate:@"INSERT INTO tags (object_identifier, tag) VALUES (?, ?);" withArgumentsInArray:tag]); + } + }]; + + NSArray *objects = + [self fetchFromRepository:repo + withQuery:^ZENResultSet *(ZENTestTable *table, ZENDatabase *database) { + return [database executeQuery:@"SELECT test_objects.identifier, name FROM test_objects " + @"JOIN tags ON tags.object_identifier = test_objects.identifier " + @"ORDER BY tags.rowid;"]; + }]; + XCTAssertEqualObjects([objects valueForKey:@"name"], (@[@"Banana", @"Apple"])); + + // Without a second object for its second row, Banana has no second init. One + // would have started by now, so this waits only briefly to see it. + [self waitForExpectations:@[initializedAgain] timeout:0.5]; +} + +- (void)testFailedQueryFetchesNothing { + ZENObjectRepository *repo = self.repository; + [self insertRowsNamed:@[@"Apple"]]; + + NSArray *objects = [self fetchFromRepository:repo + withQuery:^ZENResultSet *(ZENTestTable *table, ZENDatabase *database) { + return [database executeQuery:@"SELECT identifier, name FROM no_such_table;"]; + }]; + XCTAssertEqualObjects(objects, @[]); +} + +- (void)testQueryFetchUICompletionIsOnMainThread { + ZENObjectRepository *repo = self.repository; + [self insertRowsNamed:@[@"Apple"]]; + + XCTestExpectation *fetched = [self expectationWithDescription:@"fetch"]; + [repo fetchObjectsWithQuery:^ZENResultSet *(ZENTestTable *table, ZENDatabase *database) { + return [table rowsWithNamesLike:@"A%" database:database]; + } + uiCompletion:^(NSArray *fetchedObjects) { + XCTAssertTrue(NSThread.isMainThread); + XCTAssertEqualObjects([fetchedObjects valueForKey:@"name"], @[@"Apple"]); + [fetched fulfill]; + }]; + [self waitForExpectations:@[fetched] timeout:5.0]; +} + #pragma mark - Write Batches // Saves the writes build stages, and returns the batch's error, or nil once it's saved diff --git a/README.md b/README.md index 9f888e4..c004a55 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ A domain model stored in SQLite: a table class for each table, plain data object * [`ZENDomainObject`](https://github.com/znelson/CoreZen/blob/main/CoreZen/Domain/DomainObject.h) is built around a DTO. A subclass can override `performAsyncInit:completion:` to finish setting itself up after it's created or loaded, such as checking a file on disk, reading media metadata, or fetching related objects, and report an error if that fails. `+asyncInit:model:completion:` runs it for several objects at once on a thread pool. * [`ZENObjectRepository`](https://github.com/znelson/CoreZen/blob/main/CoreZen/Domain/ObjectRepository.h) combines a table, a database queue and a [`ZENObjectCache`](https://github.com/znelson/CoreZen/blob/main/CoreZen/Cache/ObjectCache.h), which holds its objects weakly or strongly. * Each identifier has one object in memory, so every part of an app sees the same one. + * Fetches get every object, the object with an identifier, or with `fetchObjectsWithQuery:completion:`, the objects in the rows a query returns, such as a query method of the table class's own. * Fetches deliver objects only once their async init has finished. Init runs once per object, and an object whose init fails is left out. * Add, update and delete are each a transaction of their own, and their completion reports `nil` once the change is saved, or the error. Only a saved change updates the cache and posts `ZENObjectRepositoryObjectAddedNotification`, `...UpdatedNotification` or `...DeletedNotification`, on the main thread. * `+performWrites:completion:` saves several writes, to objects in one or more repositories that share a database queue, in one transaction: all of them or none.