diff --git a/.github/workflows/objective-c-xcode.yml b/.github/workflows/objective-c-xcode.yml index 6775573..c03018d 100644 --- a/.github/workflows/objective-c-xcode.yml +++ b/.github/workflows/objective-c-xcode.yml @@ -126,6 +126,13 @@ jobs: run: | xcodebuild build -scheme CoreZen -project CoreZen.xcodeproj + # Builds the documentation from the headers' /// comments and the articles + # in CoreZen/CoreZen.docc. A DocC warning, such as a link to a symbol that + # doesn't exist, fails the step. + - name: Build Documentation + run: | + xcodebuild docbuild -scheme CoreZen -project CoreZen.xcodeproj OTHER_DOCC_FLAGS="--warnings-as-errors" + - name: Test run: | xcodebuild test -scheme CoreZen -project CoreZen.xcodeproj \ diff --git a/CHANGELOG.md b/CHANGELOG.md index 5634173..33da6d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ To note a change, add a line under Unreleased, in a group such as Added, Changed ## Unreleased +### Added + +- Documentation for the persistence API, built with DocC: doc comments in its headers, which Xcode shows in Quick Help, and a Persistence article with an example. + ## 0.1.0 - 2026-11-19 The first tagged version, with the persistence layer, media playback and frame rendering, and utilities that the README describes. Changes made before it are in the git history. diff --git a/CoreZen/Cache/ObjectCache.h b/CoreZen/Cache/ObjectCache.h index c72a646..a9a4b0f 100644 --- a/CoreZen/Cache/ObjectCache.h +++ b/CoreZen/Cache/ObjectCache.h @@ -12,17 +12,35 @@ NS_ASSUME_NONNULL_BEGIN +/// Objects by identifier, which any thread can use. +/// +/// A repository keeps its objects in one, so that each identifier has one object +/// in memory. @interface ZENObjectCache : NSObject +/// Makes a cache that holds each object only while something else holds it too. + (instancetype)weakObjectCache; + +/// Makes a cache that holds each object until it's removed. + (instancetype)strongObjectCache; -// nil if nothing with this identifier is cached +/// The object cached with this identifier, or nil if there's none. - (nullable id)cachedObject:(ZENIdentifier)identifier; + +/// Caches an object by its identifier, unless the cache has an object with that +/// identifier already. +/// +/// The cache keeps the first object it gets for an identifier, so ignoring a +/// second one keeps the one that the rest of the app may already be using. - (void)cacheObject:(id)object; + +/// Removes the object with this identifier, if there's one. - (void)removeObject:(ZENIdentifier)identifier; +/// Every object in the cache, in no particular order. - (NSArray> *)allCachedObjects; + +/// Removes every object. - (void)removeAllObjects; @end diff --git a/CoreZen/CoreZen.docc/ASSERT_MAIN_THREAD.md b/CoreZen/CoreZen.docc/ASSERT_MAIN_THREAD.md new file mode 100644 index 0000000..b043fc0 --- /dev/null +++ b/CoreZen/CoreZen.docc/ASSERT_MAIN_THREAD.md @@ -0,0 +1,7 @@ +# ``ASSERT_MAIN_THREAD`` + +Stops the process with an assertion failure unless it's on the main thread. + +## Overview + +Like any `assert`, it does nothing where `NDEBUG` is defined. diff --git a/CoreZen/CoreZen.docc/CoreZen.md b/CoreZen/CoreZen.docc/CoreZen.md index 1af0ddf..b8c29ce 100755 --- a/CoreZen/CoreZen.docc/CoreZen.md +++ b/CoreZen/CoreZen.docc/CoreZen.md @@ -1,13 +1,19 @@ # ``CoreZen`` -Summary +Store a domain model in SQLite, play and render media, and more, in a macOS app. ## Overview -Text +CoreZen is an Objective-C framework for macOS 14 or later, on Apple silicon. It has three parts: + +- term Persistence: A domain model stored in SQLite, with repositories that load, cache and save its objects asynchronously. It's built on [FMDB](https://github.com/ccgus/fmdb). +- term Media: Playback with [mpv](https://mpv.io), and frames rendered from video files with [FFmpeg](https://ffmpeg.org). +- term Utilities: Smaller AppKit and Foundation helpers, such as a tree of nodes, a preferences window and a work queue. + +CoreZen's [README](https://github.com/znelson/CoreZen#readme) says how to get its dependencies and build it. ## Topics -### Group +### Essentials -- ``Symbol`` \ No newline at end of file +- diff --git a/CoreZen/CoreZen.docc/Persistence.md b/CoreZen/CoreZen.docc/Persistence.md new file mode 100644 index 0000000..9b52777 --- /dev/null +++ b/CoreZen/CoreZen.docc/Persistence.md @@ -0,0 +1,157 @@ +# Persistence + +Store a domain model in SQLite, and load, cache and save its objects asynchronously. + +## Overview + +An app describes each table with three classes: + +- A table class, which conforms to ``ZENDatabaseTable``, creates and migrates the table, and reads and writes its rows. +- A data transfer object (DTO), a subclass of ``ZENDataTransferObject``, holds one row's values in properties. +- A domain object, a subclass of ``ZENDomainObject-c.class``, is what the rest of the app works with. It's built around a DTO, and adds whatever the app needs beyond the stored values. + +A ``ZENObjectRepository`` brings these together with a ``ZENDatabaseQueue``. It loads the objects, keeps one in memory for each identifier, and saves changes, all asynchronously. Each object has a ``ZENIdentifier`` from ``ZENGetNextObjectIdentifier``, which is unique across every database the process opens. + +### Describe a Table + +For a table of notes, each with some text: + +```objc +@interface NoteDTO : ZENDataTransferObject +@property (nonatomic, copy, nullable) NSString *text; +@end + +@interface Note : ZENDomainObject +@end + +@interface NoteTable : NSObject +@end + +@implementation NoteTable + ++ (NSString *)tableName { + return @"notes"; +} + ++ (BOOL)updateSchema:(ZENDatabase *)database version:(NSUInteger)version { + if (version == 1) { + [database executeUpdate:@"CREATE TABLE notes (identifier INTEGER PRIMARY KEY, text TEXT);"]; + return YES; + } + return NO; +} + +- (BOOL)insertDTO:(ZENDataTransferObject *)dto database:(ZENDatabase *)database { + NoteDTO *note = (NoteDTO *)dto; + return [database executeUpdate:@"INSERT INTO notes (identifier, text) VALUES (?, ?);", + @(note.identifier), note.text ?: NSNull.null]; +} + +- (ZENDataTransferObject *)dtoFromRow:(ZENResultSet *)row { + NoteDTO *note = [[NoteDTO alloc] initWithIdentifier:[row longLongIntForColumnIndex:0]]; + note.text = [row stringForColumnIndex:1]; + return note; +} + +- (ZENResultSet *)allRows:(ZENDatabase *)database { + return [database executeQuery:@"SELECT identifier, text FROM notes;"]; +} + +// updateDTO:database:, deleteByIdentifier:database:, rowByIdentifier:database: +// and countAllRows: work the same way. + +@end +``` + +A later version of the schema adds a branch for version 2, and so on. Each version's change runs once. + +### Open the Database + +A ``ZENDatabaseSchema`` brings the database up to the latest version of every table's schema: + +```objc +ZENDatabaseQueue *queue = [ZENDatabaseQueue databaseQueueWithURL:databaseURL]; +ZENDatabaseSchema *schema = [ZENDatabaseSchema schemaWithTableClasses:@[NoteTable.class]]; +[queue transactionSync:^(ZENDatabase *database) { + [schema initializeDatabase:database]; +}]; +``` + +### Load and Save Objects + +A repository for the table makes a `Note` from each row: + +```objc +ZENObjectRepository *notes = [[ZENObjectRepository alloc] initWithDataModel:nil + tableClass:NoteTable.class + databaseQueue:queue + domainObjectEmbryo:Note.class + cacheType:ZENObjectRepositoryCacheType_Weak]; + +NoteDTO *dto = [[NoteDTO alloc] initWithIdentifier:ZENGetNextObjectIdentifier()]; +dto.text = @"Buy milk"; +[notes addObject:[[Note alloc] initWithDTO:dto] uiCompletion:^(NSError *error) { + // nil once the note is saved, or else why it wasn't +}]; + +[notes fetchAllObjectsForUI:^(NSArray *fetchedObjects) { + // Every note +}]; +``` + +The repository runs these one after the other on the database queue, so the fetch finds the new note. Each write's completion gets nil once the change is saved, or an error in ``ZENDatabaseErrorDomain`` that says why it wasn't. An object that observes the repository, with ``ZENObjectRepository/zen_addObserver:selector:``, hears about each saved change on the main thread. + +## Topics + +### Repositories + +- ``ZENObjectRepository`` + +### Domain Objects + +- ``ZENDomainObject-c.class`` +- ``ZENDomainObject-c.protocol`` +- ``ZENDataModel`` + +### Tables + +- ``ZENDatabaseTable`` +- ``ZENDataTransferObject`` +- ``ZENDatabaseSchema`` + +### Databases + +- ``ZENDatabaseQueue`` +- ``ZENDatabase`` +- ``ZENResultSet`` +- ``ZENDatabaseErrorDomain`` +- ``ZENDatabaseErrorCode`` + +### Identifiers + +- ``ZENIdentifier`` +- ``ZENInvalidIdentifier`` +- ``ZENIdentifiable`` +- ``ZENGetNextObjectIdentifier`` +- ``ZENSetLargestObjectIdentifier`` + +### Caching + +- ``ZENObjectCache`` + +### Asynchronous Callbacks + +- ``ZENAsyncCompletionBlock`` +- ``ZENAsyncContinueBlock`` +- ``ZENFetchResultsBlock`` +- ``ZENAsyncCountCompletionBlock`` +- ``ZENCallAsyncCompletionBlockOnThreadPool`` +- ``ZENCallAsyncCompletionBlockOnMainThread`` +- ``ZENCallAsyncContinueBlockOnThreadPool`` +- ``ZENCallAsyncContinueBlockOnMainThread`` +- ``ZENCallFetchResultsBlockOnThreadPool`` +- ``ZENCallFetchResultsBlockOnMainThread`` +- ``ZENCallAsyncCountCompletionBlockOnThreadPool`` +- ``ZENCallAsyncCountCompletionBlockOnMainThread`` +- ``ZENDeliverNotificationOnMainThread`` +- ``ASSERT_MAIN_THREAD`` diff --git a/CoreZen/CoreZen.docc/ZENDatabaseQueue.md b/CoreZen/CoreZen.docc/ZENDatabaseQueue.md new file mode 100644 index 0000000..13c91d5 --- /dev/null +++ b/CoreZen/CoreZen.docc/ZENDatabaseQueue.md @@ -0,0 +1,29 @@ +# ``ZENDatabaseQueue`` + +## Topics + +### Creating a Queue + +- ``databaseQueueWithURL:`` +- ``databaseQueueWithURL:options:`` +- ``databaseQueueInMemory`` +- ``databaseQueueInMemoryWithOptions:`` +- ``ZENDatabaseQueueOptions`` + +### Running Blocks + +- ``transactionAsync:`` +- ``transactionSync:`` +- ``fetchAsync:`` +- ``fetchSync:`` +- ``ZENDatabaseBlock`` + +### Closing the Database + +- ``shutdown`` +- ``shutdown:`` + +### Maintenance and Debugging + +- ``vacuumAsync`` +- ``traceExecution`` diff --git a/CoreZen/CoreZen.docc/ZENObjectRepository.md b/CoreZen/CoreZen.docc/ZENObjectRepository.md new file mode 100644 index 0000000..8df5792 --- /dev/null +++ b/CoreZen/CoreZen.docc/ZENObjectRepository.md @@ -0,0 +1,51 @@ +# ``ZENObjectRepository`` + +## Topics + +### Creating a Repository + +- ``initWithDataModel:tableClass:databaseQueue:domainObjectEmbryo:cacheType:`` +- ``ZENObjectRepositoryCacheType`` + +### Fetching Objects + +- ``fetchAllObjects:`` +- ``fetchAllObjectsForUI:`` +- ``fetchObjectByIdentifier:completion:`` +- ``fetchObjectByIdentifier:uiCompletion:`` +- ``fetchObjectsWithQuery:completion:`` +- ``fetchObjectsWithQuery:uiCompletion:`` +- ``ZENRepositoryQuery`` + +### Counting and Summing + +- ``countAllObjects:`` +- ``countAllObjectsForUI:`` +- ``sumColumn:completion:`` +- ``sumColumn:uiCompletion:`` + +### Saving Objects + +- ``addObject:completion:`` +- ``addObject:uiCompletion:`` +- ``asyncInitAndAdd:completion:`` +- ``asyncInitAndAdd:uiCompletion:`` +- ``updateObject:completion:`` +- ``updateObject:uiCompletion:`` +- ``deleteObject:completion:`` +- ``deleteObject:uiCompletion:`` + +### Saving Several Writes Together + +- ``performWrites:completion:`` +- ``performWrites:uiCompletion:`` +- ``ZENRepositoryWriteBatch`` + +### Observing Changes + +- ``zen_addObserver:selector:`` +- ``zen_removeObserver:`` +- ``ZENObjectRepositoryObjectAddedNotification`` +- ``ZENObjectRepositoryObjectUpdatedNotification`` +- ``ZENObjectRepositoryObjectDeletedNotification`` +- ``ZENObjectRepositoryNotificationObjectKey`` diff --git a/CoreZen/CoreZen.docc/ZENResultSet.md b/CoreZen/CoreZen.docc/ZENResultSet.md new file mode 100644 index 0000000..793e777 --- /dev/null +++ b/CoreZen/CoreZen.docc/ZENResultSet.md @@ -0,0 +1,30 @@ +# ``ZENResultSet`` + +## Topics + +### Moving Through Rows + +- ``next`` +- ``close`` + +### Reading by Column Index + +- ``intForColumnIndex:`` +- ``longLongIntForColumnIndex:`` +- ``unsignedLongLongIntForColumnIndex:`` +- ``doubleForColumnIndex:`` +- ``boolForColumnIndex:`` +- ``stringForColumnIndex:`` +- ``dataForColumnIndex:`` +- ``dateForColumnIndex:`` + +### Reading by Column Name + +- ``intForColumn:`` +- ``longLongIntForColumn:`` +- ``unsignedLongLongIntForColumn:`` +- ``doubleForColumn:`` +- ``boolForColumn:`` +- ``stringForColumn:`` +- ``dataForColumn:`` +- ``dateForColumn:`` diff --git a/CoreZen/CoreZen.h b/CoreZen/CoreZen.h index 054c230..7795a50 100644 --- a/CoreZen/CoreZen.h +++ b/CoreZen/CoreZen.h @@ -7,12 +7,16 @@ #import -// CoreZen's version, such as 0.1.0, is its bundle's CFBundleShortVersionString. -// These two come from Xcode's build number for the framework instead, which -// stays 1 (CURRENT_PROJECT_VERSION). - +/// Xcode's build number for the framework, which stays 1. +/// +/// CoreZen's version, such as 0.1.0, is its bundle's +/// `CFBundleShortVersionString`, not this. FOUNDATION_EXPORT double CoreZenVersionNumber; +/// Xcode's version string for the framework, made from its build number. +/// +/// CoreZen's version, such as 0.1.0, is its bundle's +/// `CFBundleShortVersionString`, not this. FOUNDATION_EXPORT const unsigned char CoreZenVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import diff --git a/CoreZen/Database/DataTransferObject.h b/CoreZen/Database/DataTransferObject.h index 918e775..8a14e49 100644 --- a/CoreZen/Database/DataTransferObject.h +++ b/CoreZen/Database/DataTransferObject.h @@ -10,15 +10,22 @@ NS_ASSUME_NONNULL_BEGIN -// A DTO's values are the properties its subclass declares. Copying one copies -// them all, so a copy can be changed without changing the original, and its -// values put back with takeValuesFromDTO:. +/// One row's values, in the properties a subclass declares. +/// +/// A table class reads rows into data transfer objects (DTOs), and writes DTOs +/// back. Copying a DTO gives a new one with the same property values, which can +/// be changed without changing the original, and put back with +/// ``takeValuesFromDTO:``. Values that are objects are shared, not copied. @interface ZENDataTransferObject : NSObject +/// Makes a DTO with an identifier: a row's, or a new one from +/// ``ZENGetNextObjectIdentifier``. - (instancetype)initWithIdentifier:(ZENIdentifier)identifier; -// Sets every property the subclass declares to dto's value for it. dto must be -// of the same class. Read-only properties are left alone, like the identifier. +/// Sets every property the subclass declares to another DTO's value for it. +/// +/// The other DTO must be of the same class. Read-only properties are left alone, +/// like the identifier. - (void)takeValuesFromDTO:(ZENDataTransferObject *)dto; @end diff --git a/CoreZen/Database/Database.h b/CoreZen/Database/Database.h index 350b5f7..1a117ba 100644 --- a/CoreZen/Database/Database.h +++ b/CoreZen/Database/Database.h @@ -11,38 +11,68 @@ NS_ASSUME_NONNULL_BEGIN -// Why database work didn't save its changes. Each error's description gives the -// details, including SQLite's message when there is one. +/// The domain of the errors that say why database work didn't save its changes. +/// +/// Each error's description gives the details, including SQLite's message when +/// there is one. extern NSErrorDomain const ZENDatabaseErrorDomain; +/// Why database work didn't save its changes. typedef NS_ERROR_ENUM(ZENDatabaseErrorDomain, ZENDatabaseErrorCode){ - // A statement failed, so its transaction rolled back + /// A statement failed, so its transaction rolled back. ZENDatabaseErrorStatementFailed = 1, - // The transaction's block canceled it, so it rolled back + /// The transaction's block canceled it, so it rolled back. ZENDatabaseErrorTransactionCanceled = 2, - // SQLite couldn't commit the transaction, so it rolled back + /// SQLite couldn't commit the transaction, so it rolled back. ZENDatabaseErrorCommitFailed = 3, - // The database couldn't be opened + /// The database couldn't be opened. ZENDatabaseErrorNotOpen = 4, - // A table reported that it couldn't write, though no statement failed + /// A table reported that it couldn't write, though no statement failed. ZENDatabaseErrorWriteFailed = 5, }; +/// A connection to a database, for running statements in the blocks a +/// ``ZENDatabaseQueue`` runs. +/// +/// A statement's `?` placeholders take Objective-C objects, such as `NSString`, +/// `NSNumber`, `NSData`, `NSDate` (stored as seconds since 1970) or `NSNull` +/// for NULL. Use a database only in the block it was passed to. @interface ZENDatabase : NSObject +/// Runs a statement that returns no rows, such as an `INSERT`, with an object +/// for each `?` in it. +/// +/// It returns NO if the statement fails, which in a transaction makes the +/// transaction roll back. - (BOOL)executeUpdate:(NSString *)sql, ...; + +/// Runs a statement that returns no rows, with the objects in an array for its +/// `?` placeholders. +/// +/// It returns NO if the statement fails, which in a transaction makes the +/// transaction roll back. - (BOOL)executeUpdate:(NSString *)sql withArgumentsInArray:(NSArray *)arguments; -// nil if the query fails, which in a transaction makes it roll back +/// Runs a query, with an object for each `?` in it. +/// +/// It returns nil if the query fails, which in a transaction makes the +/// transaction roll back. - (nullable ZENResultSet *)executeQuery:(NSString *)sql, ...; + +/// Runs a query, with the objects in an array for its `?` placeholders. +/// +/// It returns nil if the query fails, which in a transaction makes the +/// transaction roll back. - (nullable ZENResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments; +/// SQLite's message about the most recent statement, which says why it failed. - (NSString *)lastErrorMessage; -// In a transaction block: roll back the transaction's changes when the block -// returns, instead of committing them. Statements the block runs after this -// still run, and roll back too. A transaction also rolls back on its own when -// one of its statements fails. +/// Rolls back the transaction when its block returns, instead of committing it. +/// +/// Call it in a transaction block. Statements the block runs after this still +/// run, and roll back too. A transaction also rolls back on its own when one of +/// its statements fails. - (void)cancelTransaction; @end diff --git a/CoreZen/Database/DatabaseQueue.h b/CoreZen/Database/DatabaseQueue.h index 9916276..969d29f 100644 --- a/CoreZen/Database/DatabaseQueue.h +++ b/CoreZen/Database/DatabaseQueue.h @@ -11,57 +11,106 @@ NS_ASSUME_NONNULL_BEGIN -// database is nil only if the queue couldn't open its database +/// A block that a database queue runs with its database. +/// +/// The database is nil only if the queue couldn't open it. typedef void (^ZENDatabaseBlock)(ZENDatabase *_Nullable database); -// Runs blocks on a database one at a time, in the order they're queued. Every -// block gets the queue's one connection, which opens when a block first needs it -// and closes at shutdown, or when the queue is released. So anything that belongs -// to a connection, like a temporary table, lasts from one block to the next. +/// Runs blocks on a database one at a time, in the order they're queued. +/// +/// Every block gets the queue's one connection, which opens when a block first +/// needs it and closes at shutdown, or when the queue is released. So anything +/// that belongs to a connection, like a temporary table, lasts from one block to +/// the next. Async blocks run on a background thread. @interface ZENDatabaseQueue : NSObject +/// Options for a database queue's connection. typedef NS_OPTIONS(NSUInteger, ZENDatabaseQueueOptions) { - // Enforce the REFERENCES clauses in the database's tables, which SQLite - // ignores unless asked. A change that would leave a row referring to one that - // doesn't exist fails, or does what the clause's ON DELETE or ON UPDATE action - // says. Schema updates run in a transaction, where SQLite can't turn this off, - // so a migration that drops a table other tables refer to, as rebuilding a - // table does, deletes its rows under those rules first. + /// Enforce the `REFERENCES` clauses in the database's tables, which SQLite + /// ignores unless asked. + /// + /// A change that would leave a row referring to one that doesn't exist fails, + /// or does what the clause's `ON DELETE` or `ON UPDATE` action says. Schema + /// updates run in a transaction, where SQLite can't turn this off, so a + /// migration that drops a table other tables refer to, as rebuilding a table + /// does, deletes its rows under those rules first. ZENDatabaseQueueOptionForeignKeys = 1 << 0, }; -// Each in-memory queue has a database of its own, gone once the queue closes it +/// Makes a queue with a new database in memory. +/// +/// Each in-memory queue has a database of its own, gone once the queue closes it. + (instancetype)databaseQueueInMemory; + +/// Makes a queue with a new database in memory, with options. +/// +/// Each in-memory queue has a database of its own, gone once the queue closes it. + (instancetype)databaseQueueInMemoryWithOptions:(ZENDatabaseQueueOptions)options; -// A database file uses SQLite's write-ahead log (WAL), which it keeps in the -// file once switched. A write doesn't wait for other connections' reads, nor -// they for it. A power loss or system crash can undo the last few commits, but -// can't corrupt the database. WAL needs the file on a local volume, and adds two -// more next to it: name-wal and name-shm. Copy or move all three together. Once -// the database closes cleanly, the first alone holds all its data, but after a -// crash, name-wal can hold the latest commits. +/// Makes a queue for the database file at a URL, which it creates if there's +/// none. +/// +/// The file's folder must exist already. A database file uses SQLite's +/// write-ahead log (WAL), which it keeps in the file once switched. A write +/// doesn't wait for other connections' reads, nor they for it. A power loss or +/// system crash can undo the last few commits, but can't corrupt the database. +/// WAL needs the file on a local volume, and adds two more next to it: +/// `name-wal` and `name-shm`. Copy or move all three together. Once the database +/// closes cleanly, the first alone holds all its data, but after a crash, +/// `name-wal` can hold the latest commits. + (instancetype)databaseQueueWithURL:(NSURL *)URL; + +/// Makes a queue for the database file at a URL, with options. +/// +/// Like ``databaseQueueWithURL:``, it creates the file if there's none. + (instancetype)databaseQueueWithURL:(NSURL *)URL options:(ZENDatabaseQueueOptions)options; -// Runs the async blocks already queued, then updateBlock if there is one, then -// closes the database. Calls after this don't run their blocks, and neither does -// a sync call still waiting for its turn on another thread. A second shutdown -// does nothing, and doesn't run its block. +/// Closes the database, once the async blocks already queued have run. +/// +/// Calls after this don't run their blocks, and neither does a sync call still +/// waiting for its turn on another thread. A second shutdown does nothing. - (void)shutdown; + +/// Runs a last block before closing the database, once the async blocks already +/// queued have run. +/// +/// Calls after this don't run their blocks, and neither does a sync call still +/// waiting for its turn on another thread. A second shutdown does nothing, and +/// doesn't run its block. - (void)shutdown:(nullable ZENDatabaseBlock)updateBlock; -// Run a block in a transaction, which commits when the block returns. It rolls -// back instead if any statement in it fails, or if the block calls the -// database's cancelTransaction. +/// Runs a block in a transaction, asynchronously. +/// +/// The transaction commits when the block returns. It rolls back instead if any +/// statement in it fails, or if the block calls the database's +/// ``ZENDatabase/cancelTransaction``. - (void)transactionAsync:(ZENDatabaseBlock)updateBlock; + +/// Runs a block in a transaction, and waits for it to finish. +/// +/// The transaction commits when the block returns. It rolls back instead if any +/// statement in it fails, or if the block calls the database's +/// ``ZENDatabase/cancelTransaction``. - (void)transactionSync:(ZENDatabaseBlock)updateBlock; + +/// Runs a block outside a transaction, asynchronously. +/// +/// Each statement the block runs commits on its own. - (void)fetchAsync:(ZENDatabaseBlock)fetchBlock; + +/// Runs a block outside a transaction, and waits for it to finish. +/// +/// Each statement the block runs commits on its own. - (void)fetchSync:(ZENDatabaseBlock)fetchBlock; + +/// Rebuilds the database file to give back the space deleted rows left, +/// asynchronously. - (void)vacuumAsync; -// Log each SQL statement as it runs. Off by default. A change takes effect from -// the next block the queue runs. +/// Whether to log each SQL statement as it runs. +/// +/// It's off by default. A change takes effect from the next block the queue +/// runs. @property (atomic) BOOL traceExecution; @end diff --git a/CoreZen/Database/DatabaseSchema.h b/CoreZen/Database/DatabaseSchema.h index 85ab61a..9067afa 100644 --- a/CoreZen/Database/DatabaseSchema.h +++ b/CoreZen/Database/DatabaseSchema.h @@ -11,13 +11,25 @@ NS_ASSUME_NONNULL_BEGIN +/// Brings a database up to the latest version of its tables' schemas. +/// +/// The version is one number for the whole database, which SQLite keeps as its +/// `user_version`. To update it, the schema asks every table to make its change +/// for the next version, with ``ZENDatabaseTable/updateSchema:version:``, and +/// repeats until no table has a change for the next version. @interface ZENDatabaseSchema : NSObject +/// Makes a schema for tables, given as classes that conform to +/// ``ZENDatabaseTable``. + (instancetype)schemaWithTableClasses:(NSArray *)tables; -// Updates the schema to the latest version in a transaction, joining the -// caller's if one is open. If any statement fails, the whole update rolls back, -// so it runs again the next time. +/// Updates a database to the latest version, then moves the identifier counter +/// past its largest identifier. +/// +/// The update runs in a transaction, joining the caller's if one is open. If any +/// statement fails, the whole update rolls back, so it runs again the next time. +/// Then it raises the counter that ``ZENGetNextObjectIdentifier`` uses past the +/// largest identifier in any of the tables. - (void)initializeDatabase:(ZENDatabase *)database; @end diff --git a/CoreZen/Database/DatabaseTable.h b/CoreZen/Database/DatabaseTable.h index 5c14112..1473dc0 100644 --- a/CoreZen/Database/DatabaseTable.h +++ b/CoreZen/Database/DatabaseTable.h @@ -15,46 +15,80 @@ NS_ASSUME_NONNULL_BEGIN +/// A class for one table, which creates and migrates the table, and reads and +/// writes its rows as DTOs. +/// +/// A repository makes one instance of its table class, with `new`, and calls it +/// on its database queue. Every table needs an integer column named +/// `identifier`, whose largest value ``ZENDatabaseSchema`` reads. The rows a +/// repository reads, from ``allRows:``, ``rowByIdentifier:database:`` and its +/// query fetches, must have the identifier as their first column: the repository +/// reads it to find an object it already has, without making a DTO. @protocol ZENDatabaseTable #pragma mark - Metadata +/// The table's name in SQL. + (NSString *)tableName; +/// Makes the table's change for a schema version, if it has one. +/// +/// ``ZENDatabaseSchema`` calls this for every table with the version after the +/// database's current one, then the next, for as long as at least one table has +/// a change. Version numbers are shared by every table in a schema. Make the +/// change and return YES if the table has one for this version, or else return +/// NO. The statements run in the schema update's transaction, so if one fails, +/// the whole update rolls back. + (BOOL)updateSchema:(ZENDatabase *)database version:(NSUInteger)version; #pragma mark - Create +/// Inserts a row with a DTO's values. +/// +/// It returns NO if it couldn't. In a repository's write, that rolls back the +/// transaction. - (BOOL)insertDTO:(ZENDataTransferObject *)dto database:(ZENDatabase *)database; #pragma mark - Update +/// Updates the row with a DTO's identifier to the DTO's values. +/// +/// It returns NO if it couldn't. In a repository's write, that rolls back the +/// transaction. - (BOOL)updateDTO:(ZENDataTransferObject *)dto database:(ZENDatabase *)database; #pragma mark - Delete +/// Deletes the row with an identifier. +/// +/// It returns NO if it couldn't. In a repository's write, that rolls back the +/// transaction. - (BOOL)deleteByIdentifier:(ZENIdentifier)identifier database:(ZENDatabase *)database; #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. - +/// Makes a DTO from the current row of a result set. - (ZENDataTransferObject *)dtoFromRow:(ZENResultSet *)row; -// nil if the query fails +/// Every row, with the identifier as the first column. +/// +/// It returns nil if the query fails. - (nullable ZENResultSet *)allRows:(ZENDatabase *)database; +/// The row with an identifier, with the identifier as the first column. +/// +/// It returns nil if the query fails, and a result set with no rows if there's +/// no such row. - (nullable ZENResultSet *)rowByIdentifier:(ZENIdentifier)identifier database:(ZENDatabase *)database; #pragma mark - Count +/// The number of rows. - (NSUInteger)countAllRows:(ZENDatabase *)database; @end diff --git a/CoreZen/Database/ResultSet.h b/CoreZen/Database/ResultSet.h index f1d2969..1b96236 100644 --- a/CoreZen/Database/ResultSet.h +++ b/CoreZen/Database/ResultSet.h @@ -9,33 +9,59 @@ NS_ASSUME_NONNULL_BEGIN +/// The rows a query returned, read one at a time. +/// +/// A result set starts before the first row. Call ``next`` to move to each row +/// in turn, then read the row's values by column index, counting from 0, or by +/// column name. Close it once you're done with it, especially before reading +/// every row, so SQLite can finish the statement. Releasing it closes it too. @interface ZENResultSet : NSObject +/// Moves to the next row. +/// +/// It returns NO once there are no more rows, or if reading the next one fails, +/// which in a transaction makes the transaction roll back. - (BOOL)next; + +/// Closes the result set, which finishes its statement. - (void)close; #pragma mark - By column index -// The object getters return nil for a NULL value - +/// The current row's value in the column at an index, as an `int`. - (int)intForColumnIndex:(int)columnIdx; +/// The current row's value in the column at an index, as a `long long`. - (long long)longLongIntForColumnIndex:(int)columnIdx; +/// The current row's value in the column at an index, as an `unsigned long long`. - (unsigned long long)unsignedLongLongIntForColumnIndex:(int)columnIdx; +/// The current row's value in the column at an index, as a `double`. - (double)doubleForColumnIndex:(int)columnIdx; +/// The current row's value in the column at an index, as a `BOOL`: YES for anything but 0. - (BOOL)boolForColumnIndex:(int)columnIdx; +/// The current row's value in the column at an index, as a string, or nil for NULL. - (nullable NSString *)stringForColumnIndex:(int)columnIdx; +/// The current row's value in the column at an index, as data, or nil for NULL. - (nullable NSData *)dataForColumnIndex:(int)columnIdx; +/// The current row's value in the column at an index, as a date, from a number of seconds since 1970, or nil for NULL. - (nullable NSDate *)dateForColumnIndex:(int)columnIdx; #pragma mark - By column name +/// The current row's value in the column with a name, as an `int`. - (int)intForColumn:(NSString *)columnName; +/// The current row's value in the column with a name, as a `long long`. - (long long)longLongIntForColumn:(NSString *)columnName; +/// The current row's value in the column with a name, as an `unsigned long long`. - (unsigned long long)unsignedLongLongIntForColumn:(NSString *)columnName; +/// The current row's value in the column with a name, as a `double`. - (double)doubleForColumn:(NSString *)columnName; +/// The current row's value in the column with a name, as a `BOOL`: YES for anything but 0. - (BOOL)boolForColumn:(NSString *)columnName; +/// The current row's value in the column with a name, as a string, or nil for NULL. - (nullable NSString *)stringForColumn:(NSString *)columnName; +/// The current row's value in the column with a name, as data, or nil for NULL. - (nullable NSData *)dataForColumn:(NSString *)columnName; +/// The current row's value in the column with a name, as a date, from a number of seconds since 1970, or nil for NULL. - (nullable NSDate *)dateForColumn:(NSString *)columnName; @end diff --git a/CoreZen/Domain/DomainCallbacks.h b/CoreZen/Domain/DomainCallbacks.h index 955bbe6..2626120 100644 --- a/CoreZen/Domain/DomainCallbacks.h +++ b/CoreZen/Domain/DomainCallbacks.h @@ -10,16 +10,19 @@ NS_ASSUME_NONNULL_BEGIN -// Block to return control after async work completes +/// A block called when asynchronous work finishes. typedef void (^ZENAsyncContinueBlock)(void); -// Block to return control after async work completes, with NSError result +/// A block called when asynchronous work finishes, with nil if it succeeded, or +/// else the error. typedef void (^ZENAsyncCompletionBlock)(NSError *_Nullable error); -// Block to return control after fetching results data +/// A block called with the objects a fetch found. +/// +/// A fetch whose query fails calls it with no objects. typedef void (^ZENFetchResultsBlock)(NSArray *fetchedObjects); -// Block to return control after fetching an object count +/// A block called with a count, or a sum. typedef void (^ZENAsyncCountCompletionBlock)(NSUInteger count); NS_ASSUME_NONNULL_END diff --git a/CoreZen/Domain/DomainCommon.h b/CoreZen/Domain/DomainCommon.h index 0ecc1e8..36c65df 100644 --- a/CoreZen/Domain/DomainCommon.h +++ b/CoreZen/Domain/DomainCommon.h @@ -9,7 +9,9 @@ NS_ASSUME_NONNULL_BEGIN -// Convenience macro to confirm threading assumptions +/// Stops the process with an assertion failure unless it's on the main thread. +/// +/// Like any `assert`, it does nothing where `NDEBUG` is defined. #define ASSERT_MAIN_THREAD assert([NSThread isMainThread]) // ======================================== @@ -18,10 +20,14 @@ NS_ASSUME_NONNULL_BEGIN // - void (no params) // ======================================== -// Call a ZENAsyncContinueBlock on a thread pool +/// Calls a block asynchronously, on a background thread, from a global dispatch queue. +/// +/// It does nothing if the block is nil. void ZENCallAsyncContinueBlockOnThreadPool(ZENAsyncContinueBlock _Nullable continueBlock); -// Call a ZENAsyncContinueBlock on the main thread +/// Calls a block asynchronously, on the main thread. +/// +/// It does nothing if the block is nil. void ZENCallAsyncContinueBlockOnMainThread(ZENAsyncContinueBlock _Nullable continueBlock); // ======================================== @@ -30,10 +36,14 @@ void ZENCallAsyncContinueBlockOnMainThread(ZENAsyncContinueBlock _Nullable conti // - NSError* error // ======================================== -// Call a ZENAsyncCompletionBlock on a thread pool +/// Calls a block, with an error asynchronously, on a background thread, from a global dispatch queue. +/// +/// It does nothing if the block is nil. void ZENCallAsyncCompletionBlockOnThreadPool(ZENAsyncCompletionBlock _Nullable completionBlock, NSError *_Nullable error); -// Call a ZENAsyncCompletionBlock on the main thread +/// Calls a block, with an error asynchronously, on the main thread. +/// +/// It does nothing if the block is nil. void ZENCallAsyncCompletionBlockOnMainThread(ZENAsyncCompletionBlock _Nullable completionBlock, NSError *_Nullable error); // ======================================== @@ -42,10 +52,14 @@ void ZENCallAsyncCompletionBlockOnMainThread(ZENAsyncCompletionBlock _Nullable c // - NSArray* fetchedObjects // ======================================== -// Call a ZENFetchResultsBlock on a thread pool +/// Calls a block, with objects asynchronously, on a background thread, from a global dispatch queue. +/// +/// It does nothing if the block is nil. void ZENCallFetchResultsBlockOnThreadPool(ZENFetchResultsBlock _Nullable fetchResultsBlock, NSArray *fetchedObjects); -// Call a ZENFetchResultsBlock on the main thread +/// Calls a block, with objects asynchronously, on the main thread. +/// +/// It does nothing if the block is nil. void ZENCallFetchResultsBlockOnMainThread(ZENFetchResultsBlock _Nullable fetchResultsBlock, NSArray *fetchedObjects); // ======================================== @@ -54,17 +68,24 @@ void ZENCallFetchResultsBlockOnMainThread(ZENFetchResultsBlock _Nullable fetchRe // - NSUInteger count // ======================================== -// Call a ZENAsyncCountCompletionBlock on a thread pool +/// Calls a block, with a count asynchronously, on a background thread, from a global dispatch queue. +/// +/// It does nothing if the block is nil. void ZENCallAsyncCountCompletionBlockOnThreadPool(ZENAsyncCountCompletionBlock _Nullable countBlock, NSUInteger count); -// Call a ZENAsyncCountCompletionBlock on the main thread +/// Calls a block, with a count asynchronously, on the main thread. +/// +/// It does nothing if the block is nil. void ZENCallAsyncCountCompletionBlockOnMainThread(ZENAsyncCountCompletionBlock _Nullable countBlock, NSUInteger count); // ======================================== // Notifications // ======================================== -// Deliver a notification on the main thread +/// Posts a notification from the default notification center, asynchronously, +/// on the main thread. +/// +/// The sender is the notification's object, and userData its user info. void ZENDeliverNotificationOnMainThread(NSString *notification, id _Nullable sender, NSDictionary *_Nullable userData); NS_ASSUME_NONNULL_END diff --git a/CoreZen/Domain/DomainObject.h b/CoreZen/Domain/DomainObject.h index 4ea4985..b1828d3 100644 --- a/CoreZen/Domain/DomainObject.h +++ b/CoreZen/Domain/DomainObject.h @@ -12,50 +12,83 @@ NS_ASSUME_NONNULL_BEGIN +/// The object a repository passes to the async init of each of its objects. +/// +/// It's usually the app's model, so an object can find the objects it relates +/// to. The protocol has no requirements. @protocol ZENDataModel @end +/// The methods a repository needs from the objects it makes from its table's +/// rows. +/// +/// A repository's objects are usually subclasses of ``ZENDomainObject-c.class``, +/// which conforms to it. @protocol ZENDomainObject +/// Makes an object from a row's DTO. - (instancetype)initWithDTO:(ZENDataTransferObject *)dto; -// Allows object to perform async initialization. Called from thread pool. Call -// completion with nil when initialization succeeds, or with an error when it -// fails. A repository leaves an object whose init failed out of fetch results -// and drops it from its cache, and asyncInitAndAdd: doesn't add it. +/// Finishes setting up the object, asynchronously, after it's made. +/// +/// A repository calls this on a background thread, once, when it first makes +/// the object from the database, and delivers the object to fetches only after +/// it completes. Call completion with nil when initialization succeeds, or with +/// an error when it fails. A repository leaves an object whose init failed out +/// of fetch results and drops it from its cache, and +/// ``ZENObjectRepository/asyncInitAndAdd:completion:`` doesn't add it. - (void)performAsyncInit:(nullable id)model completion:(ZENAsyncCompletionBlock)completion; @end +/// An object built around a DTO, which holds its stored values. +/// +/// Subclass it for each kind of object a repository stores. A subclass adds what +/// the app needs beyond the stored values, and can override +/// ``performAsyncInit:completion:`` to finish setting itself up, such as by +/// checking a file on disk, reading media metadata or fetching related objects. @interface ZENDomainObject : NSObject -// nil only in a subclass that starts without one and sets it later +/// The DTO with the object's stored values. +/// +/// It's nil only in a subclass that starts without one and sets it later. @property (nonatomic, strong, readonly, nullable) ZENDataTransferObject *basicDTO; +/// Makes an object around a DTO, which becomes its ``basicDTO``. - (instancetype)initWithDTO:(ZENDataTransferObject *)dto; +/// Finishes setting up the object, asynchronously, after it's made. +/// +/// By default it calls completion with nil right away. A subclass that has more +/// to do overrides it, and calls completion with nil when it's done, or with an +/// error if it fails. - (void)performAsyncInit:(nullable id)model completion:(ZENAsyncCompletionBlock)completion; -// Called once a repository has saved a change to the object's DTO: after an -// update in a write batch has put its values in, or after updateObject: has -// saved the object. An object that keeps state worked out from its DTO brings -// it up to date here. It runs on the database queue, before observers are told -// about the change, so it should be quick. Does nothing by default. +/// Called once a repository has saved a change to the object's DTO. +/// +/// It's called after an update in a write batch has put its values in, or after +/// ``ZENObjectRepository/updateObject:completion:`` has saved the object. An +/// object that keeps state worked out from its DTO brings it up to date here. +/// It runs on the database queue, before observers are told about the change, so +/// it should be quick. It does nothing by default. - (void)didUpdateDTO; -// Calls performAsyncInit on a thread pool for each of the objects, -// then completion block after, also on thread pool. Only the first call to -// each object's performAsyncInit completion counts; later calls are ignored. -// Completion gets nil if every object's init succeeded, or else one of the -// errors the objects reported. +/// Runs the async init of several objects at once. +/// +/// It calls each object's ``performAsyncInit:completion:`` on a background +/// thread, then calls completion on a background thread once they've all +/// finished. Only the first call to each object's completion counts; later +/// calls are ignored. Completion gets nil if every object's init succeeded, or +/// else one of the errors the objects reported. + (void)asyncInit:(NSArray *)objects model:(nullable id)model completion:(nullable ZENAsyncCompletionBlock)completion; #pragma mark - ZENIdentifier protocol +/// The identifier of the object's ``basicDTO``. - (ZENIdentifier)identifier; @end diff --git a/CoreZen/Domain/ObjectRepository.h b/CoreZen/Domain/ObjectRepository.h index 73db109..89bf9e9 100644 --- a/CoreZen/Domain/ObjectRepository.h +++ b/CoreZen/Domain/ObjectRepository.h @@ -17,20 +17,68 @@ 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. +/// A block that returns the rows for a repository's 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); +/// How a repository's cache holds its objects. typedef enum : NSUInteger { + /// The cache holds an object only while something else holds it too. A + /// fetch after it's released makes a new one from its row. ZENObjectRepositoryCacheType_Weak = 0, + /// The cache holds every object the repository has loaded or added, until + /// it's deleted. ZENObjectRepositoryCacheType_Strong = 1 } ZENObjectRepositoryCacheType; +/// Loads, caches and saves the objects stored in one table, asynchronously. +/// +/// A repository combines a table class, a database queue and a cache. The cache +/// holds one object for each identifier, so every part of an app sees the same +/// one. +/// +/// Every method is asynchronous. Each has two forms: one calls its block on a +/// background thread, and the other, named with `uiCompletion:` or `ForUI`, +/// calls it on the main thread. +/// +/// ### Fetching +/// +/// 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 ``ZENDomainObject-c.protocol/performAsyncInit:completion:`` runs +/// once, when the repository first creates it from the database; objects already +/// in the cache aren't initialized again. An object whose async init fails is +/// left out of the results and dropped from the cache, so a later fetch creates +/// it again and retries its init. A fetch whose query fails delivers no objects. +/// +/// ### Saving +/// +/// Each add, update or delete is a transaction of its own. Its completion gets +/// nil once the change is saved, or an error in ``ZENDatabaseErrorDomain`` when +/// it was rolled back or never made. Only a saved change updates the cache and +/// posts its notification. A failed update leaves the object's own properties as +/// the caller set them. To save several writes in one transaction, use +/// ``performWrites:completion:``. @interface ZENObjectRepository : NSObject #pragma mark - Init +/// Makes a repository for the objects stored in one table. +/// +/// - Parameters: +/// - dataModel: The object the repository passes to each object's async init, +/// such as the app's model. +/// - tableClass: The table's class. The repository makes one instance of it. +/// - databaseQueue: The queue for the database the table is in. +/// - embryo: The class of the repository's objects, which it makes from DTOs +/// with ``ZENDomainObject-c.protocol/initWithDTO:``. +/// - cacheType: Whether the repository's cache holds its objects weakly or +/// strongly. - (instancetype)initWithDataModel:(nullable id)dataModel tableClass:(Class)tableClass databaseQueue:(ZENDatabaseQueue *)databaseQueue @@ -39,167 +87,222 @@ typedef enum : NSUInteger { #pragma mark - Count -// Runs asynchronously. Completion block happens on a thread pool. +/// Counts the objects in the table, and calls a block with the count on a background thread. - (void)countAllObjects:(ZENAsyncCountCompletionBlock)countBlock; -// Same as above, but resultsBlock happens on the main thread. +/// Counts the objects in the table, and calls a block with the count on the main thread. - (void)countAllObjectsForUI:(ZENAsyncCountCompletionBlock)countBlock; #pragma mark - Sum -// Sum of an integer column over all objects, or 0 if there are none. columnName -// goes into the SQL as is, so it must be a column of this repository's table -// named in code, never user input. Runs asynchronously. Completion block -// happens on a thread pool. +/// Adds up an integer column over all the objects, and calls a block with the sum +/// on a background thread. +/// +/// The sum is 0 if there are no objects. The column name goes into the SQL as +/// is, so it must be a column of this repository's table named in code, never +/// user input. - (void)sumColumn:(NSString *)columnName completion:(ZENAsyncCountCompletionBlock)sumBlock; -// Same as above, but uiCompletion block happens on the main thread. +/// Adds up an integer column over all the objects, and calls a block with the sum +/// on the main thread. +/// +/// Like ``sumColumn:completion:``, the column name must be named in code, never +/// user input. - (void)sumColumn:(NSString *)columnName uiCompletion:(ZENAsyncCountCompletionBlock)sumBlock; #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. -// An object whose async init fails is left out of the results and dropped from -// the cache, so a later fetch creates it again and retries its init. +// Fetches deliver objects only once their async init has finished. The class +// documentation above says more. -// Runs asynchronously. Result callback block happens on a thread pool. +/// Fetches the object with an identifier, and calls a block on a background thread with an +/// array of it, or an empty array if there's none. - (void)fetchObjectByIdentifier:(ZENIdentifier)identifier completion:(ZENFetchResultsBlock)resultsBlock; -// Same as above, but uiCompletion block happens on the main thread. +/// Fetches the object with an identifier, and calls a block on the main thread with an +/// array of it, or an empty array if there's none. - (void)fetchObjectByIdentifier:(ZENIdentifier)identifier uiCompletion:(ZENFetchResultsBlock)resultsBlock; -// Runs asynchronously. Result callback block happens on a thread pool. +/// Fetches every object in the table, and calls a block with them on a background thread. - (void)fetchAllObjects:(ZENFetchResultsBlock)resultsBlock; -// Same as above, but resultsBlock happens on the main thread. +/// Fetches every object in the table, and calls a block with them 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. +/// Fetches the objects in the rows a query returns, and calls a block with them +/// on a background thread. +/// +/// The query can find the objects that match a condition, for example, and they +/// come in the order of their rows. Each object comes once, at its first row. +/// The rows need the columns the table's ``ZENDatabaseTable/dtoFromRow:`` reads, +/// identifier first, as ``ZENDatabaseTable/allRows:`` returns them. A failed +/// query fetches no objects. With a table class that has a +/// `rowsInFolder:database:` method, for example: +/// +/// ```objc +/// [repository fetchObjectsWithQuery:^ZENResultSet *(MyTable *table, ZENDatabase *database) { +/// return [table rowsInFolder:folder database:database]; +/// } completion:^(NSArray *fetchedObjects) { ... }]; +/// ``` - (void)fetchObjectsWithQuery:(ZENRepositoryQuery)query completion:(ZENFetchResultsBlock)resultsBlock; -// Same as above, but uiCompletion block happens on the main thread. +/// Fetches the objects in the rows a query returns, and calls a block with them +/// on the main thread. +/// +/// The query works as it does for ``fetchObjectsWithQuery:completion:``. - (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 -// is saved, or an error (in ZENDatabaseErrorDomain) when it was rolled back or -// never made. Only a saved change updates the cache and posts its notification. -// The completion may be nil. -// A failed update leaves the object's own properties as the caller set them. +// Each write is a transaction of its own. The class documentation above says +// more. -// Runs asynchronously. Completion block happens on a thread pool. +/// Saves a new object, then calls a block on a background thread with nil, or the error. +/// +/// Once the object is saved, the repository caches it and posts +/// ``ZENObjectRepositoryObjectAddedNotification``. - (void)addObject:(ZENDomainObject *)domainObject completion:(ZENAsyncCompletionBlock)completion; -// Same as above, but uiCompletion block happens on the main thread. +/// Saves a new object, then calls a block on the main thread with nil, or the error. +/// +/// Once the object is saved, the repository caches it and posts +/// ``ZENObjectRepositoryObjectAddedNotification``. - (void)addObject:(ZENDomainObject *)domainObject uiCompletion:(ZENAsyncCompletionBlock)completion; -// Helper method to call DomainObject +asyncInit: on object before -// adding to repository. If the object's async init fails, it isn't added, and -// completion gets the error; so does a failed add. Completion block happens on -// a thread pool. +/// Runs a new object's async init, then saves it, then calls a block on a background thread +/// with nil, or the error. +/// +/// If the object's async init fails, it isn't saved, and the block gets the +/// init's error. - (void)asyncInitAndAdd:(ZENDomainObject *)domainObject completion:(ZENAsyncCompletionBlock)completion; -// Same as above, but uiCompletion block happens on the main thread. +/// Runs a new object's async init, then saves it, then calls a block on the main thread +/// with nil, or the error. +/// +/// If the object's async init fails, it isn't saved, and the block gets the +/// init's error. - (void)asyncInitAndAdd:(ZENDomainObject *)domainObject uiCompletion:(ZENAsyncCompletionBlock)completion; -// Runs asynchronously. Completion block happens on a thread pool. +/// Saves the values in an object's DTO, then calls a block on a background thread with nil, +/// or the error. +/// +/// Once the change is saved, the object's ``ZENDomainObject-c.class/didUpdateDTO`` +/// runs, and the repository posts ``ZENObjectRepositoryObjectUpdatedNotification``. - (void)updateObject:(ZENDomainObject *)domainObject completion:(ZENAsyncCompletionBlock)completion; -// Same as above, but uiCompletion block happens on the main thread. +/// Saves the values in an object's DTO, then calls a block on the main thread with nil, +/// or the error. +/// +/// Once the change is saved, the object's ``ZENDomainObject-c.class/didUpdateDTO`` +/// runs, and the repository posts ``ZENObjectRepositoryObjectUpdatedNotification``. - (void)updateObject:(ZENDomainObject *)domainObject uiCompletion:(ZENAsyncCompletionBlock)completion; -// Runs asynchronously. Completion block happens on a thread pool. +/// Deletes an object, then calls a block on a background thread with nil, or the error. +/// +/// Once the deletion is saved, the object leaves the cache, and the repository +/// posts ``ZENObjectRepositoryObjectDeletedNotification``. - (void)deleteObject:(ZENDomainObject *)domainObject completion:(ZENAsyncCompletionBlock)completion; -// Same as above, but uiCompletion block happens on the main thread. +/// Deletes an object, then calls a block on the main thread with nil, or the error. +/// +/// Once the deletion is saved, the object leaves the cache, and the repository +/// posts ``ZENObjectRepositoryObjectDeletedNotification``. - (void)deleteObject:(ZENDomainObject *)domainObject uiCompletion:(ZENAsyncCompletionBlock)completion; #pragma mark - Write Batches -// Saves several writes, to objects in one or more repositories, in one -// transaction. build stages them on the calling thread, before this returns. -// Completion gets nil once they're all saved: each repository has updated its -// cache and posted its notifications, in the order the writes were staged. Or it -// gets an error (in ZENDatabaseErrorDomain), and nothing has changed, in the -// database or in memory. Every repository in a batch must share one database -// queue. The completion may be nil. Completion block happens on a thread pool. +/// Saves several writes, to objects in one or more repositories, in one +/// transaction, then calls a block on a background thread with nil, or the error. +/// +/// The build block stages the writes in a batch, on the calling thread, before +/// this returns. Completion gets nil once they're all saved: each repository has +/// updated its cache and posted its notifications, in the order the writes were +/// staged. Or it gets an error in ``ZENDatabaseErrorDomain``, and nothing has +/// changed, in the database or in memory. Every repository in a batch must share +/// one database queue. The completion may be nil. + (void)performWrites:(void(NS_NOESCAPE ^)(ZENRepositoryWriteBatch *batch))build completion:(nullable ZENAsyncCompletionBlock)completion; -// Same as above, but uiCompletion block happens on the main thread. +/// Saves several writes in one transaction, then calls a block on the main thread with +/// nil, or the error. +/// +/// The writes work as they do for ``performWrites:completion:``. + (void)performWrites:(void(NS_NOESCAPE ^)(ZENRepositoryWriteBatch *batch))build uiCompletion:(nullable ZENAsyncCompletionBlock)completion; #pragma mark - Notifications -// Notifications are delivered on the main thread +/// Registers an observer for the repository's added, updated and deleted +/// notifications. +/// +/// The notifications arrive on the main thread, and the selector gets each one +/// as its argument. - (void)zen_addObserver:(id)observer selector:(SEL)selector; +/// Removes an observer from the repository's notifications. - (void)zen_removeObserver:(id)observer; @end -// The writes for one +[ZENObjectRepository performWrites:completion:]. Stage at -// most one write for each object; a second one makes the batch fail. +/// The writes for one ``ZENObjectRepository/performWrites:completion:``. +/// +/// Stage at most one write for each object; a second one makes the batch fail. @interface ZENRepositoryWriteBatch : NSObject - (instancetype)init NS_UNAVAILABLE; -// Adds an object that's initialized already: its async init, if it has one, is -// done. Once saved, the repository caches it and posts it as added. +/// Adds an object that's initialized already: its async init, if it has one, +/// is done. +/// +/// Once saved, the repository caches it and posts it as added. - (void)addObject:(ZENDomainObject *)domainObject toRepository:(ZENObjectRepository *)repository; -// Updates the object with this identifier, whether or not it's loaded. change -// gets a copy of its DTO to change: the loaded object's, or else one read from -// the database. It runs on the database queue, inside the transaction. Once -// saved, a loaded object's DTO takes the copy's values, its didUpdateDTO runs, -// and the repository posts it as updated. One that isn't loaded is only changed -// in the database. An identifier with no object makes the batch fail. +/// Updates the object with an identifier, whether or not it's loaded. +/// +/// The change block gets a copy of the object's DTO to change: the loaded +/// object's, or else one read from the database. It runs on the database queue, +/// inside the transaction. Once saved, a loaded object's DTO takes the copy's +/// values, its ``ZENDomainObject-c.class/didUpdateDTO`` runs, and the repository +/// posts it as updated. One that isn't loaded is only changed in the database. +/// An identifier with no object makes the batch fail. - (void)updateObjectWithIdentifier:(ZENIdentifier)identifier inRepository:(ZENObjectRepository *)repository change:(void (^)(__kindof ZENDataTransferObject *dto))change; -// Deletes the object with this identifier. Once saved, a loaded object leaves -// the cache, and the repository posts it as deleted. +/// Deletes the object with an identifier. +/// +/// Once saved, a loaded object leaves the cache, and the repository posts it as +/// deleted. - (void)deleteObjectWithIdentifier:(ZENIdentifier)identifier fromRepository:(ZENObjectRepository *)repository; @end +/// The key in a repository notification's user info for the object it's about. extern NSString *const ZENObjectRepositoryNotificationObjectKey; +/// Posted on the main thread after a repository saves a new object. extern NSString *const ZENObjectRepositoryObjectAddedNotification; + +/// Posted on the main thread after a repository saves a change to an object. extern NSString *const ZENObjectRepositoryObjectUpdatedNotification; + +/// Posted on the main thread after a repository deletes an object. extern NSString *const ZENObjectRepositoryObjectDeletedNotification; NS_ASSUME_NONNULL_END diff --git a/CoreZen/Identifier/Identifiable.h b/CoreZen/Identifier/Identifiable.h index 0973b7e..a967e03 100644 --- a/CoreZen/Identifier/Identifiable.h +++ b/CoreZen/Identifier/Identifiable.h @@ -9,8 +9,10 @@ @import Foundation; +/// An object with an identifier. @protocol ZENIdentifiable +/// The object's identifier. @property (nonatomic, readonly) ZENIdentifier identifier; @end diff --git a/CoreZen/Identifier/Identifier.h b/CoreZen/Identifier/Identifier.h index 9b52c6f..a72d150 100644 --- a/CoreZen/Identifier/Identifier.h +++ b/CoreZen/Identifier/Identifier.h @@ -7,6 +7,11 @@ #import +/// A 64-bit integer that identifies a stored object. +/// +/// Identifiers come from ``ZENGetNextObjectIdentifier``, so each is unique across +/// every table in every database the process opens. typedef int64_t ZENIdentifier; +/// The value for no identifier. static const ZENIdentifier ZENInvalidIdentifier = -1; diff --git a/CoreZen/Identifier/ObjectIdentifier.h b/CoreZen/Identifier/ObjectIdentifier.h index 575fcf7..4d3d393 100644 --- a/CoreZen/Identifier/ObjectIdentifier.h +++ b/CoreZen/Identifier/ObjectIdentifier.h @@ -9,15 +9,17 @@ @import Foundation; -// Identifiers come from one counter for the whole process, shared by every table, -// so each is unique across every database the process opens. ZENDatabaseSchema -// moves the counter past the largest identifier in each database it initializes, -// and never moves it back. - -// Hands out the next identifier +/// Hands out the next identifier. +/// +/// Identifiers come from one counter for the whole process, shared by every +/// table, so each is unique across every database the process opens. The first +/// is 1. ``ZENDatabaseSchema`` moves the counter past the largest identifier in +/// each database it initializes, and never moves it back. Any thread can call +/// this. ZENIdentifier ZENGetNextObjectIdentifier(void); -// Sets the counter so the next identifier is identifier + 1, even if that moves -// it back to identifiers already handed out. For tests that want predictable -// identifiers; everything else should raise the counter instead. +/// Sets the counter so the next identifier is one more than this one. +/// +/// It sets the counter even if that moves it back to identifiers already handed +/// out, so it's only for tests that want predictable identifiers. void ZENSetLargestObjectIdentifier(ZENIdentifier identifier); diff --git a/README.md b/README.md index 24bebed..6e28d34 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,10 @@ Scripts/coverage_report.py build/Tests.xcresult After ⌘U, Xcode's Report navigator shows it line by line. +### Documentation + +The public headers document the API in `///` comments, which Xcode shows in Quick Help when you Option-click a name. Product > Build Documentation builds them into Xcode's documentation window, with the articles in `CoreZen/CoreZen.docc`. From the command line, `xcodebuild docbuild -scheme CoreZen -project CoreZen.xcodeproj` builds `CoreZen.doccarchive`, which opens in Xcode. CI builds the documentation too, and fails on a DocC warning, such as a link to a symbol that doesn't exist. + ### Versions CoreZen follows [Semantic Versioning](https://semver.org). Each release is a git tag such as `v0.1.0`, with a [GitHub release](https://github.com/znelson/CoreZen/releases) whose notes come from [`CHANGELOG.md`](https://github.com/znelson/CoreZen/blob/main/CHANGELOG.md). Until 1.0.0, a release that breaks the API raises the middle number (0.1.0 to 0.2.0), and any other release raises the last (0.1.0 to 0.1.1). At run time, the framework bundle's `CFBundleShortVersionString` is its version.