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
20 changes: 20 additions & 0 deletions CoreZen/Database/DatabaseQueue.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,29 @@ typedef void (^ZENDatabaseBlock)(ZENDatabase *_Nullable database);
// to a connection, like a temporary table, lasts from one block to the next.
@interface ZENDatabaseQueue : NSObject

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.
ZENDatabaseQueueOptionForeignKeys = 1 << 0,
};

// Each in-memory queue has a database of its own, gone once the queue closes it
+ (instancetype)databaseQueueInMemory;
+ (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.
+ (instancetype)databaseQueueWithURL:(NSURL *)URL;
+ (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
Expand Down
56 changes: 48 additions & 8 deletions CoreZen/Database/DatabaseQueue.m
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

#import "DatabaseQueue+Private.h"
#import "Database+Private.h"
#import "ResultSet.h"
#import "WorkQueue.h"

#import <stdatomic.h>
Expand All @@ -24,14 +25,16 @@ @interface ZENDatabaseQueue () {
}

- (void)internalInit:(NSString *)queueLabel;
- (instancetype)initInMemory;
- (instancetype)initWithURL:(NSURL *)URL;
- (instancetype)initInMemoryWithOptions:(ZENDatabaseQueueOptions)options;
- (instancetype)initWithURL:(NSURL *)URL options:(ZENDatabaseQueueOptions)options;
- (ZENDatabase *)database;
- (void)configureDatabase:(ZENDatabase *)database;
- (void)closeDatabase;
- (NSError *)runTransaction:(ZENDatabaseBlock)updateBlock;
- (void)runAsync:(ZENWorkQueueBlock)work;

@property (nonatomic, strong, readonly) NSURL *databaseURL;
@property (nonatomic, readonly) ZENDatabaseQueueOptions options;
@property (nonatomic, strong, readonly) ZENWorkQueue *workQueue;

@end
Expand All @@ -42,11 +45,12 @@ - (void)internalInit:(NSString *)queueLabel {
_workQueue = [ZENWorkQueue workQueue:queueLabel];
}

- (instancetype)initInMemory {
- (instancetype)initInMemoryWithOptions:(ZENDatabaseQueueOptions)options {
self = [super init];
if (self) {
NSLog(@"Database in memory");
_databaseURL = nil;
_options = options;

static atomic_uint_fast64_t nextIdentifier = 0;
uint64_t queueID = atomic_fetch_add(&nextIdentifier, 1);
Expand All @@ -58,14 +62,19 @@ - (instancetype)initInMemory {
}

+ (instancetype)databaseQueueInMemory {
return [[ZENDatabaseQueue alloc] initInMemory];
return [self databaseQueueInMemoryWithOptions:0];
}

- (instancetype)initWithURL:(NSURL *)URL {
+ (instancetype)databaseQueueInMemoryWithOptions:(ZENDatabaseQueueOptions)options {
return [[ZENDatabaseQueue alloc] initInMemoryWithOptions:options];
}

- (instancetype)initWithURL:(NSURL *)URL options:(ZENDatabaseQueueOptions)options {
self = [super init];
if (self) {
NSLog(@"Database at: %@", URL);
_databaseURL = URL;
_options = options;

NSString *queueLabel = [NSString stringWithFormat:@"ZENDatabaseQueue-%@", [URL lastPathComponent]];
[self internalInit:queueLabel];
Expand All @@ -74,7 +83,11 @@ - (instancetype)initWithURL:(NSURL *)URL {
}

+ (instancetype)databaseQueueWithURL:(NSURL *)URL {
return [[ZENDatabaseQueue alloc] initWithURL:URL];
return [self databaseQueueWithURL:URL options:0];
}

+ (instancetype)databaseQueueWithURL:(NSURL *)URL options:(ZENDatabaseQueueOptions)options {
return [[ZENDatabaseQueue alloc] initWithURL:URL options:options];
}

- (void)shutdown {
Expand Down Expand Up @@ -124,8 +137,7 @@ - (ZENDatabase *)database {
}

_database = [ZENDatabase databaseWithFMDatabase:fmdb];
[_database executeUpdate:@"PRAGMA synchronous = 1;"];
[_database setShouldCacheStatements:YES];
[self configureDatabase:_database];
}

// Set every time, so a change reaches a database opened before it
Expand All @@ -134,6 +146,34 @@ - (ZENDatabase *)database {
return _database;
}

// Runs once, as the connection opens. That's before any transaction begins, which
// matters: inside one, SQLite ignores changes to the journal mode and foreign keys.
- (void)configureDatabase:(ZENDatabase *)database {
// In-memory databases have no file to keep a log next to
if (self.databaseURL) {
// The mode is kept in the file, so this changes it only the first time
ZENResultSet *rs = [database executeQuery:@"PRAGMA journal_mode = WAL;"];
NSString *mode = [rs next] ? [rs stringForColumnIndex:0] : nil;
[rs close];
if (![mode isEqualToString:@"wal"]) {
NSLog(@"WARNING: %@ couldn't switch to a write-ahead log, so it keeps its %@ journal",
self.databaseURL.lastPathComponent, mode ?: @"current");
}
}

// With the write-ahead log, NORMAL syncs at checkpoints rather than every
// commit. A power loss can then undo the last commits, but SQLite's
// documentation says it can't corrupt the database. With the rollback journal
// it only calls NORMAL "probably" safe, on modern filesystems.
[database executeUpdate:@"PRAGMA synchronous = NORMAL;"];

if (self.options & ZENDatabaseQueueOptionForeignKeys) {
[database executeUpdate:@"PRAGMA foreign_keys = ON;"];
}

[database setShouldCacheStatements:YES];
}

// Runs on the work queue, last. Releasing the queue without shutting it down also
// closes the database, when the ZENDatabase deallocates.
- (void)closeDatabase {
Expand Down
105 changes: 105 additions & 0 deletions CoreZenTests/DatabaseTests.m
Original file line number Diff line number Diff line change
Expand Up @@ -783,6 +783,111 @@ - (void)testShutdownWithoutBlockRunsWorkQueuedBeforeIt {
[reopened shutdown];
}

#pragma mark - Write-Ahead Log

// The value a pragma reports on the queue's connection
- (NSString *)valueOfPragma:(NSString *)pragma onQueue:(ZENDatabaseQueue *)queue {
__block NSString *value = nil;
[queue fetchSync:^(ZENDatabase *database) {
ZENResultSet *rs = [database executeQuery:[NSString stringWithFormat:@"PRAGMA %@;", pragma]];
value = [rs next] ? [rs stringForColumnIndex:0] : nil;
[rs close];
}];
return value;
}

- (void)testDatabaseFileUsesWriteAheadLog {
ZENDatabaseQueue *queue = [ZENDatabaseQueue databaseQueueWithURL:[self temporaryDatabaseURL]];
XCTAssertEqualObjects([self valueOfPragma:@"journal_mode" onQueue:queue], @"wal");
XCTAssertEqualObjects([self valueOfPragma:@"synchronous" onQueue:queue], @"1", @"synchronous should be NORMAL");
[queue shutdown];
}

- (void)testWriteSavesWhileAnotherConnectionReads {
NSURL *URL = [self temporaryDatabaseURL];
ZENDatabaseQueue *writer = [ZENDatabaseQueue databaseQueueWithURL:URL];
ZENDatabaseQueue *reader = [ZENDatabaseQueue databaseQueueWithURL:URL];
ZENDatabaseSchema *schema = [ZENDatabaseSchema schemaWithTableClasses:@[[ZENTestTable class]]];
[writer transactionSync:^(ZENDatabase *database) {
[schema initializeDatabase:database];
XCTAssertTrue([self insertRowNamed:@"Alpha" database:database]);
}];

// The reader stops partway through a query, which keeps its read going, until
// the writer has finished
dispatch_semaphore_t reading = dispatch_semaphore_create(0);
dispatch_semaphore_t written = dispatch_semaphore_create(0);
XCTestExpectation *readFinished = [self expectationWithDescription:@"read finished"];
[reader fetchAsync:^(ZENDatabase *database) {
ZENResultSet *rs = [database executeQuery:@"SELECT name FROM test_objects;"];
XCTAssertTrue([rs next]);
dispatch_semaphore_signal(reading);
dispatch_semaphore_wait(written, dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC));
// A read sees the database as it was when the read began
XCTAssertFalse([rs next]);
[rs close];
[readFinished fulfill];
}];
XCTAssertEqual(dispatch_semaphore_wait(reading, dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC)), 0);

NSError *error = [self resultOfTransaction:^(ZENDatabase *database) {
XCTAssertTrue([self insertRowNamed:@"Beta" database:database]);
}
onQueue:writer];
dispatch_semaphore_signal(written);
[self waitForExpectations:@[readFinished] timeout:5.0];
XCTAssertNil(error, @"The write should save while the other connection reads");

// The reader's next read sees it
[reader fetchSync:^(ZENDatabase *database) {
XCTAssertEqual([self countRowsInTable:@"test_objects" database:database], 2);
}];
[writer shutdown];
[reader shutdown];
}

- (void)testInMemoryDatabaseKeepsItsJournal {
// An in-memory database can't have a write-ahead log, and doesn't need one
ZENDatabaseQueue *queue = [ZENDatabaseQueue databaseQueueInMemory];
XCTAssertEqualObjects([self valueOfPragma:@"journal_mode" onQueue:queue], @"memory");
[queue shutdown];
}

#pragma mark - Foreign Keys

// Makes a table whose rows refer to rows of another, and adds one that refers to
// a row that isn't there, all in the queue's first transaction. Returns its result.
- (NSError *)addRowWithMissingReferenceOnQueue:(ZENDatabaseQueue *)queue {
return [self resultOfTransaction:^(ZENDatabase *database) {
XCTAssertTrue([database executeUpdate:@"CREATE TABLE parents (identifier INTEGER PRIMARY KEY);"]);
XCTAssertTrue([database executeUpdate:@"CREATE TABLE children (parent INTEGER REFERENCES parents (identifier));"]);
[database executeUpdate:@"INSERT INTO children VALUES (1);"];
}
onQueue:queue];
}

- (void)testForeignKeysAreEnforcedWhenAskedFor {
ZENDatabaseQueue *queue = [ZENDatabaseQueue databaseQueueInMemoryWithOptions:ZENDatabaseQueueOptionForeignKeys];
NSError *error = [self addRowWithMissingReferenceOnQueue:queue];
XCTAssertEqualObjects(error.domain, ZENDatabaseErrorDomain);
XCTAssertEqual(error.code, ZENDatabaseErrorStatementFailed);
XCTAssertTrue([error.localizedDescription containsString:@"FOREIGN KEY constraint failed"], @"%@", error);
[queue shutdown];
}

- (void)testForeignKeysAreEnforcedInADatabaseFile {
ZENDatabaseQueue *queue = [ZENDatabaseQueue databaseQueueWithURL:[self temporaryDatabaseURL]
options:ZENDatabaseQueueOptionForeignKeys];
XCTAssertEqual([self addRowWithMissingReferenceOnQueue:queue].code, ZENDatabaseErrorStatementFailed);
[queue shutdown];
}

- (void)testForeignKeysAreNotEnforcedByDefault {
ZENDatabaseQueue *queue = [ZENDatabaseQueue databaseQueueInMemory];
XCTAssertNil([self addRowWithMissingReferenceOnQueue:queue]);
[queue shutdown];
}

#pragma mark - Trace Execution

// ZENDatabase keeps its FMDatabase private, so these read FMDB's setting by key path
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ A domain model stored in SQLite: a table class for each table, plain data object
* [`ZENDatabaseQueue`](https://github.com/znelson/CoreZen/blob/main/CoreZen/Database/DatabaseQueue.h) runs blocks on a database one at a time, synchronously or asynchronously. Each queue has one SQLite connection, so anything that belongs to a connection, like a temporary table, lasts from one block to the next.
* A transaction block commits when it returns, or rolls back if any statement in it fails or it calls `cancelTransaction`.
* `shutdown:` runs the async work already queued, then a final block of your own, then closes the database. Work queued after that doesn't run.
* A database file uses SQLite's write-ahead log, so a write and reads on other connections don't wait for each other, and a power loss can undo the last commits but not corrupt the database. The file gets two companions, `-wal` and `-shm`, which go wherever it goes.
* `ZENDatabaseQueueOptionForeignKeys` turns on SQLite's enforcement of `REFERENCES` clauses, which is off unless asked for.
* An in-memory queue has a database of its own, which is handy for tests.
* [`ZENDatabase`](https://github.com/znelson/CoreZen/blob/main/CoreZen/Database/Database.h) and [`ZENResultSet`](https://github.com/znelson/CoreZen/blob/main/CoreZen/Database/ResultSet.h) run statements and read their results, wrapping FMDB's classes.
* A class for each table conforms to [`ZENDatabaseTable`](https://github.com/znelson/CoreZen/blob/main/CoreZen/Database/DatabaseTable.h): it creates and migrates the table, and inserts, updates, deletes, reads and counts its rows as [`ZENDataTransferObject`](https://github.com/znelson/CoreZen/blob/main/CoreZen/Database/DataTransferObject.h)s. A data transfer object (DTO) holds one row's values in properties its subclass declares, and can be copied.
Expand Down