diff --git a/CHANGELOG.md b/CHANGELOG.md index b16c973..e3cfbf1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,11 +10,17 @@ To note a change, add a line under Unreleased, in a group such as Added, Changed - Documentation for the whole API, built with DocC: doc comments in the public headers, which Xcode shows in Quick Help, and an article with examples for each of CoreZen's three parts: persistence, media and utilities. - `-[ZENFrameRenderer renderExactFrameAtSeconds:width:height:completion:]`, which renders the frame a player shows at a time, rather than the keyframe at or before it. +- `-[ZENDatabaseSchema initializeDatabase:error:]`, which says whether the schema update worked, and why not when it didn't. An app can stop there, instead of going on to use tables the update didn't change. + +### Deprecated + +- `-[ZENDatabaseSchema initializeDatabase:]`, which can't say that the update failed. Use `initializeDatabase:error:`. ### Fixed - Frames rendered from a file whose timestamps don't start at 0, such as an MPEG transport stream, come from the time asked for. Before, times counted from timestamp 0, so frames came from too early and their actual times were off by the file's start, and a rough seek could land a keyframe or more late. - Frames render from interlaced video, such as a DVD's MPEG-2. FFmpeg's scaler refused to turn an interlaced frame into a progressive image, so every render of one had no image. +- A schema update whose commit fails rolls back. Before, the update's transaction could stay open, so the queue's next transaction ran inside it and was lost with it. ## 0.1.0 - 2026-11-19 diff --git a/CoreZen/CoreZen.docc/Persistence.md b/CoreZen/CoreZen.docc/Persistence.md index 9b52777..c133c60 100644 --- a/CoreZen/CoreZen.docc/Persistence.md +++ b/CoreZen/CoreZen.docc/Persistence.md @@ -67,14 +67,22 @@ A later version of the schema adds a branch for version 2, and so on. Each versi ### Open the Database -A ``ZENDatabaseSchema`` brings the database up to the latest version of every table's schema: +A ``ZENDatabaseSchema`` brings the database up to the latest version of every table's schema. Outside a transaction, as in a fetch block, the update commits in a transaction of its own, so its result says whether it saved: ```objc ZENDatabaseQueue *queue = [ZENDatabaseQueue databaseQueueWithURL:databaseURL]; ZENDatabaseSchema *schema = [ZENDatabaseSchema schemaWithTableClasses:@[NoteTable.class]]; -[queue transactionSync:^(ZENDatabase *database) { - [schema initializeDatabase:database]; +__block BOOL updated = NO; +__block NSError *error = nil; +[queue fetchSync:^(ZENDatabase *database) { + updated = [schema initializeDatabase:database error:&error]; }]; +if (!updated) { + // The update rolled back, so the database has its earlier version, which + // the tables' code may not fit. The error says which statement failed. + [NSApp presentError:error]; + return; +} ``` ### Load and Save Objects diff --git a/CoreZen/Database/DatabaseSchema.h b/CoreZen/Database/DatabaseSchema.h index 9067afa..0d3e4cf 100644 --- a/CoreZen/Database/DatabaseSchema.h +++ b/CoreZen/Database/DatabaseSchema.h @@ -24,13 +24,32 @@ NS_ASSUME_NONNULL_BEGIN + (instancetype)schemaWithTableClasses:(NSArray *)tables; /// Updates a database to the latest version, then moves the identifier counter -/// past its largest identifier. +/// past its largest identifier, and says whether the update worked. /// -/// 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; +/// The update runs in a transaction of its own, or joins the caller's if one is +/// open. If any statement in it fails, or its commit does, the whole update rolls +/// back, so the database keeps the version it had, and the update runs again the +/// next time. Joined to the caller's transaction, the update saves only when that +/// transaction commits, and it fails if that transaction is already set to roll +/// back. +/// +/// It returns YES once the database is at the latest version, including when it +/// already was. It returns NO, with the error set, if the update failed. The +/// error is in ``ZENDatabaseErrorDomain``, and for a failed statement, its +/// description has SQLite's message. The error pointer may be NULL. +/// +/// Either way, it then raises the counter that ``ZENGetNextObjectIdentifier`` +/// uses past the largest identifier in any of the tables, which can hold rows +/// even when the update fails. +- (BOOL)initializeDatabase:(ZENDatabase *)database error:(NSError *_Nullable *_Nullable)outError; + +/// Updates a database to the latest version, then moves the identifier counter +/// past its largest identifier, without saying whether the update worked. +/// +/// It does what ``initializeDatabase:error:`` does, but a caller can't tell that +/// the update failed, and goes on to use tables the update didn't change. +- (void)initializeDatabase:(ZENDatabase *)database + __attribute__((deprecated("Use initializeDatabase:error:, which says whether the update worked"))); @end diff --git a/CoreZen/Database/DatabaseSchema.m b/CoreZen/Database/DatabaseSchema.m index 7755d3a..231b546 100644 --- a/CoreZen/Database/DatabaseSchema.m +++ b/CoreZen/Database/DatabaseSchema.m @@ -39,7 +39,7 @@ + (instancetype)schemaWithTableClasses:(NSArray *)tables { return [[ZENDatabaseSchema alloc] initWithTableClasses:tables]; } -- (void)initializeDatabase:(ZENDatabase *)database { +- (BOOL)initializeDatabase:(ZENDatabase *)database error:(NSError **)outError { // Update the database schema to the latest version, in a transaction of its // own unless the caller has one open. A failed statement makes the caller's // transaction roll back too. @@ -48,20 +48,47 @@ - (void)initializeDatabase:(ZENDatabase *)database { [database beginTransaction]; } BOOL versionChanged = [self updateDatabaseSchema:database]; - NSError *rollbackError = database.rollbackError; - if (rollbackError) { - os_log_error(ZENLogDatabase(), "Rolling back the schema update: %{public}@", rollbackError.localizedDescription); + NSError *updateError = database.rollbackError; + if (updateError) { + os_log_error(ZENLogDatabase(), "Rolling back the schema update: %{public}@", updateError.localizedDescription); } if (ownsTransaction) { - if (versionChanged && !rollbackError) { - [database commit]; + if (versionChanged && !updateError) { + if (![database commit]) { + NSString *description = + [NSString stringWithFormat:@"Couldn't commit the schema update: %@", database.lastErrorMessage]; + os_log_error(ZENLogDatabase(), "%{public}@, so rolling it back", description); + updateError = ZENDatabaseErrorMake(ZENDatabaseErrorCommitFailed, description); + // A failed commit can leave the transaction open, which would swallow + // the queue's next transaction + if (database.inTransaction) { + [database rollback]; + } + } } else { [database rollback]; } } - // Initialize the global identifiers from database tables + // Raise the global identifier counter past the tables' rows, which exist even + // when the update failed [self initializeIdentifiers:database]; + + if (updateError) { + if (outError) { + *outError = updateError; + } + return NO; + } + return YES; +} + +// Deprecated, but still part of the API +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-implementations" +- (void)initializeDatabase:(ZENDatabase *)database { + [self initializeDatabase:database error:NULL]; } +#pragma clang diagnostic pop - (NSArray *)tableNames { NSMutableArray *tableNames = [NSMutableArray array]; diff --git a/CoreZenTests/Classes/TestTable.h b/CoreZenTests/Classes/TestTable.h index ec22b60..616b926 100644 --- a/CoreZenTests/Classes/TestTable.h +++ b/CoreZenTests/Classes/TestTable.h @@ -25,6 +25,13 @@ @end +// Its schema update to version 1 creates its table, then leaves a row whose +// deferred foreign key refers to no row. With foreign keys enforced, the update's +// statements succeed and its commit fails. +@interface ZENUncommittableMigrationTestTable : ZENTestTable + +@end + // Reads test_objects like ZENTestTable, but its writes report failure without // running a statement, as a table with checks of its own might @interface ZENRefusingTestTable : ZENTestTable diff --git a/CoreZenTests/Classes/TestTable.m b/CoreZenTests/Classes/TestTable.m index 7bc0ce8..2e2ed48 100644 --- a/CoreZenTests/Classes/TestTable.m +++ b/CoreZenTests/Classes/TestTable.m @@ -104,6 +104,26 @@ + (BOOL)updateSchema:(ZENDatabase *)database version:(NSUInteger)version { @end +@implementation ZENUncommittableMigrationTestTable + ++ (NSString *)tableName { + return @"uncommittable_migration_objects"; +} + ++ (BOOL)updateSchema:(ZENDatabase *)database version:(NSUInteger)version { + BOOL updated = [super updateSchema:database version:version]; + if (version == 1) { + // SQLite checks a deferred foreign key only at COMMIT + [database executeUpdate:@"CREATE TABLE parents (identifier INTEGER PRIMARY KEY);"]; + [database executeUpdate:@"CREATE TABLE orphans " + @"(parent INTEGER REFERENCES parents (identifier) DEFERRABLE INITIALLY DEFERRED);"]; + [database executeUpdate:@"INSERT INTO orphans VALUES (-1);"]; + } + return updated; +} + +@end + @implementation ZENRefusingTestTable - (BOOL)insertDTO:(ZENDataTransferObject *)dto database:(ZENDatabase *)database { diff --git a/CoreZenTests/DatabaseTests.m b/CoreZenTests/DatabaseTests.m index 0270701..4b57feb 100644 --- a/CoreZenTests/DatabaseTests.m +++ b/CoreZenTests/DatabaseTests.m @@ -58,7 +58,7 @@ - (void)setUp { ZENDatabaseSchema *schema = [ZENDatabaseSchema schemaWithTableClasses:@[[ZENTestTable class]]]; [self.queue transactionSync:^(ZENDatabase *database) { - [schema initializeDatabase:database]; + XCTAssertTrue([schema initializeDatabase:database error:NULL]); }]; } @@ -89,49 +89,164 @@ - (void)testSchemaVersionIsSet { }]; } -// The schema version and whether the broken migration's table exists, after -// initializing a fresh database with it, either on its own or inside a transaction -- (void)initializeBrokenMigrationInTransaction:(BOOL)inTransaction - schemaVersion:(long long *)schemaVersion - tableExists:(BOOL *)tableExists { - ZENDatabaseQueue *queue = [ZENDatabaseQueue databaseQueueInMemory]; - ZENDatabaseSchema *schema = [ZENDatabaseSchema schemaWithTableClasses:@[[ZENBrokenMigrationTestTable class]]]; +// Initializes the queue's database with a schema of one table, either on its +// own or inside a transaction, and returns what initializeDatabase:error: did +- (BOOL)initializeTableClass:(Class)tableClass + onQueue:(ZENDatabaseQueue *)queue + inTransaction:(BOOL)inTransaction + error:(NSError **)outError { + ZENDatabaseSchema *schema = [ZENDatabaseSchema schemaWithTableClasses:@[tableClass]]; + __block BOOL initialized = NO; + __block NSError *error = nil; ZENDatabaseBlock initialize = ^(ZENDatabase *database) { - [schema initializeDatabase:database]; + initialized = [schema initializeDatabase:database error:&error]; }; if (inTransaction) { [queue transactionSync:initialize]; } else { [queue fetchSync:initialize]; } + if (outError) { + *outError = error; + } + return initialized; +} + +- (BOOL)tableExists:(NSString *)tableName onQueue:(ZENDatabaseQueue *)queue { + __block BOOL exists = NO; [queue fetchSync:^(ZENDatabase *database) { - ZENResultSet *rs = [database executeQuery:@"PRAGMA user_version;"]; - XCTAssertTrue([rs next]); - *schemaVersion = [rs longLongIntForColumnIndex:0]; - [rs close]; - rs = [database executeQuery:@"SELECT name FROM sqlite_master WHERE type='table' AND name='broken_migration_objects';"]; - *tableExists = [rs next]; + ZENResultSet *rs = [database executeQuery:@"SELECT name FROM sqlite_master WHERE type='table' AND name=?;", tableName]; + exists = [rs next]; [rs close]; }]; + return exists; +} + +- (void)testSchemaUpdateReportsSuccess { + ZENDatabaseQueue *queue = [ZENDatabaseQueue databaseQueueInMemory]; + NSError *error = nil; + XCTAssertTrue([self initializeTableClass:[ZENTestTable class] onQueue:queue inTransaction:NO error:&error]); + XCTAssertNil(error); + XCTAssertEqualObjects([self valueOfPragma:@"user_version" onQueue:queue], @"1"); [queue shutdown]; } -- (void)testFailedSchemaUpdateRollsBack { +- (void)testSchemaUpdateAtLatestVersionReportsSuccess { + // setUp already brought the queue's database to the latest version, so this + // update has nothing to do + NSError *error = nil; + XCTAssertTrue([self initializeTableClass:[ZENTestTable class] onQueue:self.queue inTransaction:NO error:&error]); + XCTAssertNil(error); + XCTAssertEqualObjects([self valueOfPragma:@"user_version" onQueue:self.queue], @"1"); +} + +// Version 2 of the broken migration fails after version 1 made its table +- (void)checkFailedSchemaUpdateInTransaction:(BOOL)inTransaction { + ZENDatabaseQueue *queue = [ZENDatabaseQueue databaseQueueInMemory]; + NSError *error = nil; + XCTAssertFalse([self initializeTableClass:[ZENBrokenMigrationTestTable class] + onQueue:queue + inTransaction:inTransaction + error:&error]); + XCTAssertEqualObjects(error.domain, ZENDatabaseErrorDomain); + XCTAssertEqual(error.code, ZENDatabaseErrorStatementFailed); + XCTAssertTrue([error.localizedDescription containsString:@"no such table: no_such_table"], + @"The error should have SQLite's message: %@", error.localizedDescription); + // Rolling back the whole update leaves the database at version 0, so the // update runs again next time instead of skipping the broken migration - long long schemaVersion = -1; - BOOL tableExists = YES; - [self initializeBrokenMigrationInTransaction:NO schemaVersion:&schemaVersion tableExists:&tableExists]; - XCTAssertEqual(schemaVersion, 0); - XCTAssertFalse(tableExists, @"Version 1's table should roll back with the failed version 2"); + XCTAssertEqualObjects([self valueOfPragma:@"user_version" onQueue:queue], @"0"); + XCTAssertFalse([self tableExists:@"broken_migration_objects" onQueue:queue], + @"Version 1's table should roll back with the failed version 2"); + [queue shutdown]; +} + +- (void)testFailedSchemaUpdateRollsBackAndReportsTheStatement { + [self checkFailedSchemaUpdateInTransaction:NO]; +} + +- (void)testFailedSchemaUpdateInsideTransactionRollsBackAndReportsTheStatement { + [self checkFailedSchemaUpdateInTransaction:YES]; +} + +- (void)testSchemaUpdateInsideCanceledTransactionFails { + // The update would work, but it joins a transaction that's set to roll back + ZENDatabaseQueue *queue = [ZENDatabaseQueue databaseQueueInMemory]; + ZENDatabaseSchema *schema = [ZENDatabaseSchema schemaWithTableClasses:@[[ZENTestTable class]]]; + __block BOOL initialized = YES; + __block NSError *error = nil; + [queue transactionSync:^(ZENDatabase *database) { + [database cancelTransaction]; + initialized = [schema initializeDatabase:database error:&error]; + }]; + XCTAssertFalse(initialized); + XCTAssertEqualObjects(error.domain, ZENDatabaseErrorDomain); + XCTAssertEqual(error.code, ZENDatabaseErrorTransactionCanceled); + XCTAssertEqualObjects([self valueOfPragma:@"user_version" onQueue:queue], @"0"); + [queue shutdown]; +} + +- (void)testFailedSchemaCommitRollsBackAndReportsTheCommit { + ZENDatabaseQueue *queue = [ZENDatabaseQueue databaseQueueInMemoryWithOptions:ZENDatabaseQueueOptionForeignKeys]; + NSError *error = nil; + XCTAssertFalse([self initializeTableClass:[ZENUncommittableMigrationTestTable class] + onQueue:queue + inTransaction:NO + error:&error]); + XCTAssertEqualObjects(error.domain, ZENDatabaseErrorDomain); + XCTAssertEqual(error.code, ZENDatabaseErrorCommitFailed); + XCTAssertTrue([error.localizedDescription containsString:@"FOREIGN KEY constraint failed"], + @"The error should have SQLite's message: %@", error.localizedDescription); + XCTAssertEqualObjects([self valueOfPragma:@"user_version" onQueue:queue], @"0"); + XCTAssertFalse([self tableExists:@"uncommittable_migration_objects" onQueue:queue]); + [queue shutdown]; +} + +- (void)testFailedSchemaCommitDoesNotHoldTheNextTransaction { + // A failed commit can leave its transaction open. The next transaction would + // then run inside it, and roll back with it. + ZENDatabaseQueue *queue = [ZENDatabaseQueue databaseQueueInMemoryWithOptions:ZENDatabaseQueueOptionForeignKeys]; + [self initializeTableClass:[ZENUncommittableMigrationTestTable class] onQueue:queue inTransaction:NO error:NULL]; + [queue transactionSync:^(ZENDatabase *database) { + XCTAssertTrue([database executeUpdate:@"CREATE TABLE later (value INTEGER);"]); + }]; + XCTAssertTrue([self tableExists:@"later" onQueue:queue], @"The next transaction should commit on its own"); + [queue shutdown]; +} + +- (void)testFailedSchemaUpdateStillRaisesIdentifiers { + // A database from an earlier version has rows, though its update fails, as an + // app's might when its newest migration doesn't fit the database. New objects + // mustn't reuse the rows' identifiers. + ZENDatabaseQueue *queue = [ZENDatabaseQueue databaseQueueInMemory]; + [queue fetchSync:^(ZENDatabase *database) { + XCTAssertTrue([database executeUpdate:@"CREATE TABLE broken_migration_objects (identifier INTEGER PRIMARY KEY, name TEXT);"]); + XCTAssertTrue([database executeUpdate:@"INSERT INTO broken_migration_objects VALUES (100, 'row');"]); + }]; + XCTAssertFalse([self initializeTableClass:[ZENBrokenMigrationTestTable class] onQueue:queue inTransaction:NO error:NULL]); + XCTAssertEqual(ZENGetNextObjectIdentifier(), 101); + [queue shutdown]; } -- (void)testFailedSchemaUpdateInsideTransactionRollsBack { - long long schemaVersion = -1; - BOOL tableExists = YES; - [self initializeBrokenMigrationInTransaction:YES schemaVersion:&schemaVersion tableExists:&tableExists]; - XCTAssertEqual(schemaVersion, 0); - XCTAssertFalse(tableExists, @"Version 1's table should roll back with the failed version 2"); +- (void)testDeprecatedInitializeDatabaseStillUpdates { + ZENDatabaseQueue *queue = [ZENDatabaseQueue databaseQueueInMemory]; + ZENDatabaseQueue *brokenQueue = [ZENDatabaseQueue databaseQueueInMemory]; + ZENDatabaseSchema *schema = [ZENDatabaseSchema schemaWithTableClasses:@[[ZENTestTable class]]]; + ZENDatabaseSchema *brokenSchema = [ZENDatabaseSchema schemaWithTableClasses:@[[ZENBrokenMigrationTestTable class]]]; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + [queue fetchSync:^(ZENDatabase *database) { + [schema initializeDatabase:database]; + }]; + // It has no error to give back when the update fails + [brokenQueue fetchSync:^(ZENDatabase *database) { + [brokenSchema initializeDatabase:database]; + }]; +#pragma clang diagnostic pop + XCTAssertEqualObjects([self valueOfPragma:@"user_version" onQueue:queue], @"1"); + XCTAssertEqualObjects([self valueOfPragma:@"user_version" onQueue:brokenQueue], @"0"); + [queue shutdown]; + [brokenQueue shutdown]; } #pragma mark - Identifiers @@ -152,7 +267,7 @@ - (void)openWithIdentifiers:(NSArray *> *)identifiers ZENDatabaseQueue *queue = [ZENDatabaseQueue databaseQueueInMemory]; ZENDatabaseSchema *schema = [ZENDatabaseSchema schemaWithTableClasses:tableClasses]; [queue fetchSync:^(ZENDatabase *database) { - [schema initializeDatabase:database]; + XCTAssertTrue([schema initializeDatabase:database error:NULL]); }]; [queue transactionSync:^(ZENDatabase *database) { [tableClasses enumerateObjectsUsingBlock:^(Class tableClass, NSUInteger index, BOOL *stop) { @@ -166,7 +281,7 @@ - (void)openWithIdentifiers:(NSArray *> *)identifiers ZENSetLargestObjectIdentifier(counter); [queue fetchSync:^(ZENDatabase *database) { - [schema initializeDatabase:database]; + XCTAssertTrue([schema initializeDatabase:database error:NULL]); }]; [queue shutdown]; } @@ -810,7 +925,7 @@ - (void)testWriteSavesWhileAnotherConnectionReads { ZENDatabaseQueue *reader = [ZENDatabaseQueue databaseQueueWithURL:URL]; ZENDatabaseSchema *schema = [ZENDatabaseSchema schemaWithTableClasses:@[[ZENTestTable class]]]; [writer transactionSync:^(ZENDatabase *database) { - [schema initializeDatabase:database]; + XCTAssertTrue([schema initializeDatabase:database error:NULL]); XCTAssertTrue([self insertRowNamed:@"Alpha" database:database]); }]; diff --git a/CoreZenTests/DomainTests.m b/CoreZenTests/DomainTests.m index 3d85709..e15ffcd 100644 --- a/CoreZenTests/DomainTests.m +++ b/CoreZenTests/DomainTests.m @@ -44,7 +44,7 @@ - (void)setUp { ZENDatabaseSchema *schema = [ZENDatabaseSchema schemaWithTableClasses:@[[ZENTestTable class]]]; [self.queue transactionSync:^(ZENDatabase *database) { - [schema initializeDatabase:database]; + XCTAssertTrue([schema initializeDatabase:database error:NULL]); }]; }