Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CoreZen/Database/DatabaseTable.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
27 changes: 27 additions & 0 deletions CoreZen/Domain/ObjectRepository.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<ZENDatabaseTable> *table, ZENDatabase *database);

typedef enum : NSUInteger {
ZENObjectRepositoryCacheType_Weak = 0,
ZENObjectRepositoryCacheType_Strong = 1
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand Down
133 changes: 63 additions & 70 deletions CoreZen/Domain/ObjectRepository.m
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,10 @@ @interface ZENObjectRepository () {
@property (nonatomic, strong, readonly) ZENObjectCache *cache;
@property (nonatomic, weak, readonly) id<ZENDataModel> dataModel;

// Runs synchronously. To be called on database queue.
- (id<ZENIdentifiable>)createObjectFromRow:(ZENResultSet *)row;

// Runs synchronously. To be called on database queue.
- (id<ZENIdentifiable>)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;
Expand Down Expand Up @@ -113,25 +111,38 @@ - (instancetype)initWithDataModel:(id<ZENDataModel>)dataModel
return self;
}

#pragma mark - [private] Create

- (id<ZENIdentifiable>)createObjectFromRow:(ZENResultSet *)row {
ZENDataTransferObject *dto = [self.table dtoFromRow:row];
id<ZENIdentifiable> object = [[(Class)self.embryo alloc] initWithDTO:dto];
return object;
}

#pragma mark - [private] Fetch

- (id<ZENIdentifiable>)fetchObjectByIdentifier:(ZENIdentifier)identifier
database:(ZENDatabase *)database {
ZENResultSet *rs = [self.table rowByIdentifier:identifier database:database];
id<ZENIdentifiable> object = nil;
if ([rs next]) {
object = [self createObjectFromRow:rs];
- (NSArray *)objectsFromRows:(ZENResultSet *)rows {
NSMutableArray *objects = [NSMutableArray array];
NSMutableArray *newObjects = [NSMutableArray array];
NSMutableSet<NSNumber *> *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<ZENIdentifiable> 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
Expand Down Expand Up @@ -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<ZENIdentifiable> 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<ZENIdentifiable> 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<ZENDatabaseTable> *table, ZENDatabase *database) {
return [table rowByIdentifier:identifier database:database];
}
completion:resultsBlock];
}

- (void)fetchObjectByIdentifier:(ZENIdentifier)identifier
Expand All @@ -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<ZENIdentifiable> 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<ZENDatabaseTable> *table, ZENDatabase *database) {
return [table allRows:database];
}
completion:resultsBlock];
}

- (void)fetchAllObjectsForUI:(ZENFetchResultsBlock)resultsBlock {
Expand All @@ -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
Expand Down
15 changes: 15 additions & 0 deletions CoreZenTests/Classes/TestDomainObject.h
Original file line number Diff line number Diff line change
Expand Up @@ -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 <ZENDataModel>

@property (atomic, copy) void (^repeatedInit)(ZENIdentifier identifier);

- (void)countInitOf:(ZENIdentifier)identifier;

@end

// Its performAsyncInit: tells its model, a ZENInitCountingModel
@interface ZENCountedInitDomainObject : ZENTestDomainObject

@end
36 changes: 36 additions & 0 deletions CoreZenTests/Classes/TestDomainObject.m
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,39 @@ - (NSError *)asyncInitError {
}

@end

@implementation ZENInitCountingModel {
NSCountedSet<NSNumber *> *_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<ZENDataModel>)model
completion:(ZENAsyncCompletionBlock)completion {
[(ZENInitCountingModel *)model countInitOf:self.identifier];
completion(nil);
}

@end
4 changes: 4 additions & 0 deletions CoreZenTests/Classes/TestTable.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@

@interface ZENTestTable : NSObject <ZENDatabaseTable>

// 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
Expand Down
5 changes: 5 additions & 0 deletions CoreZenTests/Classes/TestTable.m
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down
Loading