From ab6f18e46dd8ec1ae1529b32b8d808b426db4df8 Mon Sep 17 00:00:00 2001 From: Michael Allman Date: Fri, 8 Oct 2021 15:37:59 -0700 Subject: [PATCH 01/42] Initial commit of code to implement progress-reporting database backups --- GRDB/Core/Database.swift | 14 +++++++--- GRDB/Core/DatabaseReader.swift | 28 +++++++++++++++++-- Tests/GRDBTests/DatabasePoolBackupTests.swift | 15 +++++++++- .../GRDBTests/DatabaseQueueBackupTests.swift | 17 +++++++++-- 4 files changed, 64 insertions(+), 10 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 1b47e7e90..4511383f1 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1245,8 +1245,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib func backup( to dbDest: Database, + pageStepSize: Int32 = -1, afterBackupInit: (() -> Void)? = nil, - afterBackupStep: (() -> Void)? = nil) + afterBackupStep: ((Progress) -> Void)? = nil) throws { guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", sqliteConnection, "main") else { @@ -1260,12 +1261,17 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib do { backupLoop: while true { - switch sqlite3_backup_step(backup, -1) { + let rc = sqlite3_backup_step(backup, pageStepSize) + let pageCount = sqlite3_backup_pagecount(backup) + let completedCount = pageCount - sqlite3_backup_remaining(backup) + let progress = Progress(totalUnitCount: Int64(pageCount)) + progress.completedUnitCount = Int64(completedCount) + switch rc { case SQLITE_DONE: - afterBackupStep?() + afterBackupStep?(progress) break backupLoop case SQLITE_OK: - afterBackupStep?() + afterBackupStep?(progress) case let code: throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage) } diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index e31b7cb7a..b620b00e8 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -278,21 +278,43 @@ extension DatabaseReader { /// When the source is a DatabasePool, concurrent writes can happen during /// the backup. Those writes may, or may not, be reflected in the backup, /// but they won't trigger any error. - public func backup(to writer: DatabaseWriter) throws { + /// + /// The `backup` method uses the optional `progress` callback to report + /// the progress of the backup operation. + public func backup( + to writer: DatabaseWriter, + progress: ((Progress) -> ())? = nil) + throws + { + try backup(to: writer, pageStepSize: 5, progress: progress) + } + + /// A module-private function to pass the page step size for testing + func backup( + to writer: DatabaseWriter, + pageStepSize: Int32 = -1, + progress: ((Progress) -> ())? = nil) + throws + { try writer.writeWithoutTransaction { dbDest in - try backup(to: dbDest) + try backup( + to: dbDest, + pageStepSize: pageStepSize, + afterBackupStep: progress) } } func backup( to dbDest: Database, + pageStepSize: Int32 = -1, afterBackupInit: (() -> Void)? = nil, - afterBackupStep: (() -> Void)? = nil) + afterBackupStep: ((Progress) -> Void)? = nil) throws { try read { dbFrom in try dbFrom.backup( to: dbDest, + pageStepSize: pageStepSize, afterBackupInit: afterBackupInit, afterBackupStep: afterBackupStep) } diff --git a/Tests/GRDBTests/DatabasePoolBackupTests.swift b/Tests/GRDBTests/DatabasePoolBackupTests.swift index c59afd57d..5cb41af99 100644 --- a/Tests/GRDBTests/DatabasePoolBackupTests.swift +++ b/Tests/GRDBTests/DatabasePoolBackupTests.swift @@ -8,13 +8,26 @@ class DatabasePoolBackupTests: GRDBTestCase { let source = try makeDatabasePool(filename: "source.sqlite", configuration: Configuration()) let destination = try makeDatabasePool(filename: "destination.sqlite", configuration: Configuration()) + var pageCount: Int = 0 try source.write { db in try db.execute(sql: "CREATE TABLE item (id INTEGER PRIMARY KEY)") try db.execute(sql: "INSERT INTO item (id) VALUES (NULL)") XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM item")!, 1) + pageCount = try Int.fetchOne(db, sql: "PRAGMA page_count")! } - try source.backup(to: destination) + XCTAssert(pageCount > 0) + + var progressCount: Int = 1 + try source.backup(to: destination, pageStepSize: 1) { progress in + let expectedCompletedPages = Int64(progressCount) + XCTAssertEqual(expectedCompletedPages, progress.completedUnitCount) + if !progress.isFinished { + progressCount += 1 + } + } + + XCTAssertEqual(pageCount, progressCount) try destination.read { db in XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM item")!, 1) diff --git a/Tests/GRDBTests/DatabaseQueueBackupTests.swift b/Tests/GRDBTests/DatabaseQueueBackupTests.swift index 8cdde038b..e6cb6db99 100644 --- a/Tests/GRDBTests/DatabaseQueueBackupTests.swift +++ b/Tests/GRDBTests/DatabaseQueueBackupTests.swift @@ -1,5 +1,5 @@ import XCTest -import GRDB +@testable import GRDB class DatabaseQueueBackupTests: GRDBTestCase { @@ -8,13 +8,26 @@ class DatabaseQueueBackupTests: GRDBTestCase { let source = try makeDatabaseQueue(filename: "source.sqlite", configuration: Configuration()) let destination = try makeDatabaseQueue(filename: "destination.sqlite", configuration: Configuration()) + var pageCount: Int = 0 try source.inDatabase { db in try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)") XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) + pageCount = try Int.fetchOne(db, sql: "PRAGMA page_count")! } - try source.backup(to: destination) + XCTAssert(pageCount > 0) + + var progressCount: Int = 1 + try source.backup(to: destination, pageStepSize: 1) { progress in + let expectedCompletedPages = Int64(progressCount) + XCTAssertEqual(expectedCompletedPages, progress.completedUnitCount) + if !progress.isFinished { + progressCount += 1 + } + } + + XCTAssertEqual(pageCount, progressCount) try destination.inDatabase { db in XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) From f829d46b7f6a7cdbd7c0f112260b097ca13af9d9 Mon Sep 17 00:00:00 2001 From: Michael Allman Date: Mon, 11 Oct 2021 13:24:20 -0700 Subject: [PATCH 02/42] Change default backup page step size from 5 to 100, which is the value used in the sqlite3 cli .backup command --- GRDB/Core/DatabaseReader.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index b620b00e8..c21190ade 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -286,7 +286,7 @@ extension DatabaseReader { progress: ((Progress) -> ())? = nil) throws { - try backup(to: writer, pageStepSize: 5, progress: progress) + try backup(to: writer, pageStepSize: 100, progress: progress) } /// A module-private function to pass the page step size for testing From f012c011b1aaa892acff00df9b2e20690e7a6281 Mon Sep 17 00:00:00 2001 From: Michael Allman Date: Mon, 11 Oct 2021 13:25:58 -0700 Subject: [PATCH 03/42] Import the Foundation framework in DatabaseReader.swift, which is required to get the Progress class --- GRDB/Core/DatabaseReader.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index c21190ade..ff7de2441 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -2,6 +2,7 @@ import Combine #endif import Dispatch +import Foundation /// `DatabaseReader` is the protocol for all types that can fetch values from /// an SQLite database. From 087ad1008635855180c796576a3d892fe01f19f2 Mon Sep 17 00:00:00 2001 From: Michael Allman Date: Tue, 9 Nov 2021 11:01:42 -0800 Subject: [PATCH 04/42] Add an API to track progress of and cancel backups in progress, for both the DatabaseReader/DatabaseWriter API and Database API --- GRDB.xcodeproj/project.pbxproj | 32 +++++++- GRDB/Core/Database.swift | 54 +++++++++++-- GRDB/Core/DatabaseBackupCancelled.swift | 3 + GRDB/Core/DatabaseBackupProgress.swift | 7 ++ GRDB/Core/DatabaseReader.swift | 16 +--- GRDBCustom.xcodeproj/project.pbxproj | 20 ++++- Tests/GRDBTests/BackupTestCase.swift | 81 +++++++++++++++++++ Tests/GRDBTests/DatabasePoolBackupTests.swift | 55 +++---------- .../GRDBTests/DatabaseQueueBackupTests.swift | 55 +++---------- 9 files changed, 217 insertions(+), 106 deletions(-) create mode 100644 GRDB/Core/DatabaseBackupCancelled.swift create mode 100644 GRDB/Core/DatabaseBackupProgress.swift create mode 100644 Tests/GRDBTests/BackupTestCase.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 5a1a122d4..ab80e0dbe 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -7,6 +7,17 @@ objects = { /* Begin PBXBuildFile section */ + 4ED4BB592731DD25008B127D /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB582731DD25008B127D /* BackupTestCase.swift */; }; + 4ED4BB5A2731DD25008B127D /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB582731DD25008B127D /* BackupTestCase.swift */; }; + 4ED4BB5B2731DD25008B127D /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB582731DD25008B127D /* BackupTestCase.swift */; }; + 4ED4BB602731DFC4008B127D /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB5C2731DFB0008B127D /* DatabaseBackupProgress.swift */; }; + 4ED4BB612731DFC7008B127D /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB5C2731DFB0008B127D /* DatabaseBackupProgress.swift */; }; + 4ED4BB622731DFC8008B127D /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB5C2731DFB0008B127D /* DatabaseBackupProgress.swift */; }; + 4ED4BB632731DFC8008B127D /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB5C2731DFB0008B127D /* DatabaseBackupProgress.swift */; }; + 4ED4BB652731E6AF008B127D /* DatabaseBackupCancelled.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB642731E6AF008B127D /* DatabaseBackupCancelled.swift */; }; + 4ED4BB662731E6AF008B127D /* DatabaseBackupCancelled.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB642731E6AF008B127D /* DatabaseBackupCancelled.swift */; }; + 4ED4BB672731E6AF008B127D /* DatabaseBackupCancelled.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB642731E6AF008B127D /* DatabaseBackupCancelled.swift */; }; + 4ED4BB682731E6AF008B127D /* DatabaseBackupCancelled.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB642731E6AF008B127D /* DatabaseBackupCancelled.swift */; }; 56012B552573EED000B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */; }; 56012B562573EED100B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */; }; 56012B572573EED100B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */; }; @@ -1266,6 +1277,9 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ + 4ED4BB582731DD25008B127D /* BackupTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BackupTestCase.swift; sourceTree = ""; }; + 4ED4BB5C2731DFB0008B127D /* DatabaseBackupProgress.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseBackupProgress.swift; sourceTree = ""; }; + 4ED4BB642731E6AF008B127D /* DatabaseBackupCancelled.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseBackupCancelled.swift; sourceTree = ""; }; 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpressionTests.swift; sourceTree = ""; }; 56012B742574048B00B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = ""; }; 560233C32724234F00529DF3 /* SharedValueObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservation.swift; sourceTree = ""; }; @@ -1935,8 +1949,8 @@ 563363BB1C93FD32000BE133 /* DatabaseQueue */ = { isa = PBXGroup; children = ( - 5687359E1CEDE16C009B9116 /* Betty.jpeg */, 5672DE581CDB72520022BA81 /* DatabaseQueueBackupTests.swift */, + 5687359E1CEDE16C009B9116 /* Betty.jpeg */, 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */, 56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */, 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */, @@ -2218,6 +2232,7 @@ 56A238111B9C74A90082EB20 /* Core */ = { isa = PBXGroup; children = ( + 4ED4BB582731DD25008B127D /* BackupTestCase.swift */, 5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */, 56DAA2C41DE99D8D006E10C8 /* Cursor */, 56E4F7ED2392E2D000A611F6 /* DatabaseAbortedTransactionTests.swift */, @@ -2324,6 +2339,8 @@ 56A238711B9C75030082EB20 /* Database.swift */, 566B91221FA4CF810012D5B0 /* Database+Schema.swift */, 566B91081FA4C3960012D5B0 /* Database+Statements.swift */, + 4ED4BB642731E6AF008B127D /* DatabaseBackupCancelled.swift */, + 4ED4BB5C2731DFB0008B127D /* DatabaseBackupProgress.swift */, 566B91121FA4C3F50012D5B0 /* DatabaseCollation.swift */, 56A238731B9C75030082EB20 /* DatabaseError.swift */, 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */, @@ -2350,8 +2367,8 @@ 56A238781B9C75030082EB20 /* Statement.swift */, 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */, 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, - 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, 5605F1471C672E4000235C62 /* Support */, + 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, ); path = Core; sourceTree = ""; @@ -3004,6 +3021,7 @@ 56FBFEDB2210731A00945324 /* SQLRequest.swift in Sources */, 56F5ABD91D814330001F60CB /* Data.swift in Sources */, 565490D41D5AE252005622CB /* (null) in Sources */, + 4ED4BB622731DFC8008B127D /* DatabaseBackupProgress.swift in Sources */, 56713FDF2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */, 566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, 565490B61D5AE236005622CB /* Configuration.swift in Sources */, @@ -3027,6 +3045,7 @@ 565490B81D5AE236005622CB /* DatabaseError.swift in Sources */, 56DAA2E11DE9C827006E10C8 /* Cursor.swift in Sources */, 5653EB0520944C7C00F46237 /* BelongsToAssociation.swift in Sources */, + 4ED4BB672731E6AF008B127D /* DatabaseBackupCancelled.swift in Sources */, 56A2FA3C24424F4800E97D23 /* Export.swift in Sources */, 565490BC1D5AE236005622CB /* DatabaseSchemaCache.swift in Sources */, 563EF42F2161180D007DAACD /* AssociationAggregate.swift in Sources */, @@ -3156,6 +3175,7 @@ 5698AC7B1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 56894FC82606589B00268F4D /* Decimal.swift in Sources */, 569D6DDF220EF9E100A058A9 /* SQLInterpolation.swift in Sources */, + 4ED4BB612731DFC7008B127D /* DatabaseBackupProgress.swift in Sources */, 56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */, 5653EB0D20944C7C00F46237 /* HasManyAssociation.swift in Sources */, 567ECE502222E431009245CA /* GRDB-5.0.swift in Sources */, @@ -3174,6 +3194,7 @@ 560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */, 5613ED4521A95B2C00DC7A68 /* ValueReducer.swift in Sources */, 560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */, + 4ED4BB662731E6AF008B127D /* DatabaseBackupCancelled.swift in Sources */, 56717272261C68EA00423B6F /* CaseInsensitiveIdentifier.swift in Sources */, 5613ED3621A95A5C00DC7A68 /* Map.swift in Sources */, 56E9FAD8221053DD00C703A8 /* SQL.swift in Sources */, @@ -3347,6 +3368,7 @@ 563B8FA2249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */, 56A238581B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift in Sources */, 56A5EF131EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, + 4ED4BB5A2731DD25008B127D /* BackupTestCase.swift in Sources */, 5653EAE920944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */, 5698ACD21DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 561CFA7923735016000C8BAA /* TableRecordUpdateTests.swift in Sources */, @@ -3581,6 +3603,7 @@ 5665FA332129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, 563B8FA1249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */, 56CC9246201E058100CB597E /* DropFirstCursorTests.swift in Sources */, + 4ED4BB592731DD25008B127D /* BackupTestCase.swift in Sources */, 5698AC401DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 562393571DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 5653EAE820944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */, @@ -3758,6 +3781,7 @@ AAA4DCCF230F1E0600C74B15 /* VirtualTableModule.swift in Sources */, 56894FD22606589D00268F4D /* Decimal.swift in Sources */, AAA4DCD0230F1E0600C74B15 /* SQLInterpolation.swift in Sources */, + 4ED4BB632731DFC8008B127D /* DatabaseBackupProgress.swift in Sources */, AAA4DCD1230F1E0600C74B15 /* DatabaseError.swift in Sources */, AAA4DCD2230F1E0600C74B15 /* HasManyAssociation.swift in Sources */, AAA4DCD3230F1E0600C74B15 /* GRDB-5.0.swift in Sources */, @@ -3776,6 +3800,7 @@ AAA4DCDF230F1E0600C74B15 /* PersistableRecord.swift in Sources */, AAA4DCE0230F1E0600C74B15 /* ValueReducer.swift in Sources */, AAA4DCE2230F1E0600C74B15 /* StatementColumnConvertible.swift in Sources */, + 4ED4BB682731E6AF008B127D /* DatabaseBackupCancelled.swift in Sources */, 56717274261C68EA00423B6F /* CaseInsensitiveIdentifier.swift in Sources */, AAA4DCE3230F1E0600C74B15 /* Map.swift in Sources */, AAA4DCE5230F1E0600C74B15 /* SQL.swift in Sources */, @@ -3949,6 +3974,7 @@ 563B8FA3249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */, AAA4DD8A230F262000C74B15 /* RecordPrimaryKeyRowIDTests.swift in Sources */, AAA4DD8B230F262000C74B15 /* ForeignKeyInfoTests.swift in Sources */, + 4ED4BB5B2731DD25008B127D /* BackupTestCase.swift in Sources */, AAA4DD8C230F262000C74B15 /* AssociationChainSQLTests.swift in Sources */, AAA4DD8D230F262000C74B15 /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 561CFA7A23735016000C8BAA /* TableRecordUpdateTests.swift in Sources */, @@ -4126,6 +4152,7 @@ 567ECE4F2222E431009245CA /* GRDB-5.0.swift in Sources */, 56894FB72606589700268F4D /* Decimal.swift in Sources */, 56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, + 4ED4BB602731DFC4008B127D /* DatabaseBackupProgress.swift in Sources */, 56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */, 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */, 564CE43121AA901800652B19 /* ValueObserver.swift in Sources */, @@ -4144,6 +4171,7 @@ 56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */, 5605F1671C672E4000235C62 /* NSNumber.swift in Sources */, 56E9FADA221053DD00C703A8 /* SQL.swift in Sources */, + 4ED4BB652731E6AF008B127D /* DatabaseBackupCancelled.swift in Sources */, 56717271261C68E900423B6F /* CaseInsensitiveIdentifier.swift in Sources */, C96C0F2B2084A442006B2981 /* SQLiteDateParser.swift in Sources */, 56781B0B243F86E600650A83 /* Refinable.swift in Sources */, diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 4511383f1..d0b40defd 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1243,11 +1243,23 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - Backup - func backup( + public func backup( + to dbDest: Database, + pageStepSize: Int32 = -1, + progress: ((DatabaseBackupProgress) -> ())? = nil) + throws + { + try backupInternal( + to: dbDest, + pageStepSize: pageStepSize, + afterBackupStep: progress) + } + + func backupInternal( to dbDest: Database, pageStepSize: Int32 = -1, afterBackupInit: (() -> Void)? = nil, - afterBackupStep: ((Progress) -> Void)? = nil) + afterBackupStep: ((DatabaseBackupProgress) -> Void)? = nil) throws { guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", sqliteConnection, "main") else { @@ -1259,13 +1271,17 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib afterBackupInit?() + let progress = DatabaseBackupProgressImpl() + do { backupLoop: while true { + guard !progress.cancelRequested else { + throw DatabaseBackupCancelled(progress: progress) + } let rc = sqlite3_backup_step(backup, pageStepSize) - let pageCount = sqlite3_backup_pagecount(backup) - let completedCount = pageCount - sqlite3_backup_remaining(backup) - let progress = Progress(totalUnitCount: Int64(pageCount)) - progress.completedUnitCount = Int64(completedCount) + let totalPages = Int(sqlite3_backup_pagecount(backup)) + let completedPages = totalPages - Int(sqlite3_backup_remaining(backup)) + progress.updateProgress(totalPages: totalPages, completedPages: completedPages) switch rc { case SQLITE_DONE: afterBackupStep?(progress) @@ -1291,6 +1307,32 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // The schema of the destination database has changed: dbDest.clearSchemaCache() } + + private class DatabaseBackupProgressImpl: DatabaseBackupProgress { + public private(set) var totalPages: Int + public private(set) var completedPages: Int + + public var isFinished: Bool { + totalPages == completedPages + } + + fileprivate var cancelRequested: Bool + + fileprivate init() { + totalPages = 0 + completedPages = 0 + cancelRequested = false + } + + public func cancel() { + cancelRequested = true + } + + fileprivate func updateProgress(totalPages: Int, completedPages: Int) { + self.totalPages = totalPages + self.completedPages = completedPages + } + } } #if SQLITE_HAS_CODEC diff --git a/GRDB/Core/DatabaseBackupCancelled.swift b/GRDB/Core/DatabaseBackupCancelled.swift new file mode 100644 index 000000000..2ac2eb11e --- /dev/null +++ b/GRDB/Core/DatabaseBackupCancelled.swift @@ -0,0 +1,3 @@ +public struct DatabaseBackupCancelled: Error { + public let progress: DatabaseBackupProgress +} diff --git a/GRDB/Core/DatabaseBackupProgress.swift b/GRDB/Core/DatabaseBackupProgress.swift new file mode 100644 index 000000000..032118c7e --- /dev/null +++ b/GRDB/Core/DatabaseBackupProgress.swift @@ -0,0 +1,7 @@ +public protocol DatabaseBackupProgress { + var totalPages: Int { get } + var completedPages: Int { get } + var isFinished: Bool { get } + + func cancel() +} diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index ff7de2441..59df93632 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -2,7 +2,6 @@ import Combine #endif import Dispatch -import Foundation /// `DatabaseReader` is the protocol for all types that can fetch values from /// an SQLite database. @@ -283,18 +282,9 @@ extension DatabaseReader { /// The `backup` method uses the optional `progress` callback to report /// the progress of the backup operation. public func backup( - to writer: DatabaseWriter, - progress: ((Progress) -> ())? = nil) - throws - { - try backup(to: writer, pageStepSize: 100, progress: progress) - } - - /// A module-private function to pass the page step size for testing - func backup( to writer: DatabaseWriter, pageStepSize: Int32 = -1, - progress: ((Progress) -> ())? = nil) + progress: ((DatabaseBackupProgress) -> ())? = nil) throws { try writer.writeWithoutTransaction { dbDest in @@ -309,11 +299,11 @@ extension DatabaseReader { to dbDest: Database, pageStepSize: Int32 = -1, afterBackupInit: (() -> Void)? = nil, - afterBackupStep: ((Progress) -> Void)? = nil) + afterBackupStep: ((DatabaseBackupProgress) -> Void)? = nil) throws { try read { dbFrom in - try dbFrom.backup( + try dbFrom.backupInternal( to: dbDest, pageStepSize: pageStepSize, afterBackupInit: afterBackupInit, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 921bf2c8e..d7d2f47cb 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -7,6 +7,12 @@ objects = { /* Begin PBXBuildFile section */ + 4ECF7776273AFAFD001685F5 /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ECF7773273AFAFD001685F5 /* DatabaseBackupProgress.swift */; }; + 4ECF7777273AFAFD001685F5 /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ECF7773273AFAFD001685F5 /* DatabaseBackupProgress.swift */; }; + 4ECF7778273AFAFD001685F5 /* DatabaseBackupCancelled.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ECF7775273AFAFD001685F5 /* DatabaseBackupCancelled.swift */; }; + 4ECF7779273AFAFD001685F5 /* DatabaseBackupCancelled.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ECF7775273AFAFD001685F5 /* DatabaseBackupCancelled.swift */; }; + 4ECF777D273AFBA9001685F5 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ECF777A273AFB72001685F5 /* BackupTestCase.swift */; }; + 4ECF777E273AFBAB001685F5 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ECF777A273AFB72001685F5 /* BackupTestCase.swift */; }; 56012B6A2573FAE700B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B682573FAE600B4925B /* CommonTableExpressionTests.swift */; }; 56012B6B2573FAE700B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B682573FAE600B4925B /* CommonTableExpressionTests.swift */; }; 56012B81257404A400B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B80257404A300B4925B /* CommonTableExpression.swift */; }; @@ -772,6 +778,9 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ + 4ECF7773273AFAFD001685F5 /* DatabaseBackupProgress.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseBackupProgress.swift; sourceTree = ""; }; + 4ECF7775273AFAFD001685F5 /* DatabaseBackupCancelled.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseBackupCancelled.swift; sourceTree = ""; }; + 4ECF777A273AFB72001685F5 /* BackupTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BackupTestCase.swift; sourceTree = ""; }; 56012B682573FAE600B4925B /* CommonTableExpressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CommonTableExpressionTests.swift; sourceTree = ""; }; 56012B80257404A300B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = ""; }; 560233CC2724339A00529DF3 /* SharedValueObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservationTests.swift; sourceTree = ""; }; @@ -1680,6 +1689,7 @@ 56A238111B9C74A90082EB20 /* Core */ = { isa = PBXGroup; children = ( + 4ECF777A273AFB72001685F5 /* BackupTestCase.swift */, 5665F865203EF4590084C6C0 /* ColumnInfoTests.swift */, 56DAA2C41DE99D8D006E10C8 /* Cursor */, 56E4F7F72392E2EE00A611F6 /* DatabaseAbortedTransactionTests.swift */, @@ -1786,6 +1796,8 @@ 56A238711B9C75030082EB20 /* Database.swift */, 566B91221FA4CF810012D5B0 /* Database+Schema.swift */, 566B91081FA4C3960012D5B0 /* Database+Statements.swift */, + 4ECF7775273AFAFD001685F5 /* DatabaseBackupCancelled.swift */, + 4ECF7773273AFAFD001685F5 /* DatabaseBackupProgress.swift */, 566B91121FA4C3F50012D5B0 /* DatabaseCollation.swift */, 56A238731B9C75030082EB20 /* DatabaseError.swift */, 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */, @@ -1812,8 +1824,8 @@ 56A238781B9C75030082EB20 /* Statement.swift */, 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */, 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, - 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, 5605F1471C672E4000235C62 /* Support */, + 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, ); path = Core; sourceTree = ""; @@ -2383,6 +2395,8 @@ 5656A8A82295BF44001FF3FF /* DatabasePromise.swift in Sources */, 5656A86E2295BD56001FF3FF /* HasManyThroughAssociation.swift in Sources */, 56894FE8260658A500268F4D /* Decimal.swift in Sources */, + 4ECF7779273AFAFD001685F5 /* DatabaseBackupCancelled.swift in Sources */, + 4ECF7777273AFAFD001685F5 /* DatabaseBackupProgress.swift in Sources */, 566BE7162342541F00A8254B /* LockedBox.swift in Sources */, F3BA80111CFB2876003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80281CFB2891003DC1BA /* StandardLibrary.swift in Sources */, @@ -2560,6 +2574,7 @@ 5615B279222B109600061C1C /* AssociationHasOneThroughFetchableRecordTests.swift in Sources */, F3BA81261CFB3063003DC1BA /* RecordCopyTests.swift in Sources */, 56A8C24D1D1918F30096E9D4 /* FoundationNSUUIDTests.swift in Sources */, + 4ECF777D273AFBA9001685F5 /* BackupTestCase.swift in Sources */, 5653EB8320961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 5698AC471DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, F3BA80D61CFB2FFD003DC1BA /* DatabaseReaderTests.swift in Sources */, @@ -2750,6 +2765,8 @@ 5656A8A72295BF44001FF3FF /* DatabasePromise.swift in Sources */, 5656A86D2295BD56001FF3FF /* HasManyThroughAssociation.swift in Sources */, 56894FE3260658A400268F4D /* Decimal.swift in Sources */, + 4ECF7778273AFAFD001685F5 /* DatabaseBackupCancelled.swift in Sources */, + 4ECF7776273AFAFD001685F5 /* DatabaseBackupProgress.swift in Sources */, 566BE7152342541F00A8254B /* LockedBox.swift in Sources */, F3BA806D1CFB2E55003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */, @@ -2927,6 +2944,7 @@ 5615B278222B109600061C1C /* AssociationHasOneThroughFetchableRecordTests.swift in Sources */, 5698ACA11DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, F3BA80C31CFB2FD2003DC1BA /* DatabasePoolFunctionTests.swift in Sources */, + 4ECF777E273AFBAB001685F5 /* BackupTestCase.swift in Sources */, 5653EB8220961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, F3BA80D51CFB2FFB003DC1BA /* DatabaseReaderTests.swift in Sources */, F3BA81321CFB3064003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, diff --git a/Tests/GRDBTests/BackupTestCase.swift b/Tests/GRDBTests/BackupTestCase.swift new file mode 100644 index 000000000..35653fa65 --- /dev/null +++ b/Tests/GRDBTests/BackupTestCase.swift @@ -0,0 +1,81 @@ +import XCTest +@testable import GRDB + +class BackupTestCase: GRDBTestCase { + + func setupBackupSource(_ writer: DatabaseWriter) throws -> Int { + try writer.write { db in + try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") + try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)") + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) + } + + let pageCount: Int = try writer.read { db in + try Int.fetchOne(db, sql: "PRAGMA page_count")! + } + + XCTAssert(pageCount > 0) + + return pageCount + } + + func testDatabaseWriterBackup(from source: DatabaseWriter, to destination: DatabaseWriter) throws { + let sourceDbPageCount = try setupBackupSource(source) + var progressCount: Int = 1 + try source.backup(to: destination, pageStepSize: 1) { progress in + let expectedCompletedPages = progressCount + XCTAssertEqual(expectedCompletedPages, progress.completedPages) + if !progress.isFinished { + progressCount += 1 + } + } + + XCTAssertEqual(sourceDbPageCount, progressCount) + + try destination.read { db in + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) + } + + try source.write { db in + try db.execute(sql: "DROP TABLE items") + } + + try source.backup(to: destination) + + try destination.read { db in + XCTAssertFalse(try db.tableExists("items")) + } + } + + func testDatabaseBackup(from source: DatabaseWriter, to destination: DatabaseWriter) throws { + let sourceDbPageCount = try setupBackupSource(source) + try source.write { dbSource in + try destination.barrierWriteWithoutTransaction { dbDest in + var progressCount: Int = 1 + try dbSource.backup(to: dbDest, pageStepSize: 1) { progress in + let expectedCompletedPages = progressCount + XCTAssertEqual(expectedCompletedPages, progress.completedPages) + if !progress.isFinished { + progressCount += 1 + } + } + + XCTAssertEqual(sourceDbPageCount, progressCount) + } + } + + try destination.read { db in + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) + } + + try source.write { db in + try db.execute(sql: "DROP TABLE items") + } + + try source.backup(to: destination) + + try destination.read { db in + XCTAssertFalse(try db.tableExists("items")) + } + } +} diff --git a/Tests/GRDBTests/DatabasePoolBackupTests.swift b/Tests/GRDBTests/DatabasePoolBackupTests.swift index 5cb41af99..12eaac17e 100644 --- a/Tests/GRDBTests/DatabasePoolBackupTests.swift +++ b/Tests/GRDBTests/DatabasePoolBackupTests.swift @@ -1,47 +1,18 @@ -import XCTest -@testable import GRDB +import GRDB -class DatabasePoolBackupTests: GRDBTestCase { - - func testBackup() throws { +class DatabasePoolBackupTests: BackupTestCase { + + func testDatabaseWriterBackup() throws { // SQLCipher can't backup encrypted databases: use a pristine Configuration - let source = try makeDatabasePool(filename: "source.sqlite", configuration: Configuration()) - let destination = try makeDatabasePool(filename: "destination.sqlite", configuration: Configuration()) - - var pageCount: Int = 0 - try source.write { db in - try db.execute(sql: "CREATE TABLE item (id INTEGER PRIMARY KEY)") - try db.execute(sql: "INSERT INTO item (id) VALUES (NULL)") - XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM item")!, 1) - pageCount = try Int.fetchOne(db, sql: "PRAGMA page_count")! - } - - XCTAssert(pageCount > 0) - - var progressCount: Int = 1 - try source.backup(to: destination, pageStepSize: 1) { progress in - let expectedCompletedPages = Int64(progressCount) - XCTAssertEqual(expectedCompletedPages, progress.completedUnitCount) - if !progress.isFinished { - progressCount += 1 - } - } - - XCTAssertEqual(pageCount, progressCount) - - try destination.read { db in - XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM item")!, 1) - } - - try source.write { db in - try db.execute(sql: "DROP TABLE item") - } - - try source.backup(to: destination) - - try destination.read { db in - XCTAssertFalse(try db.tableExists("item")) - } + let source: DatabaseWriter = try makeDatabasePool(filename: "source.sqlite", configuration: Configuration()) + let destination: DatabaseWriter = try makeDatabasePool(filename: "destination.sqlite", configuration: Configuration()) + try testDatabaseWriterBackup(from: source, to: destination) + } + + func testDatabaseBackup() throws { + let source: DatabaseWriter = try makeDatabasePool(filename: "source.sqlite", configuration: Configuration()) + let destination: DatabaseWriter = try makeDatabasePool(filename: "destination.sqlite", configuration: Configuration()) + try testDatabaseBackup(from: source, to: destination) } // TODO: fix flaky test diff --git a/Tests/GRDBTests/DatabaseQueueBackupTests.swift b/Tests/GRDBTests/DatabaseQueueBackupTests.swift index e6cb6db99..2af8fc5dc 100644 --- a/Tests/GRDBTests/DatabaseQueueBackupTests.swift +++ b/Tests/GRDBTests/DatabaseQueueBackupTests.swift @@ -1,46 +1,17 @@ -import XCTest -@testable import GRDB +import GRDB -class DatabaseQueueBackupTests: GRDBTestCase { - - func testBackup() throws { +class DatabaseQueueBackupTests: BackupTestCase { + + func testDatabaseWriterBackup() throws { // SQLCipher can't backup encrypted databases: use a pristine Configuration - let source = try makeDatabaseQueue(filename: "source.sqlite", configuration: Configuration()) - let destination = try makeDatabaseQueue(filename: "destination.sqlite", configuration: Configuration()) - - var pageCount: Int = 0 - try source.inDatabase { db in - try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") - try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)") - XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) - pageCount = try Int.fetchOne(db, sql: "PRAGMA page_count")! - } - - XCTAssert(pageCount > 0) - - var progressCount: Int = 1 - try source.backup(to: destination, pageStepSize: 1) { progress in - let expectedCompletedPages = Int64(progressCount) - XCTAssertEqual(expectedCompletedPages, progress.completedUnitCount) - if !progress.isFinished { - progressCount += 1 - } - } - - XCTAssertEqual(pageCount, progressCount) - - try destination.inDatabase { db in - XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) - } - - try source.inDatabase { db in - try db.execute(sql: "DROP TABLE items") - } - - try source.backup(to: destination) - - try destination.inDatabase { db in - XCTAssertFalse(try db.tableExists("items")) - } + let source: DatabaseWriter = try makeDatabaseQueue(filename: "source.sqlite", configuration: Configuration()) + let destination: DatabaseWriter = try makeDatabaseQueue(filename: "destination.sqlite", configuration: Configuration()) + try testDatabaseWriterBackup(from: source, to: destination) + } + + func testDatabaseBackup() throws { + let source: DatabaseWriter = try makeDatabaseQueue(filename: "source.sqlite", configuration: Configuration()) + let destination: DatabaseWriter = try makeDatabaseQueue(filename: "destination.sqlite", configuration: Configuration()) + try testDatabaseBackup(from: source, to: destination) } } From 13e195db40838b2cce0b0c9aac74f91c8c42729b Mon Sep 17 00:00:00 2001 From: Michael Allman Date: Wed, 8 Dec 2021 09:34:52 -0800 Subject: [PATCH 05/42] Revise incremental backup API to report progress via a throwing callback function --- GRDB.xcodeproj/project.pbxproj | 22 +------ GRDB/Core/Database.swift | 86 ++++++++++++++----------- GRDB/Core/DatabaseBackupCancelled.swift | 3 - GRDB/Core/DatabaseBackupProgress.swift | 7 -- GRDB/Core/DatabaseReader.swift | 41 ++++++++++-- Tests/GRDBTests/BackupTestCase.swift | 74 ++++++++++++++++++--- 6 files changed, 151 insertions(+), 82 deletions(-) delete mode 100644 GRDB/Core/DatabaseBackupCancelled.swift delete mode 100644 GRDB/Core/DatabaseBackupProgress.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index ab80e0dbe..236ef17ab 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -10,14 +10,6 @@ 4ED4BB592731DD25008B127D /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB582731DD25008B127D /* BackupTestCase.swift */; }; 4ED4BB5A2731DD25008B127D /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB582731DD25008B127D /* BackupTestCase.swift */; }; 4ED4BB5B2731DD25008B127D /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB582731DD25008B127D /* BackupTestCase.swift */; }; - 4ED4BB602731DFC4008B127D /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB5C2731DFB0008B127D /* DatabaseBackupProgress.swift */; }; - 4ED4BB612731DFC7008B127D /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB5C2731DFB0008B127D /* DatabaseBackupProgress.swift */; }; - 4ED4BB622731DFC8008B127D /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB5C2731DFB0008B127D /* DatabaseBackupProgress.swift */; }; - 4ED4BB632731DFC8008B127D /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB5C2731DFB0008B127D /* DatabaseBackupProgress.swift */; }; - 4ED4BB652731E6AF008B127D /* DatabaseBackupCancelled.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB642731E6AF008B127D /* DatabaseBackupCancelled.swift */; }; - 4ED4BB662731E6AF008B127D /* DatabaseBackupCancelled.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB642731E6AF008B127D /* DatabaseBackupCancelled.swift */; }; - 4ED4BB672731E6AF008B127D /* DatabaseBackupCancelled.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB642731E6AF008B127D /* DatabaseBackupCancelled.swift */; }; - 4ED4BB682731E6AF008B127D /* DatabaseBackupCancelled.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB642731E6AF008B127D /* DatabaseBackupCancelled.swift */; }; 56012B552573EED000B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */; }; 56012B562573EED100B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */; }; 56012B572573EED100B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */; }; @@ -1278,8 +1270,6 @@ /* Begin PBXFileReference section */ 4ED4BB582731DD25008B127D /* BackupTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BackupTestCase.swift; sourceTree = ""; }; - 4ED4BB5C2731DFB0008B127D /* DatabaseBackupProgress.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseBackupProgress.swift; sourceTree = ""; }; - 4ED4BB642731E6AF008B127D /* DatabaseBackupCancelled.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseBackupCancelled.swift; sourceTree = ""; }; 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpressionTests.swift; sourceTree = ""; }; 56012B742574048B00B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = ""; }; 560233C32724234F00529DF3 /* SharedValueObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservation.swift; sourceTree = ""; }; @@ -1949,8 +1939,8 @@ 563363BB1C93FD32000BE133 /* DatabaseQueue */ = { isa = PBXGroup; children = ( - 5672DE581CDB72520022BA81 /* DatabaseQueueBackupTests.swift */, 5687359E1CEDE16C009B9116 /* Betty.jpeg */, + 5672DE581CDB72520022BA81 /* DatabaseQueueBackupTests.swift */, 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */, 56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */, 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */, @@ -2339,8 +2329,6 @@ 56A238711B9C75030082EB20 /* Database.swift */, 566B91221FA4CF810012D5B0 /* Database+Schema.swift */, 566B91081FA4C3960012D5B0 /* Database+Statements.swift */, - 4ED4BB642731E6AF008B127D /* DatabaseBackupCancelled.swift */, - 4ED4BB5C2731DFB0008B127D /* DatabaseBackupProgress.swift */, 566B91121FA4C3F50012D5B0 /* DatabaseCollation.swift */, 56A238731B9C75030082EB20 /* DatabaseError.swift */, 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */, @@ -3021,7 +3009,6 @@ 56FBFEDB2210731A00945324 /* SQLRequest.swift in Sources */, 56F5ABD91D814330001F60CB /* Data.swift in Sources */, 565490D41D5AE252005622CB /* (null) in Sources */, - 4ED4BB622731DFC8008B127D /* DatabaseBackupProgress.swift in Sources */, 56713FDF2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */, 566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, 565490B61D5AE236005622CB /* Configuration.swift in Sources */, @@ -3045,7 +3032,6 @@ 565490B81D5AE236005622CB /* DatabaseError.swift in Sources */, 56DAA2E11DE9C827006E10C8 /* Cursor.swift in Sources */, 5653EB0520944C7C00F46237 /* BelongsToAssociation.swift in Sources */, - 4ED4BB672731E6AF008B127D /* DatabaseBackupCancelled.swift in Sources */, 56A2FA3C24424F4800E97D23 /* Export.swift in Sources */, 565490BC1D5AE236005622CB /* DatabaseSchemaCache.swift in Sources */, 563EF42F2161180D007DAACD /* AssociationAggregate.swift in Sources */, @@ -3175,7 +3161,6 @@ 5698AC7B1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 56894FC82606589B00268F4D /* Decimal.swift in Sources */, 569D6DDF220EF9E100A058A9 /* SQLInterpolation.swift in Sources */, - 4ED4BB612731DFC7008B127D /* DatabaseBackupProgress.swift in Sources */, 56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */, 5653EB0D20944C7C00F46237 /* HasManyAssociation.swift in Sources */, 567ECE502222E431009245CA /* GRDB-5.0.swift in Sources */, @@ -3194,7 +3179,6 @@ 560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */, 5613ED4521A95B2C00DC7A68 /* ValueReducer.swift in Sources */, 560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */, - 4ED4BB662731E6AF008B127D /* DatabaseBackupCancelled.swift in Sources */, 56717272261C68EA00423B6F /* CaseInsensitiveIdentifier.swift in Sources */, 5613ED3621A95A5C00DC7A68 /* Map.swift in Sources */, 56E9FAD8221053DD00C703A8 /* SQL.swift in Sources */, @@ -3781,7 +3765,6 @@ AAA4DCCF230F1E0600C74B15 /* VirtualTableModule.swift in Sources */, 56894FD22606589D00268F4D /* Decimal.swift in Sources */, AAA4DCD0230F1E0600C74B15 /* SQLInterpolation.swift in Sources */, - 4ED4BB632731DFC8008B127D /* DatabaseBackupProgress.swift in Sources */, AAA4DCD1230F1E0600C74B15 /* DatabaseError.swift in Sources */, AAA4DCD2230F1E0600C74B15 /* HasManyAssociation.swift in Sources */, AAA4DCD3230F1E0600C74B15 /* GRDB-5.0.swift in Sources */, @@ -3800,7 +3783,6 @@ AAA4DCDF230F1E0600C74B15 /* PersistableRecord.swift in Sources */, AAA4DCE0230F1E0600C74B15 /* ValueReducer.swift in Sources */, AAA4DCE2230F1E0600C74B15 /* StatementColumnConvertible.swift in Sources */, - 4ED4BB682731E6AF008B127D /* DatabaseBackupCancelled.swift in Sources */, 56717274261C68EA00423B6F /* CaseInsensitiveIdentifier.swift in Sources */, AAA4DCE3230F1E0600C74B15 /* Map.swift in Sources */, AAA4DCE5230F1E0600C74B15 /* SQL.swift in Sources */, @@ -4152,7 +4134,6 @@ 567ECE4F2222E431009245CA /* GRDB-5.0.swift in Sources */, 56894FB72606589700268F4D /* Decimal.swift in Sources */, 56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, - 4ED4BB602731DFC4008B127D /* DatabaseBackupProgress.swift in Sources */, 56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */, 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */, 564CE43121AA901800652B19 /* ValueObserver.swift in Sources */, @@ -4171,7 +4152,6 @@ 56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */, 5605F1671C672E4000235C62 /* NSNumber.swift in Sources */, 56E9FADA221053DD00C703A8 /* SQL.swift in Sources */, - 4ED4BB652731E6AF008B127D /* DatabaseBackupCancelled.swift in Sources */, 56717271261C68E900423B6F /* CaseInsensitiveIdentifier.swift in Sources */, C96C0F2B2084A442006B2981 /* SQLiteDateParser.swift in Sources */, 56781B0B243F86E600650A83 /* Refinable.swift in Sources */, diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index d0b40defd..b5a5b817f 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1243,10 +1243,54 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - Backup + /// Copies the database contents into another database. + /// + /// The `backup` method blocks the current thread until the destination + /// database contains the same contents as the source database. + /// + /// When the source is a DatabasePool, concurrent writes can happen during + /// the backup. Those writes may, or may not, be reflected in the backup, + /// but they won't trigger any error. + /// + /// Usage: + /// + /// let source: Database = ... + /// let destination: Database = ... + /// try source.backup(to: destination) + /// + /// When you're after progress reporting during backup, you'll want to + /// perform the backup in several steps. Each step copies the number of + /// _database pages_ you specify. See + /// for more information: + /// + /// // Backup with progress reporting + /// try source.backup( + /// to: destination, + /// pagesPerStep: ..., + /// progress: { (completedPageCount, totalPageCount) in + /// print("\(completedPageCount) pages copied out of \(totalPageCount)") + /// }) + /// + /// The `progress` callback will be called at least once—when + /// `completedPageCount == totalPageCount`. If `progress` throws + /// when `completedPageCount < totalPageCount`, the backup is aborted + /// and the error is rethrown. An error thrown from `progress` when + /// `completedPageCount == totalPageCount` is silently ignored. + /// + /// - parameters: + /// - writer: The destination database. + /// - pagesPerStep: The number of database pages copied on each backup + /// step. By default, all pages are copied in one single step. + /// - progress: An optional function that is notified of the backup + /// progress. + /// - completedPageCount: The number of copied pages. + /// - totalPageCount: The total number of pages to be copied. + /// - throws: The error thrown by `progress` if the backup is abandoned, or + /// any `DatabaseError` that would happen while performing the backup. public func backup( to dbDest: Database, pageStepSize: Int32 = -1, - progress: ((DatabaseBackupProgress) -> ())? = nil) + progress: ((_ completedPageCount: Int, _ totalPageCount: Int) throws -> ())? = nil) throws { try backupInternal( @@ -1254,12 +1298,12 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib pageStepSize: pageStepSize, afterBackupStep: progress) } - + func backupInternal( to dbDest: Database, pageStepSize: Int32 = -1, afterBackupInit: (() -> Void)? = nil, - afterBackupStep: ((DatabaseBackupProgress) -> Void)? = nil) + afterBackupStep: ((_ completedPageCount: Int, _ totalPageCount: Int) throws -> Void)? = nil) throws { guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", sqliteConnection, "main") else { @@ -1271,23 +1315,17 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib afterBackupInit?() - let progress = DatabaseBackupProgressImpl() - do { backupLoop: while true { - guard !progress.cancelRequested else { - throw DatabaseBackupCancelled(progress: progress) - } let rc = sqlite3_backup_step(backup, pageStepSize) let totalPages = Int(sqlite3_backup_pagecount(backup)) let completedPages = totalPages - Int(sqlite3_backup_remaining(backup)) - progress.updateProgress(totalPages: totalPages, completedPages: completedPages) switch rc { case SQLITE_DONE: - afterBackupStep?(progress) + try? afterBackupStep?(completedPages, totalPages) break backupLoop case SQLITE_OK: - afterBackupStep?(progress) + try afterBackupStep?(completedPages, totalPages) case let code: throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage) } @@ -1307,32 +1345,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // The schema of the destination database has changed: dbDest.clearSchemaCache() } - - private class DatabaseBackupProgressImpl: DatabaseBackupProgress { - public private(set) var totalPages: Int - public private(set) var completedPages: Int - - public var isFinished: Bool { - totalPages == completedPages - } - - fileprivate var cancelRequested: Bool - - fileprivate init() { - totalPages = 0 - completedPages = 0 - cancelRequested = false - } - - public func cancel() { - cancelRequested = true - } - - fileprivate func updateProgress(totalPages: Int, completedPages: Int) { - self.totalPages = totalPages - self.completedPages = completedPages - } - } } #if SQLITE_HAS_CODEC diff --git a/GRDB/Core/DatabaseBackupCancelled.swift b/GRDB/Core/DatabaseBackupCancelled.swift deleted file mode 100644 index 2ac2eb11e..000000000 --- a/GRDB/Core/DatabaseBackupCancelled.swift +++ /dev/null @@ -1,3 +0,0 @@ -public struct DatabaseBackupCancelled: Error { - public let progress: DatabaseBackupProgress -} diff --git a/GRDB/Core/DatabaseBackupProgress.swift b/GRDB/Core/DatabaseBackupProgress.swift deleted file mode 100644 index 032118c7e..000000000 --- a/GRDB/Core/DatabaseBackupProgress.swift +++ /dev/null @@ -1,7 +0,0 @@ -public protocol DatabaseBackupProgress { - var totalPages: Int { get } - var completedPages: Int { get } - var isFinished: Bool { get } - - func cancel() -} diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 59df93632..97ee2e16c 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -279,12 +279,45 @@ extension DatabaseReader { /// the backup. Those writes may, or may not, be reflected in the backup, /// but they won't trigger any error. /// - /// The `backup` method uses the optional `progress` callback to report - /// the progress of the backup operation. + /// Usage: + /// + /// let source: DatabaseQueue = ... + /// let destination: DatabaseQueue = ... + /// try source.backup(to: destination) + /// + /// When you're after progress reporting during backup, you'll want to + /// perform the backup in several steps. Each step copies the number of + /// _database pages_ you specify. See + /// for more information: + /// + /// // Backup with progress reporting + /// try source.backup( + /// to: destination, + /// pagesPerStep: ..., + /// progress: { (completedPageCount, totalPageCount) in + /// print("\(completedPageCount) pages copied out of \(totalPageCount)") + /// }) + /// + /// The `progress` callback will be called at least once—when + /// `completedPageCount == totalPageCount`. If `progress` throws + /// when `completedPageCount < totalPageCount`, the backup is aborted + /// and the error is rethrown. An error thrown from `progress` when + /// `completedPageCount == totalPageCount` is silently ignored. + /// + /// - parameters: + /// - writer: The destination database. + /// - pagesPerStep: The number of database pages copied on each backup + /// step. By default, all pages are copied in one single step. + /// - progress: An optional function that is notified of the backup + /// progress. + /// - completedPageCount: The number of copied pages. + /// - totalPageCount: The total number of pages to be copied. + /// - throws: The error thrown by `progress` if the backup is abandoned, or + /// any `DatabaseError` that would happen while performing the backup. public func backup( to writer: DatabaseWriter, pageStepSize: Int32 = -1, - progress: ((DatabaseBackupProgress) -> ())? = nil) + progress: ((_ completedPageCount: Int, _ totalPageCount: Int) throws -> ())? = nil) throws { try writer.writeWithoutTransaction { dbDest in @@ -299,7 +332,7 @@ extension DatabaseReader { to dbDest: Database, pageStepSize: Int32 = -1, afterBackupInit: (() -> Void)? = nil, - afterBackupStep: ((DatabaseBackupProgress) -> Void)? = nil) + afterBackupStep: ((_ completedPageCount: Int, _ totalPageCount: Int) throws -> Void)? = nil) throws { try read { dbFrom in diff --git a/Tests/GRDBTests/BackupTestCase.swift b/Tests/GRDBTests/BackupTestCase.swift index 35653fa65..908d84e8e 100644 --- a/Tests/GRDBTests/BackupTestCase.swift +++ b/Tests/GRDBTests/BackupTestCase.swift @@ -3,30 +3,59 @@ import XCTest class BackupTestCase: GRDBTestCase { - func setupBackupSource(_ writer: DatabaseWriter) throws -> Int { + // A "user" error simply for testing purposes + private class AbandonBackupError: Error {} + + private func setupBackupSource(_ writer: DatabaseWriter) throws -> Int { try writer.write { db in try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") - try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)") - XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) + try db.execute(sql: "INSERT INTO items (id) VALUES (0)") } let pageCount: Int = try writer.read { db in try Int.fetchOne(db, sql: "PRAGMA page_count")! } - XCTAssert(pageCount > 0) + // pageCount must be greater than 1 to allow for incremental backup testing + XCTAssertGreaterThan(pageCount, 1) return pageCount } + private func setupBackupDestination(_ writer: DatabaseWriter) throws { + try writer.write { db in + try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") + try db.execute(sql: "INSERT INTO items (id) VALUES (1)") + } + } + func testDatabaseWriterBackup(from source: DatabaseWriter, to destination: DatabaseWriter) throws { let sourceDbPageCount = try setupBackupSource(source) + try setupBackupDestination(destination) + + XCTAssertThrowsError( + try source.backup(to: destination, pageStepSize: 1) { completedPages, totalPages in + XCTAssertLessThan(completedPages, totalPages) + throw AbandonBackupError() + } + ) + + // Assert that the items table is as it was before the backup was abandoned. + // Is this a valid assertion? + try destination.read { db in + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT id FROM items")!, 1) + } + var progressCount: Int = 1 - try source.backup(to: destination, pageStepSize: 1) { progress in + try source.backup(to: destination, pageStepSize: 1) { completedPages, totalPages in let expectedCompletedPages = progressCount - XCTAssertEqual(expectedCompletedPages, progress.completedPages) - if !progress.isFinished { + XCTAssertEqual(expectedCompletedPages, completedPages) + if completedPages != totalPages { progressCount += 1 + } else { + // Should not re-throw since completedPages == totalPages + throw AbandonBackupError() } } @@ -34,6 +63,7 @@ class BackupTestCase: GRDBTestCase { try destination.read { db in XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT id FROM items")!, 0) } try source.write { db in @@ -49,14 +79,37 @@ class BackupTestCase: GRDBTestCase { func testDatabaseBackup(from source: DatabaseWriter, to destination: DatabaseWriter) throws { let sourceDbPageCount = try setupBackupSource(source) + try setupBackupDestination(destination) + + try source.write { dbSource in + try destination.barrierWriteWithoutTransaction { dbDest in + XCTAssertThrowsError( + try dbSource.backup(to: dbDest, pageStepSize: 1) { completedPages, totalPages in + XCTAssertLessThan(completedPages, totalPages) + throw AbandonBackupError() + } + ) + } + } + + // Assert that the items table is as it was before the backup was abandoned. + // Is this a valid assertion? + try destination.read { db in + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT id FROM items")!, 1) + } + try source.write { dbSource in try destination.barrierWriteWithoutTransaction { dbDest in var progressCount: Int = 1 - try dbSource.backup(to: dbDest, pageStepSize: 1) { progress in + try dbSource.backup(to: dbDest, pageStepSize: 1) { completedPages, totalPages in let expectedCompletedPages = progressCount - XCTAssertEqual(expectedCompletedPages, progress.completedPages) - if !progress.isFinished { + XCTAssertEqual(expectedCompletedPages, completedPages) + if completedPages != totalPages { progressCount += 1 + } else { + // Should not re-throw since completedPages == totalPages + throw AbandonBackupError() } } @@ -66,6 +119,7 @@ class BackupTestCase: GRDBTestCase { try destination.read { db in XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT id FROM items")!, 0) } try source.write { db in From bedf2dbcd40662de10a8b3de972cde55d67e0ac4 Mon Sep 17 00:00:00 2001 From: Michael Allman Date: Wed, 8 Dec 2021 10:23:11 -0800 Subject: [PATCH 06/42] Revise and correct some names and backup code documentation --- GRDB/Core/Database.swift | 45 ++++++++++++++-------------- GRDB/Core/DatabaseReader.swift | 16 +++++----- Tests/GRDBTests/BackupTestCase.swift | 12 ++++---- 3 files changed, 37 insertions(+), 36 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index b5a5b817f..17ec5fec8 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1248,15 +1248,16 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// The `backup` method blocks the current thread until the destination /// database contains the same contents as the source database. /// - /// When the source is a DatabasePool, concurrent writes can happen during - /// the backup. Those writes may, or may not, be reflected in the backup, - /// but they won't trigger any error. - /// /// Usage: /// - /// let source: Database = ... - /// let destination: Database = ... - /// try source.backup(to: destination) + /// let source: DatabaseQueue = ... + /// let destination: DatabaseQueue = ... + /// try source.write { sourceDb in + /// try destination.barrierWriteWithoutTransaction { destDb in + /// try sourceDb.backup(to: destDb) + /// } + /// } + /// /// /// When you're after progress reporting during backup, you'll want to /// perform the backup in several steps. Each step copies the number of @@ -1264,8 +1265,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// for more information: /// /// // Backup with progress reporting - /// try source.backup( - /// to: destination, + /// try sourceDb.backup( + /// to: destDb, /// pagesPerStep: ..., /// progress: { (completedPageCount, totalPageCount) in /// print("\(completedPageCount) pages copied out of \(totalPageCount)") @@ -1278,7 +1279,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// `completedPageCount == totalPageCount` is silently ignored. /// /// - parameters: - /// - writer: The destination database. + /// - destDb: The destination database. /// - pagesPerStep: The number of database pages copied on each backup /// step. By default, all pages are copied in one single step. /// - progress: An optional function that is notified of the backup @@ -1288,26 +1289,26 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// - throws: The error thrown by `progress` if the backup is abandoned, or /// any `DatabaseError` that would happen while performing the backup. public func backup( - to dbDest: Database, - pageStepSize: Int32 = -1, + to destDb: Database, + pagesPerStep: Int32 = -1, progress: ((_ completedPageCount: Int, _ totalPageCount: Int) throws -> ())? = nil) throws { try backupInternal( - to: dbDest, - pageStepSize: pageStepSize, + to: destDb, + pagesPerStep: pagesPerStep, afterBackupStep: progress) } func backupInternal( - to dbDest: Database, - pageStepSize: Int32 = -1, + to destDb: Database, + pagesPerStep: Int32 = -1, afterBackupInit: (() -> Void)? = nil, afterBackupStep: ((_ completedPageCount: Int, _ totalPageCount: Int) throws -> Void)? = nil) throws { - guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", sqliteConnection, "main") else { - throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage) + guard let backup = sqlite3_backup_init(destDb.sqliteConnection, "main", sqliteConnection, "main") else { + throw DatabaseError(resultCode: destDb.lastErrorCode, message: destDb.lastErrorMessage) } guard Int(bitPattern: backup) != Int(SQLITE_ERROR) else { throw DatabaseError() @@ -1317,7 +1318,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib do { backupLoop: while true { - let rc = sqlite3_backup_step(backup, pageStepSize) + let rc = sqlite3_backup_step(backup, pagesPerStep) let totalPages = Int(sqlite3_backup_pagecount(backup)) let completedPages = totalPages - Int(sqlite3_backup_remaining(backup)) switch rc { @@ -1327,7 +1328,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib case SQLITE_OK: try afterBackupStep?(completedPages, totalPages) case let code: - throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage) + throw DatabaseError(resultCode: code, message: destDb.lastErrorMessage) } } } catch { @@ -1339,11 +1340,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib case SQLITE_OK: break case let code: - throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage) + throw DatabaseError(resultCode: code, message: destDb.lastErrorMessage) } // The schema of the destination database has changed: - dbDest.clearSchemaCache() + destDb.clearSchemaCache() } } diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 97ee2e16c..2072672dc 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -316,29 +316,29 @@ extension DatabaseReader { /// any `DatabaseError` that would happen while performing the backup. public func backup( to writer: DatabaseWriter, - pageStepSize: Int32 = -1, + pagesPerStep: Int32 = -1, progress: ((_ completedPageCount: Int, _ totalPageCount: Int) throws -> ())? = nil) throws { - try writer.writeWithoutTransaction { dbDest in + try writer.writeWithoutTransaction { destDb in try backup( - to: dbDest, - pageStepSize: pageStepSize, + to: destDb, + pagesPerStep: pagesPerStep, afterBackupStep: progress) } } func backup( - to dbDest: Database, - pageStepSize: Int32 = -1, + to destDb: Database, + pagesPerStep: Int32 = -1, afterBackupInit: (() -> Void)? = nil, afterBackupStep: ((_ completedPageCount: Int, _ totalPageCount: Int) throws -> Void)? = nil) throws { try read { dbFrom in try dbFrom.backupInternal( - to: dbDest, - pageStepSize: pageStepSize, + to: destDb, + pagesPerStep: pagesPerStep, afterBackupInit: afterBackupInit, afterBackupStep: afterBackupStep) } diff --git a/Tests/GRDBTests/BackupTestCase.swift b/Tests/GRDBTests/BackupTestCase.swift index 908d84e8e..f35d1fa87 100644 --- a/Tests/GRDBTests/BackupTestCase.swift +++ b/Tests/GRDBTests/BackupTestCase.swift @@ -34,7 +34,7 @@ class BackupTestCase: GRDBTestCase { try setupBackupDestination(destination) XCTAssertThrowsError( - try source.backup(to: destination, pageStepSize: 1) { completedPages, totalPages in + try source.backup(to: destination, pagesPerStep: 1) { completedPages, totalPages in XCTAssertLessThan(completedPages, totalPages) throw AbandonBackupError() } @@ -48,7 +48,7 @@ class BackupTestCase: GRDBTestCase { } var progressCount: Int = 1 - try source.backup(to: destination, pageStepSize: 1) { completedPages, totalPages in + try source.backup(to: destination, pagesPerStep: 1) { completedPages, totalPages in let expectedCompletedPages = progressCount XCTAssertEqual(expectedCompletedPages, completedPages) if completedPages != totalPages { @@ -81,10 +81,10 @@ class BackupTestCase: GRDBTestCase { let sourceDbPageCount = try setupBackupSource(source) try setupBackupDestination(destination) - try source.write { dbSource in - try destination.barrierWriteWithoutTransaction { dbDest in + try source.write { sourceDb in + try destination.barrierWriteWithoutTransaction { destDb in XCTAssertThrowsError( - try dbSource.backup(to: dbDest, pageStepSize: 1) { completedPages, totalPages in + try sourceDb.backup(to: destDb, pagesPerStep: 1) { completedPages, totalPages in XCTAssertLessThan(completedPages, totalPages) throw AbandonBackupError() } @@ -102,7 +102,7 @@ class BackupTestCase: GRDBTestCase { try source.write { dbSource in try destination.barrierWriteWithoutTransaction { dbDest in var progressCount: Int = 1 - try dbSource.backup(to: dbDest, pageStepSize: 1) { completedPages, totalPages in + try dbSource.backup(to: dbDest, pagesPerStep: 1) { completedPages, totalPages in let expectedCompletedPages = progressCount XCTAssertEqual(expectedCompletedPages, completedPages) if completedPages != totalPages { From a71639159ba1cfd167772658dcc125c3bf02e9bf Mon Sep 17 00:00:00 2001 From: Michael Allman Date: Wed, 15 Dec 2021 01:52:25 -0500 Subject: [PATCH 07/42] Add DatabaseBackupProgress and update the documentation --- GRDB.xcodeproj/project.pbxproj | 10 +++++++ GRDB/Core/Database.swift | 32 ++++++++++++--------- GRDB/Core/DatabaseBackupProgress.swift | 17 +++++++++++ GRDB/Core/DatabaseReader.swift | 25 +++++++++-------- GRDBCustom.xcodeproj/project.pbxproj | 18 ++++-------- README.md | 36 ++++++++++++++++++++++++ Tests/GRDBTests/BackupTestCase.swift | 39 +++++++++++++++----------- 7 files changed, 123 insertions(+), 54 deletions(-) create mode 100644 GRDB/Core/DatabaseBackupProgress.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 236ef17ab..838ad3427 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -7,6 +7,10 @@ objects = { /* Begin PBXBuildFile section */ + 4E13D2F32769B87F0037588C /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */; }; + 4E13D2F42769B87F0037588C /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */; }; + 4E13D2F52769B87F0037588C /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */; }; + 4E13D2F62769B87F0037588C /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */; }; 4ED4BB592731DD25008B127D /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB582731DD25008B127D /* BackupTestCase.swift */; }; 4ED4BB5A2731DD25008B127D /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB582731DD25008B127D /* BackupTestCase.swift */; }; 4ED4BB5B2731DD25008B127D /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB582731DD25008B127D /* BackupTestCase.swift */; }; @@ -1269,6 +1273,7 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ + 4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseBackupProgress.swift; sourceTree = ""; }; 4ED4BB582731DD25008B127D /* BackupTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BackupTestCase.swift; sourceTree = ""; }; 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpressionTests.swift; sourceTree = ""; }; 56012B742574048B00B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = ""; }; @@ -2329,6 +2334,7 @@ 56A238711B9C75030082EB20 /* Database.swift */, 566B91221FA4CF810012D5B0 /* Database+Schema.swift */, 566B91081FA4C3960012D5B0 /* Database+Statements.swift */, + 4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */, 566B91121FA4C3F50012D5B0 /* DatabaseCollation.swift */, 56A238731B9C75030082EB20 /* DatabaseError.swift */, 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */, @@ -2918,6 +2924,7 @@ 565490CE1D5AE252005622CB /* NSNull.swift in Sources */, 5656A8202295B12F001FF3FF /* SQLAssociation.swift in Sources */, 565490E41D5AE252005622CB /* TableRecord.swift in Sources */, + 4E13D2F52769B87F0037588C /* DatabaseBackupProgress.swift in Sources */, 564CE5AE21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */, 565490CF1D5AE252005622CB /* NSNumber.swift in Sources */, 56CEB51F1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, @@ -3121,6 +3128,7 @@ 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */, 56A2FA3B24424F4700E97D23 /* Export.swift in Sources */, 569BBA4F229170F900478429 /* Inflections+English.swift in Sources */, + 4E13D2F42769B87F0037588C /* DatabaseBackupProgress.swift in Sources */, 5656A81F2295B12F001FF3FF /* SQLAssociation.swift in Sources */, 5617294F223533F40006E219 /* EncodableRecord.swift in Sources */, 563B8FAD24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */, @@ -3725,6 +3733,7 @@ AAA4DCA7230F1E0600C74B15 /* TableRecord.swift in Sources */, 56A2FA3D24424F4800E97D23 /* Export.swift in Sources */, AAA4DCA8230F1E0600C74B15 /* Inflections+English.swift in Sources */, + 4E13D2F62769B87F0037588C /* DatabaseBackupProgress.swift in Sources */, AAA4DCA9230F1E0600C74B15 /* SQLAssociation.swift in Sources */, AAA4DCAA230F1E0600C74B15 /* EncodableRecord.swift in Sources */, 563B8FAF24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */, @@ -4094,6 +4103,7 @@ 5698AD181DAAD17A0056AF8C /* FTS5Tokenizer.swift in Sources */, 56A2FA3624424D2A00E97D23 /* Export.swift in Sources */, 56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, + 4E13D2F32769B87F0037588C /* DatabaseBackupProgress.swift in Sources */, 560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */, 563B8FAC24A1CE43007A48C9 /* DatabasePublishers.swift in Sources */, 5605F1691C672E4000235C62 /* NSString.swift in Sources */, diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 17ec5fec8..6af3e1d44 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1267,16 +1267,19 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// // Backup with progress reporting /// try sourceDb.backup( /// to: destDb, - /// pagesPerStep: ..., - /// progress: { (completedPageCount, totalPageCount) in - /// print("\(completedPageCount) pages copied out of \(totalPageCount)") - /// }) + /// pagesPerStep: ...) + /// { backupProgress in + /// print("Database backup progress:", backupProgress) + /// } /// /// The `progress` callback will be called at least once—when - /// `completedPageCount == totalPageCount`. If `progress` throws - /// when `completedPageCount < totalPageCount`, the backup is aborted - /// and the error is rethrown. An error thrown from `progress` when - /// `completedPageCount == totalPageCount` is silently ignored. + /// `backupProgress.isCompleted == true`. If the callback throws + /// when `backupProgress.isCompleted == false`, the backup is aborted + /// and the error is rethrown. If the callback throws when + /// `backupProgress.isCompleted == true`, backup completion is + /// unaffected and the error is silently ignored. + /// + /// See also `DatabaseReader.backup()`. /// /// - parameters: /// - destDb: The destination database. @@ -1284,14 +1287,12 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// step. By default, all pages are copied in one single step. /// - progress: An optional function that is notified of the backup /// progress. - /// - completedPageCount: The number of copied pages. - /// - totalPageCount: The total number of pages to be copied. /// - throws: The error thrown by `progress` if the backup is abandoned, or /// any `DatabaseError` that would happen while performing the backup. public func backup( to destDb: Database, pagesPerStep: Int32 = -1, - progress: ((_ completedPageCount: Int, _ totalPageCount: Int) throws -> ())? = nil) + progress: ((DatabaseBackupProgress) throws -> ())? = nil) throws { try backupInternal( @@ -1304,7 +1305,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib to destDb: Database, pagesPerStep: Int32 = -1, afterBackupInit: (() -> Void)? = nil, - afterBackupStep: ((_ completedPageCount: Int, _ totalPageCount: Int) throws -> Void)? = nil) + afterBackupStep: ((DatabaseBackupProgress) throws -> Void)? = nil) throws { guard let backup = sqlite3_backup_init(destDb.sqliteConnection, "main", sqliteConnection, "main") else { @@ -1321,12 +1322,15 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib let rc = sqlite3_backup_step(backup, pagesPerStep) let totalPages = Int(sqlite3_backup_pagecount(backup)) let completedPages = totalPages - Int(sqlite3_backup_remaining(backup)) + let progress = DatabaseBackupProgress(completedPageCount: completedPages, + totalPageCount: totalPages, + isCompleted: rc == SQLITE_DONE) switch rc { case SQLITE_DONE: - try? afterBackupStep?(completedPages, totalPages) + try? afterBackupStep?(progress) break backupLoop case SQLITE_OK: - try afterBackupStep?(completedPages, totalPages) + try afterBackupStep?(progress) case let code: throw DatabaseError(resultCode: code, message: destDb.lastErrorMessage) } diff --git a/GRDB/Core/DatabaseBackupProgress.swift b/GRDB/Core/DatabaseBackupProgress.swift new file mode 100644 index 000000000..5c5ee6a57 --- /dev/null +++ b/GRDB/Core/DatabaseBackupProgress.swift @@ -0,0 +1,17 @@ +/// An instance of `DatabaseBackupProgress` is passed to a callback of the +/// `DatabaseReader.backup` or `Database.backup` methods to report +/// database backup progress to the caller. +/// +/// This is an advanced API for expert users. It is based directly on the SQLite +/// [online backup API](https://www.sqlite.org/c3ref/backup_finish.html). +/// +/// This struct is not meant to be instantiated by users. +public struct DatabaseBackupProgress { + /// Completed page count is defined as `sqlite3_backup_pagecount() - sqlite3_backup_remaining()` + public let completedPageCount: Int + /// Total page count is defined by the `sqlite3_backup_pagecount` function + public let totalPageCount: Int + /// This property is true if and only if `sqlite3_backup_step()` returns + /// `SQLITE_DONE` + public let isCompleted: Bool +} diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 2072672dc..0f95c7d25 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -293,16 +293,19 @@ extension DatabaseReader { /// // Backup with progress reporting /// try source.backup( /// to: destination, - /// pagesPerStep: ..., - /// progress: { (completedPageCount, totalPageCount) in - /// print("\(completedPageCount) pages copied out of \(totalPageCount)") - /// }) + /// pagesPerStep: ...) + /// { backupProgress in + /// print("Database backup progress:", backupProgress) + /// } /// /// The `progress` callback will be called at least once—when - /// `completedPageCount == totalPageCount`. If `progress` throws - /// when `completedPageCount < totalPageCount`, the backup is aborted - /// and the error is rethrown. An error thrown from `progress` when - /// `completedPageCount == totalPageCount` is silently ignored. + /// `backupProgress.isCompleted == true`. If the callback throws + /// when `backupProgress.isCompleted == false`, the backup is aborted + /// and the error is rethrown. If the callback throws when + /// `backupProgress.isCompleted == true`, backup completion is + /// unaffected and the error is silently ignored. + /// + /// See also `Database.backup()`. /// /// - parameters: /// - writer: The destination database. @@ -310,14 +313,12 @@ extension DatabaseReader { /// step. By default, all pages are copied in one single step. /// - progress: An optional function that is notified of the backup /// progress. - /// - completedPageCount: The number of copied pages. - /// - totalPageCount: The total number of pages to be copied. /// - throws: The error thrown by `progress` if the backup is abandoned, or /// any `DatabaseError` that would happen while performing the backup. public func backup( to writer: DatabaseWriter, pagesPerStep: Int32 = -1, - progress: ((_ completedPageCount: Int, _ totalPageCount: Int) throws -> ())? = nil) + progress: ((DatabaseBackupProgress) throws -> ())? = nil) throws { try writer.writeWithoutTransaction { destDb in @@ -332,7 +333,7 @@ extension DatabaseReader { to destDb: Database, pagesPerStep: Int32 = -1, afterBackupInit: (() -> Void)? = nil, - afterBackupStep: ((_ completedPageCount: Int, _ totalPageCount: Int) throws -> Void)? = nil) + afterBackupStep: ((DatabaseBackupProgress) throws -> Void)? = nil) throws { try read { dbFrom in diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index d7d2f47cb..ce661caad 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -7,10 +7,8 @@ objects = { /* Begin PBXBuildFile section */ - 4ECF7776273AFAFD001685F5 /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ECF7773273AFAFD001685F5 /* DatabaseBackupProgress.swift */; }; - 4ECF7777273AFAFD001685F5 /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ECF7773273AFAFD001685F5 /* DatabaseBackupProgress.swift */; }; - 4ECF7778273AFAFD001685F5 /* DatabaseBackupCancelled.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ECF7775273AFAFD001685F5 /* DatabaseBackupCancelled.swift */; }; - 4ECF7779273AFAFD001685F5 /* DatabaseBackupCancelled.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ECF7775273AFAFD001685F5 /* DatabaseBackupCancelled.swift */; }; + 4E13D2F82769BC230037588C /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E13D2F72769BC230037588C /* DatabaseBackupProgress.swift */; }; + 4E13D2F92769BC230037588C /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E13D2F72769BC230037588C /* DatabaseBackupProgress.swift */; }; 4ECF777D273AFBA9001685F5 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ECF777A273AFB72001685F5 /* BackupTestCase.swift */; }; 4ECF777E273AFBAB001685F5 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ECF777A273AFB72001685F5 /* BackupTestCase.swift */; }; 56012B6A2573FAE700B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B682573FAE600B4925B /* CommonTableExpressionTests.swift */; }; @@ -778,8 +776,7 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 4ECF7773273AFAFD001685F5 /* DatabaseBackupProgress.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseBackupProgress.swift; sourceTree = ""; }; - 4ECF7775273AFAFD001685F5 /* DatabaseBackupCancelled.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseBackupCancelled.swift; sourceTree = ""; }; + 4E13D2F72769BC230037588C /* DatabaseBackupProgress.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseBackupProgress.swift; sourceTree = ""; }; 4ECF777A273AFB72001685F5 /* BackupTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BackupTestCase.swift; sourceTree = ""; }; 56012B682573FAE600B4925B /* CommonTableExpressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CommonTableExpressionTests.swift; sourceTree = ""; }; 56012B80257404A300B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = ""; }; @@ -1796,8 +1793,7 @@ 56A238711B9C75030082EB20 /* Database.swift */, 566B91221FA4CF810012D5B0 /* Database+Schema.swift */, 566B91081FA4C3960012D5B0 /* Database+Statements.swift */, - 4ECF7775273AFAFD001685F5 /* DatabaseBackupCancelled.swift */, - 4ECF7773273AFAFD001685F5 /* DatabaseBackupProgress.swift */, + 4E13D2F72769BC230037588C /* DatabaseBackupProgress.swift */, 566B91121FA4C3F50012D5B0 /* DatabaseCollation.swift */, 56A238731B9C75030082EB20 /* DatabaseError.swift */, 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */, @@ -2355,6 +2351,7 @@ 5656A87E2295BD56001FF3FF /* SQLAssociation.swift in Sources */, F3BA80131CFB2876003DC1BA /* DatabaseValue.swift in Sources */, 56C0539822ACEECD0029D27D /* ValueReducer.swift in Sources */, + 4E13D2F92769BC230037588C /* DatabaseBackupProgress.swift in Sources */, 56A2FA3A24424F4200E97D23 /* Export.swift in Sources */, 56B964B61DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, F3BA80171CFB2876003DC1BA /* RowAdapter.swift in Sources */, @@ -2395,8 +2392,6 @@ 5656A8A82295BF44001FF3FF /* DatabasePromise.swift in Sources */, 5656A86E2295BD56001FF3FF /* HasManyThroughAssociation.swift in Sources */, 56894FE8260658A500268F4D /* Decimal.swift in Sources */, - 4ECF7779273AFAFD001685F5 /* DatabaseBackupCancelled.swift in Sources */, - 4ECF7777273AFAFD001685F5 /* DatabaseBackupProgress.swift in Sources */, 566BE7162342541F00A8254B /* LockedBox.swift in Sources */, F3BA80111CFB2876003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80281CFB2891003DC1BA /* StandardLibrary.swift in Sources */, @@ -2725,6 +2720,7 @@ 5656A87D2295BD56001FF3FF /* SQLAssociation.swift in Sources */, F3BA806F1CFB2E55003DC1BA /* DatabaseValue.swift in Sources */, 56C0539722ACEECD0029D27D /* ValueReducer.swift in Sources */, + 4E13D2F82769BC230037588C /* DatabaseBackupProgress.swift in Sources */, 56A2FA3924424F4200E97D23 /* Export.swift in Sources */, 56B964B31DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, F3BA80731CFB2E55003DC1BA /* RowAdapter.swift in Sources */, @@ -2765,8 +2761,6 @@ 5656A8A72295BF44001FF3FF /* DatabasePromise.swift in Sources */, 5656A86D2295BD56001FF3FF /* HasManyThroughAssociation.swift in Sources */, 56894FE3260658A400268F4D /* Decimal.swift in Sources */, - 4ECF7778273AFAFD001685F5 /* DatabaseBackupCancelled.swift in Sources */, - 4ECF7776273AFAFD001685F5 /* DatabaseBackupProgress.swift in Sources */, 566BE7152342541F00A8254B /* LockedBox.swift in Sources */, F3BA806D1CFB2E55003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */, diff --git a/README.md b/README.md index 0e8e1f6c1..16110663c 100644 --- a/README.md +++ b/README.md @@ -7036,6 +7036,42 @@ The `backup` method blocks the current thread until the destination database con When the source is a [database pool](#database-pools), concurrent writes can happen during the backup. Those writes may, or may not, be reflected in the backup, but they won't trigger any error. +`Database` has an analogous `backup` method. + +```swift +let source: DatabaseQueue = ... // or DatabasePool +let destination: DatabaseQueue = ... // or DatabasePool +try source.write { sourceDb in + try destination.barrierWriteWithoutTransaction { destDb in + try sourceDb.backup(to: destDb) + } +} +``` + +This method allows for the choice of source and destination `Database` handles with which to backup the database. + +### Backup Progress Reporting + +The `backup` methods take optional `pagesPerStep` and `progress` parameters. Together these parameters can be used to track a database backup in progress and abort an incomplete backup. + +When `pagesPerStep` is provided, the database backup is performed in _steps_. At each step, no more than `pagesPerStep` database pages are copied from the source to the destination. The backup proceeds one step at a time until all pages have been copied. + +When a `progress` callback is provided, `progress` is called after every backup step, including the last. Even if a non-default `pagesPerStep` is specified or the backup is otherwise completed in a single step, the `progress` callback will be called. + +```swift +try source.backup( + to: destination, + pagesPerStep: ...) + { backupProgress in + print("Database backup progress:", backupProgress) + } +``` + +### Aborting an Incomplete Backup + +If a call to `progress` throws when `backupProgress.isComplete == false`, the backup will be aborted and the error rethrown. However, if a call to `progress` throws when `backupProgress.isComplete == true`, the backup is unaffected and the error is silently ignored. + +> :warning: **Warning**: Passing non-default values of `pagesPerStep` or `progress` to the backup methods is an advanced API intended to provide additional capabilities to expert users. GRDB's backup API provides a faithful, low-level wrapper to the underlying SQLite online backup API. GRDB's documentation is not a comprehensive substitute for the official SQLite [documentation of their backup API](https://www.sqlite.org/c3ref/backup_finish.html). ## Interrupt a Database diff --git a/Tests/GRDBTests/BackupTestCase.swift b/Tests/GRDBTests/BackupTestCase.swift index f35d1fa87..f4474f9b9 100644 --- a/Tests/GRDBTests/BackupTestCase.swift +++ b/Tests/GRDBTests/BackupTestCase.swift @@ -34,32 +34,35 @@ class BackupTestCase: GRDBTestCase { try setupBackupDestination(destination) XCTAssertThrowsError( - try source.backup(to: destination, pagesPerStep: 1) { completedPages, totalPages in - XCTAssertLessThan(completedPages, totalPages) + try source.backup(to: destination, pagesPerStep: 1) { progress in + XCTAssertLessThan(progress.completedPageCount, progress.totalPageCount) + XCTAssertFalse(progress.isCompleted) throw AbandonBackupError() } ) - // Assert that the items table is as it was before the backup was abandoned. - // Is this a valid assertion? try destination.read { db in XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT id FROM items")!, 1) } var progressCount: Int = 1 - try source.backup(to: destination, pagesPerStep: 1) { completedPages, totalPages in + var isCompleted: Bool = false + try source.backup(to: destination, pagesPerStep: 1) { progress in let expectedCompletedPages = progressCount - XCTAssertEqual(expectedCompletedPages, completedPages) - if completedPages != totalPages { + XCTAssertEqual(expectedCompletedPages, progress.completedPageCount) + if progress.completedPageCount != progress.totalPageCount { progressCount += 1 - } else { - // Should not re-throw since completedPages == totalPages + } + if progress.isCompleted { + isCompleted = true + // Should not re-throw throw AbandonBackupError() } } XCTAssertEqual(sourceDbPageCount, progressCount) + XCTAssertTrue(isCompleted) try destination.read { db in XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) @@ -84,8 +87,8 @@ class BackupTestCase: GRDBTestCase { try source.write { sourceDb in try destination.barrierWriteWithoutTransaction { destDb in XCTAssertThrowsError( - try sourceDb.backup(to: destDb, pagesPerStep: 1) { completedPages, totalPages in - XCTAssertLessThan(completedPages, totalPages) + try sourceDb.backup(to: destDb, pagesPerStep: 1) { progress in + XCTAssertLessThan(progress.completedPageCount, progress.totalPageCount) throw AbandonBackupError() } ) @@ -102,18 +105,22 @@ class BackupTestCase: GRDBTestCase { try source.write { dbSource in try destination.barrierWriteWithoutTransaction { dbDest in var progressCount: Int = 1 - try dbSource.backup(to: dbDest, pagesPerStep: 1) { completedPages, totalPages in + var isCompleted: Bool = false + try dbSource.backup(to: dbDest, pagesPerStep: 1) { progress in let expectedCompletedPages = progressCount - XCTAssertEqual(expectedCompletedPages, completedPages) - if completedPages != totalPages { + XCTAssertEqual(expectedCompletedPages, progress.completedPageCount) + if progress.completedPageCount != progress.totalPageCount { progressCount += 1 - } else { - // Should not re-throw since completedPages == totalPages + } + if progress.isCompleted { + isCompleted = true + // Should not re-throw throw AbandonBackupError() } } XCTAssertEqual(sourceDbPageCount, progressCount) + XCTAssertTrue(isCompleted) } } From c96a74658c90b307051550b8752279a83a1af3d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 19 Dec 2021 12:19:45 +0100 Subject: [PATCH 08/42] TODO --- TODO.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/TODO.md b/TODO.md index a6b4afd0f..633a620a4 100644 --- a/TODO.md +++ b/TODO.md @@ -23,6 +23,9 @@ - [ ] Grab all FTS tokens in a string - [ ] GRDB 6: decoding errors - [ ] GRDB 6: conflict resolution in persistence methods +- [ ] GRDB 6: UPSERT +- [ ] GRDB 6: support for RETURNING +- [ ] GRDB 6: allow mutating `update` (for timestamps) - [ ] Long run edition. Use case: user edits the database (CRUD) but the application wants to commmit and the end of the editing session. * Create an edition SQLite connection with an open transaction (a new kind of DatabaseWriter with a save() method) * All other writes will fail with SQLITE_BUSY. Unless they are schedules in a target dispatch queue which is paused during the edition. @@ -37,7 +40,6 @@ - [ ] Support for more kinds of joins: https://github.com/groue/GRDB.swift/issues/740 - [ ] HasAndBelongsToMany: https://github.com/groue/GRDB.swift/issues/711 - [ ] Support UNION https://github.com/groue/GRDB.swift/issues/671 (https://www.sqlite.org/lang_select.html#compound) -- [ ] request.exists(db) as an alternative to fetchOne(db) != nil. Can generate optimized SQL. - [ ] Measure the duration of transactions - [ ] Improve SQL generation for `Player.....fetchCount(db)`, especially with distinct. Try to avoid `SELECT COUNT(*) FROM (SELECT DISTINCT player.* ...)` - [ ] Alternative technique for custom SQLite builds: see the Podfile at https://github.com/CocoaPods/CocoaPods/issues/9104, and https://github.com/clemensg/sqlite3pod @@ -52,7 +54,6 @@ - [ ] CASE x WHEN w1 THEN r1 WHEN w2 THEN r2 ELSE r3 END https://www.sqlite.org/lang_expr.html - [ ] Allow concurrent reads from a snapshot - [ ] Check https://sqlite.org/sqlar.html -- [ ] FTS: prefix queries - [ ] More schema alterations - [ ] Database.clearSchemaCache() is fine, but what about dbPool readers? Can we invalidate the cache for a whole pool? From 82179662150a011793bd935a78d7fd4df518b16a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 21 Dec 2021 09:24:12 +0100 Subject: [PATCH 09/42] Table creation methods accept throwing closures --- GRDB/QueryInterface/Schema/TableDefinition.swift | 4 ++-- GRDB/QueryInterface/Schema/VirtualTableModule.swift | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index b80dbcf92..ad0918e2b 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -29,7 +29,7 @@ extension Database { temporary: Bool = false, ifNotExists: Bool = false, withoutRowID: Bool = false, - body: (TableDefinition) -> Void) + body: (TableDefinition) throws -> Void) throws { let definition = TableDefinition( @@ -37,7 +37,7 @@ extension Database { temporary: temporary, ifNotExists: ifNotExists, withoutRowID: withoutRowID) - body(definition) + try body(definition) let sql = try definition.sql(self) try execute(sql: sql) } diff --git a/GRDB/QueryInterface/Schema/VirtualTableModule.swift b/GRDB/QueryInterface/Schema/VirtualTableModule.swift index 4907d8342..cb6c53f90 100644 --- a/GRDB/QueryInterface/Schema/VirtualTableModule.swift +++ b/GRDB/QueryInterface/Schema/VirtualTableModule.swift @@ -126,14 +126,14 @@ extension Database { virtualTable tableName: String, ifNotExists: Bool = false, using module: Module, - _ body: ((Module.TableDefinition) -> Void)? = nil) + _ body: ((Module.TableDefinition) throws -> Void)? = nil) throws { // Define virtual table let configuration = VirtualTableConfiguration(ifNotExists: ifNotExists) let definition = module.makeTableDefinition(configuration: configuration) if let body = body { - body(definition) + try body(definition) } // Create virtual table From c945504a345f786543b7b2cd2848dcfb01d7720b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 21 Dec 2021 11:13:28 +0100 Subject: [PATCH 10/42] Addition and substraction are not bijective functions (due to floating point rounding errors) --- GRDB/QueryInterface/SQL/SQLExpression.swift | 19 +++---------------- .../SQLExpressionIsConstantTests.swift | 10 +++++----- Tests/GRDBTests/TableRecordDeleteTests.swift | 9 --------- 3 files changed, 8 insertions(+), 30 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 8bf1e2fe3..b703d63b5 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -189,9 +189,9 @@ public struct SQLExpression { /// If true, (a • b) is a bijective function of a, and a bijective /// function of b. /// - /// `+` and `||` (concat) are bijective. + /// `||` (concat) is bijective. /// - /// `AND`, `OR` and `*` are not. + /// `AND`, `OR`, `+` and `*` are not. let isBijective: Bool /// Creates a binary operator @@ -212,7 +212,7 @@ public struct SQLExpression { sql: "+", neutralValue: 0.databaseValue, strictlyAssociative: false, - bijective: true) + bijective: false) /// The `*` binary operator /// @@ -818,19 +818,6 @@ extension SQLExpression { return nil } - case let .binary(op, lhs, rhs): - guard acceptsBijection && op == .subtract else { - return nil - } - - if lhs.isConstantInRequest { - return try rhs.column(db, for: alias, acceptsBijection: acceptsBijection) - } else if rhs.isConstantInRequest { - return try lhs.column(db, for: alias, acceptsBijection: acceptsBijection) - } else { - return nil - } - case let .associativeBinary(op, expressions): assert(expressions.count > 1) guard acceptsBijection && op.isBijective else { diff --git a/Tests/GRDBTests/SQLExpressionIsConstantTests.swift b/Tests/GRDBTests/SQLExpressionIsConstantTests.swift index d4f5050ba..9c2f87f95 100644 --- a/Tests/GRDBTests/SQLExpressionIsConstantTests.swift +++ b/Tests/GRDBTests/SQLExpressionIsConstantTests.swift @@ -27,7 +27,7 @@ class SQLExpressionIsConstantTests: GRDBTestCase { try XCTAssertEqual((alias[Column("a")] * "foo".databaseValue).column(db, for: alias, acceptsBijection: false), nil) try XCTAssertEqual((alias[Column("a")] * "foo".databaseValue).column(db, for: alias, acceptsBijection: true), nil) try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue).column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue).column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue).column(db, for: alias, acceptsBijection: true), nil) try XCTAssertEqual((alias[Column("a")] + alias[Column("b")]).column(db, for: alias, acceptsBijection: false), nil) try XCTAssertEqual((alias[Column("a")] + alias[Column("b")]).column(db, for: alias, acceptsBijection: true), nil) try XCTAssertEqual([alias[Column("a")], "foo".databaseValue].joined(operator: .concat).column(db, for: alias, acceptsBijection: false), nil) @@ -39,7 +39,7 @@ class SQLExpressionIsConstantTests: GRDBTestCase { // SQLExpressionBinary try XCTAssertEqual((alias[Column("a")] - "foo".databaseValue).column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual((alias[Column("a")] - "foo".databaseValue).column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual((alias[Column("a")] - "foo".databaseValue).column(db, for: alias, acceptsBijection: true), nil) try XCTAssertEqual((alias[Column("a")] - alias[Column("b")]).column(db, for: alias, acceptsBijection: false), nil) try XCTAssertEqual((alias[Column("a")] - alias[Column("b")]).column(db, for: alias, acceptsBijection: true), nil) try XCTAssertEqual((alias[Column("a")] < "foo".databaseValue).column(db, for: alias, acceptsBijection: false), nil) @@ -51,7 +51,7 @@ class SQLExpressionIsConstantTests: GRDBTestCase { try XCTAssertEqual(alias[Column("a")].collating(.binary).column(db, for: alias, acceptsBijection: false), "a") try XCTAssertEqual(alias[Column("a")].collating(.binary).column(db, for: alias, acceptsBijection: true), "a") try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue).collating(.binary).column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue).collating(.binary).column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue).collating(.binary).column(db, for: alias, acceptsBijection: true), nil) // SQLExpressionContains try XCTAssertEqual([1, 2, 3].contains(alias[Column("a")]).column(db, for: alias, acceptsBijection: false), nil) @@ -169,8 +169,8 @@ class SQLExpressionIsConstantTests: GRDBTestCase { try XCTAssertEqual((1 == alias[Column("a")]).identifyingColums(db, for: alias), ["a"]) try XCTAssertEqual((-alias[Column("a")] == 1).identifyingColums(db, for: alias), ["a"]) try XCTAssertEqual(((alias[Column("a")] * 2) == 1).identifyingColums(db, for: alias), []) - try XCTAssertEqual(((alias[Column("a")] + 2) == 1).identifyingColums(db, for: alias), ["a"]) - try XCTAssertEqual(((alias[Column("a")] - 2) == 1).identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual(((alias[Column("a")] + 2) == 1).identifyingColums(db, for: alias), []) + try XCTAssertEqual(((alias[Column("a")] - 2) == 1).identifyingColums(db, for: alias), []) try XCTAssertEqual((alias[SQLExpression.fastPrimaryKey] == 1).identifyingColums(db, for: alias), ["id"]) try XCTAssertEqual((alias[Column("a")] == alias[Column("b")]).identifyingColums(db, for: alias), []) try XCTAssertEqual((TableAlias()[Column("a")] == nil).identifyingColums(db, for: alias), []) diff --git a/Tests/GRDBTests/TableRecordDeleteTests.swift b/Tests/GRDBTests/TableRecordDeleteTests.swift index d1b5a2965..07e60e613 100644 --- a/Tests/GRDBTests/TableRecordDeleteTests.swift +++ b/Tests/GRDBTests/TableRecordDeleteTests.swift @@ -312,15 +312,6 @@ class TableRecordDeleteTests: GRDBTestCase { GROUP BY "id") """) } - do { - try Player.all().group(Column.rowID + 1).deleteAll(db) - XCTAssertEqual(self.lastSQLQuery, """ - DELETE FROM "player" WHERE "id" IN (\ - SELECT "id" \ - FROM "player" \ - GROUP BY "rowid" + 1) - """) - } do { try Player.all().group(-Column("id")).deleteAll(db) XCTAssertEqual(self.lastSQLQuery, """ From bf28abbb257846427ff3341aa961f579e8ebe049 Mon Sep 17 00:00:00 2001 From: Joseph Ross Date: Tue, 28 Dec 2021 14:49:33 -0800 Subject: [PATCH 11/42] Fix typos of the word "default" --- Documentation/AssociationsBasics.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 6ddca9107..293d0b4d5 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -891,7 +891,7 @@ struct Author: TableRecord { static let databaseTableName = "writer" } struct Book: TableRecord { - // Replace the defaut "writer" association key with "author" + // Replace the default "writer" association key with "author" static let author = belongsTo(Author.self).forKey("author") } @@ -1034,7 +1034,7 @@ struct Book: TableRecord { static let databaseTableName = "publication" } struct Author: TableRecord { - // Replace the defaut "publications" association key with "books" + // Replace the default "publications" association key with "books" static let books = hasMany(Book.self).forKey("books") } From 4a3232199f102140108ead92ed89cd58213113e2 Mon Sep 17 00:00:00 2001 From: Ben Yohay Date: Wed, 29 Dec 2021 14:06:18 +0200 Subject: [PATCH 12/42] GRDB: quote `PROJECT_DIR` and `SRCROOT` environment variables. Using those variables without quoting will yield unexpected results if they contain spaces. --- GRDB.xcodeproj/project.pbxproj | 6 +++--- GRDBCustom.xcodeproj/project.pbxproj | 4 ++-- Scripts/swiftlint.sh | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 5a1a122d4..0e9aa5d59 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -2861,7 +2861,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "${PROJECT_DIR}/Scripts/swiftlint.sh\n"; + shellScript = "\"${PROJECT_DIR}/Scripts/swiftlint.sh\"\n"; }; 56EB54FA22C9115E00850069 /* Swiftlint */ = { isa = PBXShellScriptBuildPhase; @@ -2879,7 +2879,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "${PROJECT_DIR}/Scripts/swiftlint.sh\n"; + shellScript = "\"${PROJECT_DIR}/Scripts/swiftlint.sh\"\n"; }; AAA4DCFA230F1E0600C74B15 /* Swiftlint */ = { isa = PBXShellScriptBuildPhase; @@ -2897,7 +2897,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "${PROJECT_DIR}/Scripts/swiftlint.sh\n"; + shellScript = "\"${PROJECT_DIR}/Scripts/swiftlint.sh\"\n"; }; /* End PBXShellScriptBuildPhase section */ diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 921bf2c8e..c69d0f931 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -2227,7 +2227,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "${PROJECT_DIR}/Scripts/swiftlint.sh\n"; + shellScript = "\"${PROJECT_DIR}/Scripts/swiftlint.sh\"\n"; }; 56EB54FD22C9119B00850069 /* Swiftlint */ = { isa = PBXShellScriptBuildPhase; @@ -2245,7 +2245,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "${PROJECT_DIR}/Scripts/swiftlint.sh\n"; + shellScript = "\"${PROJECT_DIR}/Scripts/swiftlint.sh\"\n"; }; EED476F01CFD0B290026A4EC /* Copy .example configuration files (if no USER customizations exist) */ = { isa = PBXShellScriptBuildPhase; diff --git a/Scripts/swiftlint.sh b/Scripts/swiftlint.sh index 7781c40d8..02da30ab1 100755 --- a/Scripts/swiftlint.sh +++ b/Scripts/swiftlint.sh @@ -8,7 +8,7 @@ if test -d "/opt/homebrew/bin/"; then fi if which swiftlint >/dev/null; then - swiftlint --config ${SRCROOT}/Scripts/swiftlint.yml + swiftlint --config "${SRCROOT}/Scripts/swiftlint.yml" else echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint" fi From 4aa37f61693eaba85f9910999f269f48442a9c06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Jan 2022 13:52:09 +0100 Subject: [PATCH 13/42] Expert users need raw access to expert values --- GRDB/Core/Database.swift | 11 ++++++----- GRDB/Core/DatabaseBackupProgress.swift | 13 +++++++++---- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 6af3e1d44..157616a6f 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1320,11 +1320,12 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib do { backupLoop: while true { let rc = sqlite3_backup_step(backup, pagesPerStep) - let totalPages = Int(sqlite3_backup_pagecount(backup)) - let completedPages = totalPages - Int(sqlite3_backup_remaining(backup)) - let progress = DatabaseBackupProgress(completedPageCount: completedPages, - totalPageCount: totalPages, - isCompleted: rc == SQLITE_DONE) + let totalPageCount = Int(sqlite3_backup_pagecount(backup)) + let remainingPageCount = Int(sqlite3_backup_remaining(backup)) + let progress = DatabaseBackupProgress( + remainingPageCount: remainingPageCount, + totalPageCount: totalPageCount, + isCompleted: rc == SQLITE_DONE) switch rc { case SQLITE_DONE: try? afterBackupStep?(progress) diff --git a/GRDB/Core/DatabaseBackupProgress.swift b/GRDB/Core/DatabaseBackupProgress.swift index 5c5ee6a57..cf38f98d2 100644 --- a/GRDB/Core/DatabaseBackupProgress.swift +++ b/GRDB/Core/DatabaseBackupProgress.swift @@ -4,13 +4,18 @@ /// /// This is an advanced API for expert users. It is based directly on the SQLite /// [online backup API](https://www.sqlite.org/c3ref/backup_finish.html). -/// -/// This struct is not meant to be instantiated by users. public struct DatabaseBackupProgress { - /// Completed page count is defined as `sqlite3_backup_pagecount() - sqlite3_backup_remaining()` - public let completedPageCount: Int + /// Total page count is defined by the `sqlite3_backup_remaining` function + public let remainingPageCount: Int + /// Total page count is defined by the `sqlite3_backup_pagecount` function public let totalPageCount: Int + + /// Completed page count is defined as `sqlite3_backup_pagecount() - sqlite3_backup_remaining()` + public var completedPageCount: Int { + totalPageCount - remainingPageCount + } + /// This property is true if and only if `sqlite3_backup_step()` returns /// `SQLITE_DONE` public let isCompleted: Bool From 2af0a746760625490e3b1c77cff9717ab7106abf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Jan 2022 14:13:25 +0100 Subject: [PATCH 14/42] Fix SQLCipher 3 and 4 test projects --- .../SQLCipher3/GRDBTests.xcodeproj/project.pbxproj | 6 ++++++ .../SQLCipher4/GRDBTests.xcodeproj/project.pbxproj | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index 7adce2aec..ae433327c 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -443,6 +443,8 @@ 5641A1BD24A540D6004967E1 /* PublisherExpectation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5641A19F24A540D6004967E1 /* PublisherExpectation.swift */; }; 564A2026226B89E1001F64F1 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 564A1F6F226B89D6001F64F1 /* Betty.jpeg */; }; 564A2151226B8E18001F64F1 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 564A1F6F226B89D6001F64F1 /* Betty.jpeg */; }; + 565A27CC27871FFF00659A62 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565A27CB27871FFF00659A62 /* BackupTestCase.swift */; }; + 565A27CD27871FFF00659A62 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565A27CB27871FFF00659A62 /* BackupTestCase.swift */; }; 5691D97527257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; }; 5691D97627257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; }; 5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; }; @@ -674,6 +676,7 @@ 564A1F22226B876D001F64F1 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 564A1F6F226B89D6001F64F1 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 564A2156226B8E18001F64F1 /* GRDBTestsEncrypted.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTestsEncrypted.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 565A27CB27871FFF00659A62 /* BackupTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BackupTestCase.swift; sourceTree = ""; }; 5691D97427257CE40021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = ""; }; 6A4788C0F815F6C5E4EBDE12 /* Pods-GRDBTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.debug.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.debug.xcconfig"; sourceTree = ""; }; 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_GRDBTestsEncrypted.framework; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -799,6 +802,7 @@ 56419CAD24A54054004967E1 /* AssociationPrefetchingSQLTests.swift */, 56419D5824A54061004967E1 /* AssociationRowScopeSearchTests.swift */, 56419D6324A54062004967E1 /* AssociationTableAliasTestsSQLTests.swift */, + 565A27CB27871FFF00659A62 /* BackupTestCase.swift */, 56419CD424A54057004967E1 /* CGFloatTests.swift */, 56419CD924A54058004967E1 /* ColumnExpressionTests.swift */, 56419D5424A54061004967E1 /* ColumnInfoTests.swift */, @@ -1213,6 +1217,7 @@ 56419E1F24A54062004967E1 /* ValueObservationRecorderTests.swift in Sources */, 56419DA124A54062004967E1 /* EncryptionTests.swift in Sources */, 56419DF124A54062004967E1 /* FoundationNSNullTests.swift in Sources */, + 565A27CC27871FFF00659A62 /* BackupTestCase.swift in Sources */, 56419EEB24A54063004967E1 /* RecordPersistenceConflictPolicy.swift in Sources */, 56419E8124A54063004967E1 /* DatabaseReaderTests.swift in Sources */, 56419EDD24A54063004967E1 /* TableDefinitionTests.swift in Sources */, @@ -1437,6 +1442,7 @@ 56419E2024A54062004967E1 /* ValueObservationRecorderTests.swift in Sources */, 56419DA224A54062004967E1 /* EncryptionTests.swift in Sources */, 56419DF224A54062004967E1 /* FoundationNSNullTests.swift in Sources */, + 565A27CD27871FFF00659A62 /* BackupTestCase.swift in Sources */, 56419EEC24A54063004967E1 /* RecordPersistenceConflictPolicy.swift in Sources */, 56419E8224A54063004967E1 /* DatabaseReaderTests.swift in Sources */, 56419EDE24A54063004967E1 /* TableDefinitionTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index 61f62b11b..1d12cd7c6 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -445,6 +445,8 @@ 564A2151226B8E18001F64F1 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 564A1F6F226B89D6001F64F1 /* Betty.jpeg */; }; 564A2159226C8F25001F64F1 /* db.SQLCipher3 in Resources */ = {isa = PBXBuildFile; fileRef = 564A2158226C8F24001F64F1 /* db.SQLCipher3 */; }; 564A215A226C8F25001F64F1 /* db.SQLCipher3 in Resources */ = {isa = PBXBuildFile; fileRef = 564A2158226C8F24001F64F1 /* db.SQLCipher3 */; }; + 565A27C927871FE500659A62 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565A27C827871FE500659A62 /* BackupTestCase.swift */; }; + 565A27CA27871FE500659A62 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565A27C827871FE500659A62 /* BackupTestCase.swift */; }; 5691D97227257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; }; 5691D97327257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; }; 5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; }; @@ -677,6 +679,7 @@ 564A1F6F226B89D6001F64F1 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 564A2156226B8E18001F64F1 /* GRDBTestsEncrypted.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTestsEncrypted.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 564A2158226C8F24001F64F1 /* db.SQLCipher3 */ = {isa = PBXFileReference; lastKnownFileType = file; path = db.SQLCipher3; sourceTree = SOURCE_ROOT; }; + 565A27C827871FE500659A62 /* BackupTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BackupTestCase.swift; sourceTree = ""; }; 5691D97127257C930021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = ""; }; 67377FE4CDAD675809F93AD4 /* Pods_GRDBTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_GRDBTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 6A4788C0F815F6C5E4EBDE12 /* Pods-GRDBTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.debug.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.debug.xcconfig"; sourceTree = ""; }; @@ -803,6 +806,7 @@ 56419F4424A54097004967E1 /* AssociationPrefetchingSQLTests.swift */, 56419F5024A54098004967E1 /* AssociationRowScopeSearchTests.swift */, 56419F9E24A5409D004967E1 /* AssociationTableAliasTestsSQLTests.swift */, + 565A27C827871FE500659A62 /* BackupTestCase.swift */, 56419F6B24A5409A004967E1 /* CGFloatTests.swift */, 56419F6524A54099004967E1 /* ColumnExpressionTests.swift */, 56419F9324A5409D004967E1 /* ColumnInfoTests.swift */, @@ -1219,6 +1223,7 @@ 5641A03624A540A1004967E1 /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 5641A0AE24A540A1004967E1 /* DatabaseConfigurationTests.swift in Sources */, 5641A0CA24A540A1004967E1 /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, + 565A27C927871FE500659A62 /* BackupTestCase.swift in Sources */, 56419FD624A540A1004967E1 /* DatabaseRegionTests.swift in Sources */, 5641A0A824A540A1004967E1 /* JoinSupportTests.swift in Sources */, 5641A0D424A540A1004967E1 /* FoundationUUIDTests.swift in Sources */, @@ -1443,6 +1448,7 @@ 5641A03724A540A1004967E1 /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 5641A0AF24A540A1004967E1 /* DatabaseConfigurationTests.swift in Sources */, 5641A0CB24A540A1004967E1 /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, + 565A27CA27871FE500659A62 /* BackupTestCase.swift in Sources */, 56419FD724A540A1004967E1 /* DatabaseRegionTests.swift in Sources */, 5641A0A924A540A1004967E1 /* JoinSupportTests.swift in Sources */, 5641A0D524A540A1004967E1 /* FoundationUUIDTests.swift in Sources */, From e799c8534ec9d3798aec8ea577a0a5648280f606 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 7 Jan 2022 08:28:29 +0100 Subject: [PATCH 15/42] ColumnExpression.detached --- GRDB/QueryInterface/SQL/Column.swift | 22 +++++++++++ Tests/GRDBTests/ColumnExpressionTests.swift | 44 +++++++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/GRDB/QueryInterface/SQL/Column.swift b/GRDB/QueryInterface/SQL/Column.swift index d6d1299fb..53ba627fe 100644 --- a/GRDB/QueryInterface/SQL/Column.swift +++ b/GRDB/QueryInterface/SQL/Column.swift @@ -28,6 +28,28 @@ extension ColumnExpression { public var sqlExpression: SQLExpression { .column(name) } + + /// Returns a "detached column", which is never qualified with any table + /// name in the SQL generated by the query interface. A detached column + /// allows you to refer to an aliased expression (`expression AS alias`). + /// + /// For example, see how `Column("total").detached` makes it possible to + /// sort this query, when a raw `Column("total")` could not: + /// + /// // SELECT player.*, + /// // (player.score + player.bonus) AS total, + /// // team.* + /// // FROM player + /// // JOIN team ON team.id = player.teamID + /// // ORDER BY total, player.name + /// // ~~~~~ + /// let request = Player + /// .annotated(with: (Column("score") + Column("bonus")).forKey("total")) + /// .including(required: Book.team) + /// .order(Column("total").detached, Column("name")) + public var detached: SQLExpression { + SQL(sql: name.quotedDatabaseIdentifier).sqlExpression + } } #if compiler(>=5.5) diff --git a/Tests/GRDBTests/ColumnExpressionTests.swift b/Tests/GRDBTests/ColumnExpressionTests.swift index ac28ae801..eb1bdddcf 100644 --- a/Tests/GRDBTests/ColumnExpressionTests.swift +++ b/Tests/GRDBTests/ColumnExpressionTests.swift @@ -230,4 +230,48 @@ class ColumnExpressionTests: GRDBTestCase { try assertEqualSQL(db, request, "SELECT \"full_name\" = 'foo' FROM \"player\"") } } + + func testDetachedColumn() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "t") { t in t.column("a") } + + // Regular columns are qualified + do { + let alias = TableAlias(name: "custom") + let request = Table("t") + .aliased(alias) + .order(Column("a")) + let sql = try request.makePreparedRequest(db).statement.sql + XCTAssertEqual(sql, """ + SELECT "custom".* FROM "t" "custom" ORDER BY "custom"."a" + """) + } + + // Detached columns are NOT qualified + do { + let alias = TableAlias(name: "custom") + let request = Table("t") + .aliased(alias) + .order(Column("a").detached) + let sql = try request.makePreparedRequest(db).statement.sql + XCTAssertEqual(sql, """ + SELECT "custom".* FROM "t" "custom" ORDER BY "a" + """) + } + + // Detached columns are quoted + do { + let alias = TableAlias(name: "custom") + let request = Table("t") + .aliased(alias) + .select(Column("a").forKey("order")) + .order(Column("order").detached) + let sql = try request.makePreparedRequest(db).statement.sql + XCTAssertEqual(sql, """ + SELECT "custom"."a" AS "order" FROM "t" "custom" ORDER BY "order" + """) + } + } + } } From bdf54e80a98e722ed1f5f5a589b4160365805c3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 7 Jan 2022 13:21:02 +0100 Subject: [PATCH 16/42] Mention detached columns in the documentation of expression.forKey(_:) --- GRDB/QueryInterface/SQL/Column.swift | 2 +- GRDB/QueryInterface/SQL/SQLExpression.swift | 19 ++++++++++++++++-- README.md | 22 +++++++++++++++++++++ 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/GRDB/QueryInterface/SQL/Column.swift b/GRDB/QueryInterface/SQL/Column.swift index 53ba627fe..4bb52256d 100644 --- a/GRDB/QueryInterface/SQL/Column.swift +++ b/GRDB/QueryInterface/SQL/Column.swift @@ -31,7 +31,7 @@ extension ColumnExpression { /// Returns a "detached column", which is never qualified with any table /// name in the SQL generated by the query interface. A detached column - /// allows you to refer to an aliased expression (`expression AS alias`). + /// allows you to refer to an aliased column (`expression AS alias`). /// /// For example, see how `Column("total").detached` makes it possible to /// sort this query, when a raw `Column("total")` could not: diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index b703d63b5..7ad6871ac 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -1823,7 +1823,7 @@ extension SQLSpecificExpressible { /// :nodoc: extension SQLSpecificExpressible { - /// Give the expression the given SQL name. + /// Returns an aliased column. /// /// For example: /// @@ -1833,11 +1833,24 @@ extension SQLSpecificExpressible { /// if let row = try Row.fetchOne(db, request) { /// let area: Int = row["area"] /// } + /// + /// If you need to refer to the aliased column in another part of a request, + /// use `Column(...).detached`. For example: + /// + /// // SELECT (width * height) AS area FROM shape ORDER BY area + /// let area = (Column("width") * Column("height")).forKey("area") + /// let request = Shape + /// .select(area) + /// .order(Column("area").detached) + /// let rows = try Row.fetchCursor(db, request) + /// while let row = try rows.next() { + /// let area: Int = row["area"] + /// } public func forKey(_ key: String) -> SQLSelection { .aliasedExpression(sqlExpression, key) } - /// Give the expression the same SQL name as the coding key. + /// Returns an aliased column with the same name as the coding key. /// /// For example: /// @@ -1855,6 +1868,8 @@ extension SQLSpecificExpressible { /// /// // SELECT width, height, (width * height) AS area FROM shape /// let shapes: [Shape] = try Shape.fetchAll(db) + /// + /// See `forKey(_ key: String)` for more information. public func forKey(_ key: CodingKey) -> SQLSelection { forKey(key.stringValue) } diff --git a/README.md b/README.md index 69eac8ea2..b78d9deb4 100644 --- a/README.md +++ b/README.md @@ -4943,6 +4943,28 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli // SELECT * FROM document WHERE document MATCH 'sqlite database' Document.matching(pattern) ``` +- `AS` + + To give an alias to an expression, use the `forKey` method: + + ```swift + // SELECT (score + bonus) AS total + // FROM player + Player.select((Column("score") + Column("bonus")).forKey("total")) + ``` + + If you need to refer to this aliased column in another place of the request, use a detached column: + + ```swift + // SELECT (score + bonus) AS total + // FROM player + // ORDER BY total + Player + .select((Column("score") + Column("bonus")).forKey("total")) + .order(Column("total").detached) + ``` + + Unlike `Column("total")`, the detached column `Column("total").detached` is never associated to the "player" table, so it is always rendered as `total` in the generated SQL, even when the request involves other tables via an [association](Documentation/AssociationsBasics.md) or a [common table expression]. ### SQL Functions From 5d51f2a88424106f0a3867035cdea2f26d629f01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 7 Jan 2022 14:28:21 +0100 Subject: [PATCH 17/42] New Embedding SQL in Query Interface Requests chapter --- README.md | 147 +++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 134 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index b78d9deb4..e8ebd0dd6 100644 --- a/README.md +++ b/README.md @@ -4134,6 +4134,7 @@ So don't miss the [SQL API](#sqlite-api). - [Expressions](#expressions) - [SQL Operators](#sql-operators) - [SQL Functions](#sql-functions) +- [Embedding SQL in Query Interface Requests] - [Fetching from Requests] - [Fetching by Key](#fetching-by-key) - [Testing for Record Existence](#testing-for-record-existence) @@ -4710,7 +4711,7 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: ### SQL Operators -GRDB comes with a Swift version of many SQLite [built-in operators](https://sqlite.org/lang_expr.html#operators), listed below. But not all: see [Adding support for missing SQL functions or operators](#adding-support-for-missing-sql-functions-or-operators). +GRDB comes with a Swift version of many SQLite [built-in operators](https://sqlite.org/lang_expr.html#operators), listed below. But not all: see [Embedding SQL in Query Interface Requests] for a way to add support for missing SQL operators. - `=`, `<>`, `<`, `<=`, `>`, `>=`, `IS`, `IS NOT` @@ -4969,7 +4970,7 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli ### SQL Functions -GRDB comes with a Swift version of many SQLite [built-in functions](https://sqlite.org/lang_corefunc.html), listed below. But not all: see [Adding support for missing SQL functions or operators](#adding-support-for-missing-sql-functions-or-operators). +GRDB comes with a Swift version of many SQLite [built-in functions](https://sqlite.org/lang_corefunc.html), listed below. But not all: see [Embedding SQL in Query Interface Requests] for a way to add support for missing SQL functions. - `ABS`, `AVG`, `COUNT`, `DATETIME`, `JULIANDAY`, `LENGTH`, `MAX`, `MIN`, `SUM`, `TOTAL`: @@ -5036,22 +5037,138 @@ GRDB comes with a Swift version of many SQLite [built-in functions](https://sqli Player.select(f.apply(nameColumn)) ``` -### Adding support for missing SQL functions or operators +## Embedding SQL in Query Interface Requests -When you spot an SQL function or operator that misses its Swift version, you can define it right into your application code. +You will sometimes want to extend your query interface requests with SQL snippets. This can happen because GRDB does not provide a Swift interface for some SQL function or operator, or because you want to use an SQLite construct that GRDB does not support. -For example, you can add support for the `DATE` function, thanks to [SQL Interpolation]: +Support for extensibility is large, but not unlimited. All the SQL queries built by the query interface request have the shape below. _If you need something else, you'll have to use [raw SQL requests](#sqlite-api)._ -```swift -func date(_ value: SQLSpecificExpressible) -> SQLExpression { - SQL("DATE(\(value))").sqlExpression -} - -// SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23' -let request = Player.filter(date(Column("createdAt")) == "2020-01-23") +```sql +WITH ... -- 1 +SELECT ... -- 2 +FROM ... -- 3 +JOIN ... -- 4 +WHERE ... -- 5 +GROUP BY ... -- 6 +HAVING ... -- 7 +ORDER BY ... -- 8 +LIMIT ... -- 9 ``` -See the [Query Interface Organization] for more information about `SQLSpecificExpressible` and `SQLExpression`. +1. `WITH ...`: see [Common Table Expressions]. + +2. `SELECT ...` + + The selection can be provided as raw SQL: + + ```swift + // SELECT IFNULL(name, 'O''Brien'), score FROM player + let request = Player.select(sql: "IFNULL(name, 'O''Brien'), score") + + // SELECT IFNULL(name, 'O''Brien'), score FROM player + let defaultName = "O'Brien" + let request = Player.select(sql: "IFNULL(name, ?), score", arguments: [suffix]) + ``` + + The selection can be provided with [SQL Interpolation]: + + ```swift + // SELECT IFNULL(name, 'O''Brien'), score FROM player + let defaultName = "O'Brien" + let request = Player.select(literal: "IFNULL(name, \(defaultName)), score") + ``` + + The selection can be provided with a mix of Swift and [SQL Interpolation]: + + ```swift + // SELECT IFNULL(name, 'O''Brien') AS displayName, score FROM player + let defaultName = "O'Brien" + let displayName: SQL = "IFNULL(\(Column("name")), \(defaultName)) AS displayName" + let request = Player.select(displayName, Column("score")) + ``` + + When the custom SQL snippet should behave as a full-fledged expression, with support for the `+` Swift operator, the `forKey` aliasing method, and all other [SQL Operators](#sql-operators), build an _expression literal_ with the `SQL.sqlExpression` method: + + ```swift + // SELECT IFNULL(name, 'O''Brien') AS displayName, score FROM player + let defaultName = "O'Brien" + let displayName = SQL("IFNULL(\(Column("name")), \(defaultName))").sqlExpression + let request = Player.select(displayName.forKey("displayName"), Column("score")) + ``` + + Such expression literals allow you to build a reusable support library of SQL functions or operators that are missing from the query interface. For example, you can define a Swift `date` function: + + ```swift + func date(_ value: SQLSpecificExpressible) -> SQLExpression { + SQL("DATE(\(value))").sqlExpression + } + + // SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23' + let request = Player.filter(date(Column("createdAt")) == "2020-01-23") + ``` + + See the [Query Interface Organization] for more information about `SQLSpecificExpressible` and `SQLExpression`. + +3. `FROM ...`: only one table is supported here. You can not customize this SQL part. + +4. `JOIN ...`: joins are fully controlled by [Associations]. You can not customize this SQL part. + +5. `WHERE ...` + + The WHERE clause can be provided as raw SQL: + + ```swift + // SELECT * FROM player WHERE score >= 1000 + let request = Player.filter(sql: "score >= 1000") + + // SELECT * FROM player WHERE score >= 1000 + let minScore = 1000 + let request = Player.filter(sql: "score >= ?", arguments: [minScore]) + ``` + + The WHERE clause can be provided with [SQL Interpolation]: + + ```swift + // SELECT * FROM player WHERE score >= 1000 + let minScore = 1000 + let request = Player.select(literal: "score >= \(minScore)") + ``` + + The WHERE clause can be provided with a mix of Swift and [SQL Interpolation]: + + ```swift + // SELECT * FROM player WHERE (score >= 1000) AND (team = 'red') + let minScore = 1000 + let scoreCondition: SQL = "\(Column("score")) >= \(minScore)" + let request = Player.filter(scoreCondition && Column("team") == "red") + ``` + + See `SELECT ...` above for more SQL Interpolation examples. + +6. `GROUP BY ...` + + The GROUP BY clause can be provided as raw SQL, SQL Interpolation, or a mix of Swift and SQL Interpolation, just as the selection and the WHERE clause (see above). + +7. `HAVING ...` + + The HAVING clause can be provided as raw SQL, SQL Interpolation, or a mix of Swift and SQL Interpolation, just as the selection and the WHERE clause (see above). + +8. `ORDER BY ...` + + The ORDER BY clause can be provided as raw SQL, SQL Interpolation, or a mix of Swift and SQL Interpolation, just as the selection and the WHERE clause (see above). + + In order to support the `desc` and `asc` query interface operators, and the `reversed()` query interface method, you must provide your orderings as _expression literals_ with the `SQL.sqlExpression` method: + + ```swift + // SELECT * FROM "player" + // ORDER BY (score + bonus) ASC, name DESC + let total = SQL("(score + bonus)").sqlExpression + let request = Player + .order(total.desc, Column("name")) + .reversed() + ``` + +9. `LIMIT ...`: use the `limit(_:offset:)` method. You can not customize this SQL part. ## Fetching from Requests @@ -8230,6 +8347,9 @@ This chapter has [moved](Documentation/Concurrency.md#synchronous-and-asynchrono This chapter has [moved](Documentation/Concurrency.md#safe-and-unsafe-database-accesses). +### Adding support for missing SQL functions or operators + +This chapter was renamed to [Embedding SQL in Query Interface Requests]. [Associations]: Documentation/AssociationsBasics.md [Beyond FetchableRecord]: #beyond-fetchablerecord @@ -8243,6 +8363,7 @@ This chapter has [moved](Documentation/Concurrency.md#safe-and-unsafe-database-a [Column Names Coding Strategies]: #column-names-coding-strategies [Date and UUID Coding Strategies]: #date-and-uuid-coding-strategies [Fetching from Requests]: #fetching-from-requests +[Embedding SQL in Query Interface Requests]: #embedding-sql-in-query-interface-requests [Full-Text Search]: Documentation/FullTextSearch.md [Migrations]: Documentation/Migrations.md [The Implicit RowID Primary Key]: #the-implicit-rowid-primary-key From c0305853bc9bd44e73b4c9236328a8677379fa55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 7 Jan 2022 14:43:57 +0100 Subject: [PATCH 18/42] Enhance fatal error message for reversed literal ordering terms --- GRDB/QueryInterface/SQL/SQLOrdering.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/GRDB/QueryInterface/SQL/SQLOrdering.swift b/GRDB/QueryInterface/SQL/SQLOrdering.swift index 8150f6acd..6c4785ab9 100644 --- a/GRDB/QueryInterface/SQL/SQLOrdering.swift +++ b/GRDB/QueryInterface/SQL/SQLOrdering.swift @@ -108,7 +108,8 @@ extension SQLOrdering { case .literal: fatalError(""" Ordering literals can't be reversed. \ - To resolve this error, order by expression literals instead. + To resolve this error, order by expression literals instead. \ + For example: order(SQL("(score + bonus)").sqlExpression) """) } } From 76523db5b9073e6b35ccca82d634cf04eb6d026c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 7 Jan 2022 14:58:42 +0100 Subject: [PATCH 19/42] Removed undesired :nodoc: comment --- GRDB/QueryInterface/SQL/SQLExpression.swift | 1 - 1 file changed, 1 deletion(-) diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 7ad6871ac..94686e31b 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -1821,7 +1821,6 @@ extension SQLSpecificExpressible { // MARK: - SQL Selection Support -/// :nodoc: extension SQLSpecificExpressible { /// Returns an aliased column. /// From 29cd08cba442afdcd02f4f5d1249c624411b7b48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 7 Jan 2022 15:01:29 +0100 Subject: [PATCH 20/42] Fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e8ebd0dd6..ca5ccbeaf 100644 --- a/README.md +++ b/README.md @@ -5131,7 +5131,7 @@ LIMIT ... -- 9 ```swift // SELECT * FROM player WHERE score >= 1000 let minScore = 1000 - let request = Player.select(literal: "score >= \(minScore)") + let request = Player.filter(literal: "score >= \(minScore)") ``` The WHERE clause can be provided with a mix of Swift and [SQL Interpolation]: From 2093b477dff90a022db8dff005273a39c9f57476 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 7 Jan 2022 17:19:52 +0100 Subject: [PATCH 21/42] Failing test for #1124 --- Tests/GRDBTests/ColumnInfoTests.swift | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Tests/GRDBTests/ColumnInfoTests.swift b/Tests/GRDBTests/ColumnInfoTests.swift index 4799daf1e..82b7b42ff 100644 --- a/Tests/GRDBTests/ColumnInfoTests.swift +++ b/Tests/GRDBTests/ColumnInfoTests.swift @@ -175,4 +175,23 @@ class ColumnInfoTests: GRDBTestCase { } #endif } + + func testIssue1124() throws { + class Observer: TransactionObserver { + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { true } + func databaseDidChange(with event: DatabaseEvent) { } + func databaseDidCommit(_ db: Database) { } + func databaseDidRollback(_ db: Database) { } + } + let dbQueue = try makeDatabaseQueue() + dbQueue.add(transactionObserver: Observer(), extent: .databaseLifetime) + try dbQueue.write { db in + try db.execute(sql: """ + CREATE VIRTUAL TABLE t1 USING rtree(id,minX,maxX,minY,maxY); + CREATE TABLE t2 (a); + ALTER TABLE t2 RENAME TO t3; + """) + _ = try db.columns(in: "t1") + } + } } From 823af1944ec9cae68fc81ad4c2a6b252908f54ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 8 Jan 2022 13:43:49 +0100 Subject: [PATCH 22/42] Cursor.forEach is a customization point --- GRDB/Core/Cursor.swift | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index ec5ecdc3a..b8076dfe9 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -225,6 +225,9 @@ public protocol Cursor: AnyObject { /// Advances to the next element and returns it, or nil if no next element /// exists. Once nil has been returned, all subsequent calls return nil. func next() throws -> Element? + + /// Calls the given closure on each element in the cursor. + func forEach(_ body: (Element) throws -> Void) throws } extension Cursor { @@ -654,12 +657,14 @@ extension Cursor where Element: StringProtocol { /// having the same Element type, hiding the specifics of the underlying /// cursor. public final class AnyCursor: Cursor { - private let element: () throws -> Element? + private let _next: () throws -> Element? + private let _forEach: ((Element) throws -> Void) throws -> Void /// Creates a cursor that wraps a base cursor but whose type depends only on /// the base cursor’s element type public init(_ base: C) where C.Element == Element { - element = base.next + _next = base.next + _forEach = base.forEach } /// Creates a cursor that wraps a base iterator but whose type depends only @@ -676,12 +681,17 @@ public final class AnyCursor: Cursor { } /// Creates a cursor that wraps the given closure in its next() method - public init(_ body: @escaping () throws -> Element?) { - element = body + public init(_ next: @escaping () throws -> Element?) { + _next = next + _forEach = { + while let element = try next() { + try $0(element) + } + } } public func next() throws -> Element? { - try element() + try _next() } } From fc0e1bede1f658d8774380e2a8d79a7b422c05e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 8 Jan 2022 13:50:14 +0100 Subject: [PATCH 23/42] Methods that fully consume a cursor prefer forEach to next This allows custom forEach implementations to wrap the full consumption of a cursor --- GRDB/Core/Cursor.swift | 24 ++++++++---------------- 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index b8076dfe9..a32903377 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -21,9 +21,7 @@ extension RangeReplaceableCollection { /// - parameter cursor: The cursor whose elements feed the collection. public init(_ cursor: C) throws where C.Element == Element { self.init() - while let element = try cursor.next() { - append(element) - } + try cursor.forEach { append($0) } } /// Creates a collection containing the elements of a cursor. @@ -38,9 +36,7 @@ extension RangeReplaceableCollection { public init(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element { self.init() reserveCapacity(minimumCapacity) - while let element = try cursor.next() { - append(element) - } + try cursor.forEach { append($0) } } } @@ -60,7 +56,7 @@ extension Dictionary { throws where Value == [C.Element] { self.init() - while let value = try cursor.next() { + try cursor.forEach { value in try self[keyForValue(value), default: []].append(value) } } @@ -86,7 +82,7 @@ extension Dictionary { throws where Value == [C.Element] { self.init(minimumCapacity: minimumCapacity) - while let value = try cursor.next() { + try cursor.forEach { value in try self[keyForValue(value), default: []].append(value) } } @@ -108,7 +104,7 @@ extension Dictionary { throws where C.Element == (Key, Value) { self.init() - while let (key, value) = try keysAndValues.next() { + try keysAndValues.forEach { key, value in if updateValue(value, forKey: key) != nil { fatalError("Duplicate values for key: '\(String(describing: key))'") } @@ -137,7 +133,7 @@ extension Dictionary { throws where C.Element == (Key, Value) { self.init(minimumCapacity: minimumCapacity) - while let (key, value) = try keysAndValues.next() { + try keysAndValues.forEach { key, value in if updateValue(value, forKey: key) != nil { fatalError("Duplicate values for key: '\(String(describing: key))'") } @@ -155,9 +151,7 @@ extension Set { /// - parameter cursor: A cursor of values to gather into a set. public init(_ cursor: C) throws where C.Element == Element { self.init() - while let element = try cursor.next() { - insert(element) - } + try cursor.forEach { insert($0) } } /// Creates a set containing the elements of a cursor. @@ -172,9 +166,7 @@ extension Set { /// storage buffer. public init(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element { self.init(minimumCapacity: minimumCapacity) - while let element = try cursor.next() { - insert(element) - } + try cursor.forEach { insert($0) } } } From 1bb2029e74bf55bd7615abca0537e852ac00c4fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 8 Jan 2022 13:51:41 +0100 Subject: [PATCH 24/42] Fix #1124 by dealing with authorizers --- GRDB/Record/FetchableRecord.swift | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 24333e25b..22b274b7c 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -571,6 +571,34 @@ public final class RecordCursor: Cursor { try _statement.database.statementDidFail(_statement, withResultCode: code) } } + + // Specific override in order to deal with https://github.com/groue/GRDB.swift/issues/1124 + /// :nodoc: + public func forEach(_ body: (Record) throws -> Void) throws { + switch _state { + case .busy: + // We can't deal with possible authorizer + fatalError("Not implemented") + case .idle: + if let authorizer = try _statement.database.statementWillExecute(_statement) { + _state = .busy + try _statement.database.withAuthorizer(authorizer) { + while let element = try next() { + try body(element) + } + } + } else { + _state = .busy + while let element = try next() { + try body(element) + } + } + default: + while let element = try next() { + try body(element) + } + } + } } // MARK: - DatabaseDateDecodingStrategy From 8fdcc020e0083684486c108b1e8c4d0f2cb1a47c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 8 Jan 2022 14:09:14 +0100 Subject: [PATCH 25/42] Documentation --- Tests/GRDBTests/ColumnInfoTests.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Tests/GRDBTests/ColumnInfoTests.swift b/Tests/GRDBTests/ColumnInfoTests.swift index 82b7b42ff..1c4ba219f 100644 --- a/Tests/GRDBTests/ColumnInfoTests.swift +++ b/Tests/GRDBTests/ColumnInfoTests.swift @@ -176,6 +176,8 @@ class ColumnInfoTests: GRDBTestCase { #endif } + // Regression test for https://github.com/groue/GRDB.swift/issues/1124 + // See also https://sqlite.org/forum/forumpost/721da02ba2 func testIssue1124() throws { class Observer: TransactionObserver { func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { true } From 66602ba2e25234417292cd3213da53c636ad07da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jan 2022 13:13:11 +0100 Subject: [PATCH 26/42] CHANGELOG --- CHANGELOG.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index db59def3a..9b14cf5b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -84,6 +84,12 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## Next Release + +- **New**: [#1075](https://github.com/groue/GRDB.swift/pull/1075) by [@mallman](https://github.com/mallman): Progress-reporting database backups +- **Fixed**: [#1120](https://github.com/groue/GRDB.swift/pull/1120) by [@jnross](https://github.com/jnross): Fix typos +- **Fixed**: [#1121](https://github.com/groue/GRDB.swift/pull/1121) by [@byohay](https://github.com/byohay): Quote PROJECT_DIR and SRCROOT environment variables + ## 5.17.0 Released December 14, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.16.0...v5.17.0) @@ -98,6 +104,8 @@ Released December 14, 2021 • [diff](https://github.com/groue/GRDB.swift/com - **Documentation Update**: :star: The [Concurrency Guide](Documentation/Concurrency.md) was updated for the new support for asynchronous Swift. - **Documentation Update**: :star: [GRDBAsyncDemo](Documentation/DemoApps/GRDBAsyncDemo/README.md) is a new SwiftUI demo app that uses the new async apis. - **Documentation Update**: A new FAQ gives hints for avoiding a [Mutation of captured var in concurrently-executing code](README.md##mutation-of-captured-var-in-concurrently-executing-code) compiler error. +- **Documentation Update**: [#1107](https://github.com/groue/GRDB.swift/pull/1107) by [@tcwalther](https://github.com/tcwalther): Fix docstring for Database.create(index: ...) +- **Documentation Update**: [#1110](https://github.com/groue/GRDB.swift/pull/1110) by [@maxhumber](https://github.com/maxhumber): Minor changes to a tip in the README ## 5.16.0 From 86c01804874639f358b4d93ef6e7fe500dd579ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jan 2022 13:17:29 +0100 Subject: [PATCH 27/42] CHANGELOG --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b14cf5b2..6d33bb8a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -87,8 +87,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Next Release - **New**: [#1075](https://github.com/groue/GRDB.swift/pull/1075) by [@mallman](https://github.com/mallman): Progress-reporting database backups +- **New**: [#1129](https://github.com/groue/GRDB.swift/pull/1129) by [@groue](https://github.com/groue): Detached columns - **Fixed**: [#1120](https://github.com/groue/GRDB.swift/pull/1120) by [@jnross](https://github.com/jnross): Fix typos - **Fixed**: [#1121](https://github.com/groue/GRDB.swift/pull/1121) by [@byohay](https://github.com/byohay): Quote PROJECT_DIR and SRCROOT environment variables +- **Documentation Update**: A new [Embedding SQL in Query Interface Requests](README.md#embedding-sql-in-query-interface-requests) chapter describes the ways to leverage your SQL skills and extend GRDB apis. + ## 5.17.0 From be45781cf9f6933205eda088c1f1fdf61a5b0cb4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jan 2022 13:31:03 +0100 Subject: [PATCH 28/42] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d33bb8a8..f1345824f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -90,6 +90,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **New**: [#1129](https://github.com/groue/GRDB.swift/pull/1129) by [@groue](https://github.com/groue): Detached columns - **Fixed**: [#1120](https://github.com/groue/GRDB.swift/pull/1120) by [@jnross](https://github.com/jnross): Fix typos - **Fixed**: [#1121](https://github.com/groue/GRDB.swift/pull/1121) by [@byohay](https://github.com/byohay): Quote PROJECT_DIR and SRCROOT environment variables +- **Fixed**: [#1128](https://github.com/groue/GRDB.swift/pull/1128) by [@groue](https://github.com/groue): Deal with authorization callbacks from cursors of FetchableRecord - **Documentation Update**: A new [Embedding SQL in Query Interface Requests](README.md#embedding-sql-in-query-interface-requests) chapter describes the ways to leverage your SQL skills and extend GRDB apis. From b3d49de0238edc3ecbd3fbb14bb90630f5623053 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jan 2022 13:41:11 +0100 Subject: [PATCH 29/42] Mention CONTRIBUTING in the pull request template --- .github/PULL_REQUEST_TEMPLATE.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 203f6be68..beee7c59a 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -6,8 +6,9 @@ Please check all those boxes: --> +- [ ] CONTRIBUTING: You have read https://github.com/groue/GRDB.swift/blob/master/CONTRIBUTING.md - [ ] BRANCH: This pull request is submitted against the `development` branch. - [ ] DOCUMENTATION: Inline documentation has been updated. - [ ] DOCUMENTATION: README.md or another dedicated guide has been updated. - [ ] TESTS: Changes are tested. -- [ ] TESTS: The `make smokeTest` terminal command runs without failure (see https://github.com/groue/GRDB.swift/blob/master/CONTRIBUTING.md). +- [ ] TESTS: The `make smokeTest` terminal command runs without failure. From 0513e0acf8d20508e1695eb8f4534688e9c5b7e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jan 2022 13:42:22 +0100 Subject: [PATCH 30/42] Enhance wording in the pull request template --- .github/PULL_REQUEST_TEMPLATE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index beee7c59a..b8f58b422 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -3,7 +3,7 @@ ### Pull Request Checklist - [ ] CONTRIBUTING: You have read https://github.com/groue/GRDB.swift/blob/master/CONTRIBUTING.md From 5b7ba122e825d97b550e84c552c6581aab258de9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jan 2022 14:06:27 +0100 Subject: [PATCH 31/42] Bump custom SQLite to v3.37.2 --- Documentation/CustomSQLiteBuilds.md | 2 +- SQLiteCustom/src | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Documentation/CustomSQLiteBuilds.md b/Documentation/CustomSQLiteBuilds.md index c5b80566e..69d0f5f7e 100644 --- a/Documentation/CustomSQLiteBuilds.md +++ b/Documentation/CustomSQLiteBuilds.md @@ -3,7 +3,7 @@ Custom SQLite Builds By default, GRDB uses the version of SQLite that ships with the target operating system. -**You can build GRDB with a custom build of [SQLite 3.33.0](https://www.sqlite.org/changes.html).** +**You can build GRDB with a custom build of [SQLite 3.37.2](https://www.sqlite.org/changes.html).** A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](../../../#support-for-sqlite-pre-update-hooks). diff --git a/SQLiteCustom/src b/SQLiteCustom/src index ad1fed978..c3d119c87 160000 --- a/SQLiteCustom/src +++ b/SQLiteCustom/src @@ -1 +1 @@ -Subproject commit ad1fed978aef85290d8b2159fed8fa863fe21576 +Subproject commit c3d119c87f51a93882b38fd41b2119259d29f4b8 From c172dac909e60473938a82ebc1ac12332f73c5df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jan 2022 14:21:51 +0100 Subject: [PATCH 32/42] Update test for SQLite to v3.37.2 --- Tests/GRDBTests/ColumnInfoTests.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/GRDBTests/ColumnInfoTests.swift b/Tests/GRDBTests/ColumnInfoTests.swift index 1c4ba219f..31de2168c 100644 --- a/Tests/GRDBTests/ColumnInfoTests.swift +++ b/Tests/GRDBTests/ColumnInfoTests.swift @@ -63,13 +63,13 @@ class ColumnInfoTests: GRDBTestCase { XCTAssertEqual(columns[3].name, "d") XCTAssertEqual(columns[3].isNotNull, false) - XCTAssertEqual(columns[3].type, "int") + XCTAssertEqual(columns[3].type.uppercased(), "INT") // "int" or "INT" depending of SQLite version XCTAssertEqual(columns[3].primaryKeyIndex, 0) XCTAssertEqual(columns[3].defaultValueSQL, "NULL") XCTAssertEqual(columns[4].name, "e") XCTAssertEqual(columns[4].isNotNull, true) - XCTAssertEqual(columns[4].type, "Text") + XCTAssertEqual(columns[4].type.uppercased(), "TEXT") // "Text" or "TEXT" depending of SQLite version XCTAssertEqual(columns[4].primaryKeyIndex, 0) XCTAssertEqual(columns[4].defaultValueSQL, "'foo'") From 94ff9f3e45a9b5b3178e242de8a393e9aa9f391d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jan 2022 14:28:00 +0100 Subject: [PATCH 33/42] The casing of ColumnInfo.type depends on the SQLite version --- GRDB/Core/Database+Schema.swift | 3 +++ 1 file changed, 3 insertions(+) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 31b546ed9..d71aed13a 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -717,6 +717,9 @@ public struct ColumnInfo: FetchableRecord { public let name: String /// The column data type + /// + /// The casing of this string depends on the SQLite version: make sure you + /// process this string in a case-insensitive way. public let type: String /// True if and only if the column is constrained to be not null. From 3145a916a08d1bca2788252b98bcad7a1ce98de8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jan 2022 14:33:33 +0100 Subject: [PATCH 34/42] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f1345824f..fa3fc2d96 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -88,6 +88,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **New**: [#1075](https://github.com/groue/GRDB.swift/pull/1075) by [@mallman](https://github.com/mallman): Progress-reporting database backups - **New**: [#1129](https://github.com/groue/GRDB.swift/pull/1129) by [@groue](https://github.com/groue): Detached columns +- **New**: [#1132](https://github.com/groue/GRDB.swift/pull/1132) by [@groue](https://github.com/groue): Bump custom SQLite builds v3.72.2 - **Fixed**: [#1120](https://github.com/groue/GRDB.swift/pull/1120) by [@jnross](https://github.com/jnross): Fix typos - **Fixed**: [#1121](https://github.com/groue/GRDB.swift/pull/1121) by [@byohay](https://github.com/byohay): Quote PROJECT_DIR and SRCROOT environment variables - **Fixed**: [#1128](https://github.com/groue/GRDB.swift/pull/1128) by [@groue](https://github.com/groue): Deal with authorization callbacks from cursors of FetchableRecord From 790c054a28a7de32b2fee22d5533976c8ec81e0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jan 2022 14:43:27 +0100 Subject: [PATCH 35/42] Fix Swiftlint warnings --- GRDB/Core/Database.swift | 2 +- GRDB/Core/DatabaseReader.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 157616a6f..0b25b4f5e 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1292,7 +1292,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib public func backup( to destDb: Database, pagesPerStep: Int32 = -1, - progress: ((DatabaseBackupProgress) throws -> ())? = nil) + progress: ((DatabaseBackupProgress) throws -> Void)? = nil) throws { try backupInternal( diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 4b27f2690..392dcfe4a 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -348,7 +348,7 @@ extension DatabaseReader { public func backup( to writer: DatabaseWriter, pagesPerStep: Int32 = -1, - progress: ((DatabaseBackupProgress) throws -> ())? = nil) + progress: ((DatabaseBackupProgress) throws -> Void)? = nil) throws { try writer.writeWithoutTransaction { destDb in From 95f1d83d7891f04b090d914a1b0f2dfe1d3b88d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jan 2022 16:42:55 +0100 Subject: [PATCH 36/42] The .strict table creation option The .strict table creation option The .strict table creation option --- .../Schema/TableDefinition.swift | 192 ++++++++++++++---- .../AssociationBelongsToSQLTests.swift | 2 +- Tests/GRDBTests/TableDefinitionTests.swift | 4 +- 3 files changed, 158 insertions(+), 40 deletions(-) diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index ad0918e2b..ae9533480 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -2,6 +2,48 @@ extension Database { // MARK: - Database Schema + // TODO: deprecate just before GRDB 6 + /// Creates a database table. + /// + /// try db.create(table: "place") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("title", .text) + /// t.column("favorite", .boolean).notNull().default(false) + /// t.column("longitude", .double).notNull() + /// t.column("latitude", .double).notNull() + /// } + /// + /// See and + /// + /// + /// - warning: This method is sunsetted. You should prefer + /// `create(table:options:body:)` instead. + /// + /// - parameters: + /// - name: The table name. + /// - temporary: If true, creates a temporary table. + /// - ifNotExists: If false (the default), an error is thrown if the + /// table already exists. Otherwise, the table is created unless it + /// already exists. + /// - withoutRowID: If true, uses WITHOUT ROWID optimization. + /// - body: A closure that defines table columns and constraints. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @_disfavoredOverload + public func create( + table name: String, + temporary: Bool = false, + ifNotExists: Bool = false, + withoutRowID: Bool = false, + body: (TableDefinition) throws -> Void) + throws + { + var options: TableOptions = [] + if temporary { options.insert(.temporary) } + if ifNotExists { options.insert(.ifNotExists) } + if withoutRowID { options.insert(.withoutRowID) } + try create(table: name, options: options, body: body) + } + /// Creates a database table. /// /// try db.create(table: "place") { t in @@ -17,26 +59,18 @@ extension Database { /// /// - parameters: /// - name: The table name. - /// - temporary: If true, creates a temporary table. - /// - ifNotExists: If false (the default), an error is thrown if the - /// table already exists. Otherwise, the table is created unless it - /// already exists. - /// - withoutRowID: If true, uses WITHOUT ROWID optimization. + /// - options: Table creation options. /// - body: A closure that defines table columns and constraints. /// - throws: A DatabaseError whenever an SQLite error occurs. public func create( table name: String, - temporary: Bool = false, - ifNotExists: Bool = false, - withoutRowID: Bool = false, + options: TableOptions = [], body: (TableDefinition) throws -> Void) throws { let definition = TableDefinition( name: name, - temporary: temporary, - ifNotExists: ifNotExists, - withoutRowID: withoutRowID) + options: options) try body(definition) let sql = try definition.sql(self) try execute(sql: sql) @@ -79,6 +113,46 @@ extension Database { try execute(sql: "DROP TABLE \(name.quotedDatabaseIdentifier)") } + // TODO: deprecate just before GRDB 6 + /// Creates an index. + /// + /// try db.create(index: "playerByEmail", on: "player", columns: ["email"]) + /// + /// SQLite can also index expressions (https://www.sqlite.org/expridx.html) + /// and use specific collations. To create such an index, use a raw SQL + /// query. + /// + /// try db.execute(sql: "CREATE INDEX ...") + /// + /// See + /// + /// - warning: This method is sunsetted. You should prefer + /// `create(index:on:columns:options:condition:)` instead. + /// + /// - parameters: + /// - name: The index name. + /// - table: The name of the indexed table. + /// - columns: The indexed columns. + /// - unique: If true, creates a unique index. + /// - ifNotExists: If true, no error is thrown if index already exists. + /// - condition: If not nil, creates a partial index + /// (see ). + @_disfavoredOverload + public func create( + index name: String, + on table: String, + columns: [String], + unique: Bool = false, + ifNotExists: Bool = false, + condition: SQLExpressible? = nil) + throws + { + var options: IndexOptions = [] + if ifNotExists { options.insert(.ifNotExists) } + if unique { options.insert(.unique) } + try create(index: name, on: table, columns: columns, options: options, condition: condition) + } + /// Creates an index. /// /// try db.create(index: "playerByEmail", on: "player", columns: ["email"]) @@ -95,16 +169,14 @@ extension Database { /// - name: The index name. /// - table: The name of the indexed table. /// - columns: The indexed columns. - /// - unique: If true, creates a unique index. - /// - ifNotExists: If true, no error is thrown if index already exists. + /// - options: Index creation options. /// - condition: If not nil, creates a partial index /// (see ). public func create( index name: String, on table: String, columns: [String], - unique: Bool = false, - ifNotExists: Bool = false, + options: IndexOptions = [], condition: SQLExpressible? = nil) throws { @@ -112,8 +184,7 @@ extension Database { name: name, table: table, columns: columns, - unique: unique, - ifNotExists: ifNotExists, + options: options, condition: condition?.sqlExpression) let sql = try definition.sql(self) try execute(sql: sql) @@ -153,6 +224,29 @@ extension Database { } } +/// Table creation options +public struct TableOptions: OptionSet { + /// :nodoc: + public let rawValue: Int + + /// :nodoc: + public init(rawValue: Int) { self.rawValue = rawValue } + + /// Only creates the table if it does not already exist. + public static let ifNotExists = TableOptions(rawValue: 1 << 0) + + /// Creates a temporary table. + public static let temporary = TableOptions(rawValue: 1 << 1) + + /// Creates a without rowid table. See + public static let withoutRowID = TableOptions(rawValue: 1 << 2) + +#if GRDBCUSTOMSQLITE + /// Creates a strict table. See + public static let strict = TableOptions(rawValue: 1 << 3) +#endif +} + /// The TableDefinition class lets you define table columns and constraints. /// /// You don't create instances of this class. Instead, you use the Database @@ -200,9 +294,7 @@ public final class TableDefinition { } private let name: String - private let temporary: Bool - private let ifNotExists: Bool - private let withoutRowID: Bool + private let options: TableOptions private var columns: [ColumnItem] = [] private var primaryKeyConstraint: KeyConstraint? private var uniqueKeyConstraints: [KeyConstraint] = [] @@ -210,11 +302,9 @@ public final class TableDefinition { private var checkConstraints: [SQLExpression] = [] private var literalConstraints: [SQL] = [] - init(name: String, temporary: Bool, ifNotExists: Bool, withoutRowID: Bool) { + init(name: String, options: TableOptions) { self.name = name - self.temporary = temporary - self.ifNotExists = ifNotExists - self.withoutRowID = withoutRowID + self.options = options } /// Defines the auto-incremented primary key. @@ -444,11 +534,11 @@ public final class TableDefinition { do { var chunks: [String] = [] chunks.append("CREATE") - if temporary { + if options.contains(.temporary) { chunks.append("TEMPORARY") } chunks.append("TABLE") - if ifNotExists { + if options.contains(.ifNotExists) { chunks.append("IF NOT EXISTS") } chunks.append(name.quotedDatabaseIdentifier) @@ -549,14 +639,29 @@ public final class TableDefinition { chunks.append("(\(items.joined(separator: ", ")))") } - if withoutRowID { - chunks.append("WITHOUT ROWID") + var tableOptions: [String] = [] + +#if GRDBCUSTOMSQLITE + if options.contains(.strict) { + tableOptions.append("STRICT") } +#endif + + if options.contains(.withoutRowID) { + tableOptions.append("WITHOUT ROWID") + } + + if !tableOptions.isEmpty { + chunks.append(tableOptions.joined(separator: ", ")) + } + statements.append(chunks.joined(separator: " ")) } + var indexOptions: IndexOptions = [] + if options.contains(.ifNotExists) { indexOptions.insert(.ifNotExists) } let indexStatements = try columns - .compactMap { $0.columnDefinition?.indexDefinition(in: name, ifNotExists: ifNotExists) } + .compactMap { $0.columnDefinition?.indexDefinition(in: name, options: indexOptions) } .map { try $0.sql(db) } statements.append(contentsOf: indexStatements) return statements.joined(separator: "; ") @@ -680,7 +785,7 @@ public final class TableAlteration { let statement = chunks.joined(separator: " ") statements.append(statement) - if let indexDefinition = column.indexDefinition(in: name, ifNotExists: false) { + if let indexDefinition = column.indexDefinition(in: name) { try statements.append(indexDefinition.sql(db)) } @@ -1143,7 +1248,7 @@ public final class ColumnDefinition { return chunks.joined(separator: " ") } - fileprivate func indexDefinition(in table: String, ifNotExists: Bool) -> IndexDefinition? { + fileprivate func indexDefinition(in table: String, options: IndexOptions = []) -> IndexDefinition? { switch index { case .none: return nil case .unique: return nil @@ -1152,29 +1257,42 @@ public final class ColumnDefinition { name: "\(table)_on_\(name)", table: table, columns: [name], - unique: false, - ifNotExists: ifNotExists, + options: options, condition: nil) } } } +/// Table creation options +public struct IndexOptions: OptionSet { + /// :nodoc: + public let rawValue: Int + + /// :nodoc: + public init(rawValue: Int) { self.rawValue = rawValue } + + /// Only creates the index if it does not already exist. + public static let ifNotExists = IndexOptions(rawValue: 1 << 0) + + /// Creates a unique index. + public static let unique = IndexOptions(rawValue: 1 << 1) +} + private struct IndexDefinition { let name: String let table: String let columns: [String] - let unique: Bool - let ifNotExists: Bool + let options: IndexOptions let condition: SQLExpression? func sql(_ db: Database) throws -> String { var chunks: [String] = [] chunks.append("CREATE") - if unique { + if options.contains(.unique) { chunks.append("UNIQUE") } chunks.append("INDEX") - if ifNotExists { + if options.contains(.ifNotExists) { chunks.append("IF NOT EXISTS") } chunks.append(name.quotedDatabaseIdentifier) diff --git a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift index 152c6aa68..03aceea2e 100644 --- a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift @@ -2057,7 +2057,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase { // Existence check is performed on the primary key. let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in - try db.create(table: "author", withoutRowID: true) { t in + try db.create(table: "author", options: [.withoutRowID]) { t in t.column("a", .text).notNull() t.column("b", .text).notNull() t.primaryKey(["a", "b"]) diff --git a/Tests/GRDBTests/TableDefinitionTests.swift b/Tests/GRDBTests/TableDefinitionTests.swift index 9b8d146ce..28e69df4d 100644 --- a/Tests/GRDBTests/TableDefinitionTests.swift +++ b/Tests/GRDBTests/TableDefinitionTests.swift @@ -160,7 +160,7 @@ class TableDefinitionTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in sqlQueries.removeAll() - try db.create(table: "test", ifNotExists: true) { t in + try db.create(table: "test", options: [.ifNotExists]) { t in t.column("a", .integer).indexed() t.column("b", .integer).indexed() } @@ -677,7 +677,7 @@ class TableDefinitionTests: GRDBTestCase { t.column("b", .text) } - try db.create(index: "test_on_a_b", on: "test", columns: ["a", "b"], unique: true, ifNotExists: true, condition: Column("a") == 1) + try db.create(index: "test_on_a_b", on: "test", columns: ["a", "b"], options: [.unique, .ifNotExists], condition: Column("a") == 1) assertEqualSQL(lastSQLQuery!, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b\" ON \"test\"(\"a\", \"b\") WHERE \"a\" = 1") // Sanity check From b2fabf5fc30171ec508a2d88c8643fc76454f3b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jan 2022 16:43:13 +0100 Subject: [PATCH 37/42] Strict tables need REAL and ANY column types --- GRDB/Core/Database.swift | 6 ++++++ README.md | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 0b25b4f5e..21ab900c4 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1537,6 +1537,9 @@ extension Database { /// The `DOUBLE` SQL column type public static let double = ColumnType(rawValue: "DOUBLE") + /// The `REAL` SQL column type + public static let real = ColumnType(rawValue: "REAL") + /// The `NUMERIC` SQL column type public static let numeric = ColumnType(rawValue: "NUMERIC") @@ -1551,6 +1554,9 @@ extension Database { /// The `DATETIME` SQL column type public static let datetime = ColumnType(rawValue: "DATETIME") + + /// The `ANY` SQL column type + public static let any = ColumnType(rawValue: "ANY") } /// An SQLite conflict resolution. diff --git a/README.md b/README.md index ca5ccbeaf..5bb3617ce 100644 --- a/README.md +++ b/README.md @@ -4196,7 +4196,7 @@ try db.create(table: "example", temporary: true, ifNotExists: true) { t in ... } > > :point_up: **Note**: [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables can not be tracked with [Database Observation] tools. -**Add regular columns** with their name and eventual type (text, integer, double, numeric, boolean, blob, date and datetime) - see [SQLite data types](https://www.sqlite.org/datatype3.html): +**Add regular columns** with their name and eventual type (`text`, `integer`, `double`, `real`, `numeric`, `boolean`, `blob`, `date`, `datetime` and `any`) - see [SQLite data types](https://www.sqlite.org/datatype3.html): ```swift // CREATE TABLE example ( From 8760033045dd64b6debd866452da80f40b8c90d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jan 2022 16:47:18 +0100 Subject: [PATCH 38/42] Update the list of extended result codes from SQLite 3.37.2 This updated list contains SQLITE_CONSTRAINT_DATATYPE, introduced with strict tables. --- GRDB/Core/DatabaseError.swift | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index d027d26cd..35eb51ea7 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -116,17 +116,22 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible { public static let SQLITE_IOERR_BEGIN_ATOMIC = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (29<<8))) public static let SQLITE_IOERR_COMMIT_ATOMIC = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (30<<8))) public static let SQLITE_IOERR_ROLLBACK_ATOMIC = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (31<<8))) + public static let SQLITE_IOERR_DATA = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (32<<8))) + public static let SQLITE_IOERR_CORRUPTFS = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (33<<8))) public static let SQLITE_LOCKED_SHAREDCACHE = ResultCode(rawValue: (SQLITE_LOCKED.rawValue | (1<<8))) public static let SQLITE_LOCKED_VTAB = ResultCode(rawValue: (SQLITE_LOCKED.rawValue | (2<<8))) public static let SQLITE_BUSY_RECOVERY = ResultCode(rawValue: (SQLITE_BUSY.rawValue | (1<<8))) public static let SQLITE_BUSY_SNAPSHOT = ResultCode(rawValue: (SQLITE_BUSY.rawValue | (2<<8))) + public static let SQLITE_BUSY_TIMEOUT = ResultCode(rawValue: (SQLITE_BUSY.rawValue | (3<<8))) public static let SQLITE_CANTOPEN_NOTEMPDIR = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (1<<8))) public static let SQLITE_CANTOPEN_ISDIR = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (2<<8))) public static let SQLITE_CANTOPEN_FULLPATH = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (3<<8))) public static let SQLITE_CANTOPEN_CONVPATH = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (4<<8))) public static let SQLITE_CANTOPEN_DIRTYWAL = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (5<<8))) /* Not Used */ + public static let SQLITE_CANTOPEN_SYMLINK = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (6<<8))) public static let SQLITE_CORRUPT_VTAB = ResultCode(rawValue: (SQLITE_CORRUPT.rawValue | (1<<8))) public static let SQLITE_CORRUPT_SEQUENCE = ResultCode(rawValue: (SQLITE_CORRUPT.rawValue | (2<<8))) + public static let SQLITE_CORRUPT_INDEX = ResultCode(rawValue: (SQLITE_CORRUPT.rawValue | (3<<8))) public static let SQLITE_READONLY_RECOVERY = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (1<<8))) public static let SQLITE_READONLY_CANTLOCK = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (2<<8))) public static let SQLITE_READONLY_ROLLBACK = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (3<<8))) @@ -144,11 +149,14 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible { public static let SQLITE_CONSTRAINT_UNIQUE = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (8<<8))) public static let SQLITE_CONSTRAINT_VTAB = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (9<<8))) public static let SQLITE_CONSTRAINT_ROWID = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (10<<8))) + public static let SQLITE_CONSTRAINT_PINNED = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (11<<8))) + public static let SQLITE_CONSTRAINT_DATATYPE = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (12<<8))) public static let SQLITE_NOTICE_RECOVER_WAL = ResultCode(rawValue: (SQLITE_NOTICE.rawValue | (1<<8))) public static let SQLITE_NOTICE_RECOVER_ROLLBACK = ResultCode(rawValue: (SQLITE_NOTICE.rawValue | (2<<8))) public static let SQLITE_WARNING_AUTOINDEX = ResultCode(rawValue: (SQLITE_WARNING.rawValue | (1<<8))) public static let SQLITE_AUTH_USER = ResultCode(rawValue: (SQLITE_AUTH.rawValue | (1<<8))) public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8))) + public static let SQLITE_OK_SYMLINK = ResultCode(rawValue: (SQLITE_OK.rawValue | (2<<8))) // swiftlint:enable operator_usage_whitespace line_length } @@ -333,17 +341,22 @@ extension DatabaseError { public static let SQLITE_IOERR_BEGIN_ATOMIC = ResultCode.SQLITE_IOERR_BEGIN_ATOMIC public static let SQLITE_IOERR_COMMIT_ATOMIC = ResultCode.SQLITE_IOERR_COMMIT_ATOMIC public static let SQLITE_IOERR_ROLLBACK_ATOMIC = ResultCode.SQLITE_IOERR_ROLLBACK_ATOMIC + public static let SQLITE_IOERR_DATA = ResultCode.SQLITE_IOERR_DATA + public static let SQLITE_IOERR_CORRUPTFS = ResultCode.SQLITE_IOERR_CORRUPTFS public static let SQLITE_LOCKED_SHAREDCACHE = ResultCode.SQLITE_LOCKED_SHAREDCACHE public static let SQLITE_LOCKED_VTAB = ResultCode.SQLITE_LOCKED_VTAB public static let SQLITE_BUSY_RECOVERY = ResultCode.SQLITE_BUSY_RECOVERY public static let SQLITE_BUSY_SNAPSHOT = ResultCode.SQLITE_BUSY_SNAPSHOT + public static let SQLITE_BUSY_TIMEOUT = ResultCode.SQLITE_BUSY_TIMEOUT public static let SQLITE_CANTOPEN_NOTEMPDIR = ResultCode.SQLITE_CANTOPEN_NOTEMPDIR public static let SQLITE_CANTOPEN_ISDIR = ResultCode.SQLITE_CANTOPEN_ISDIR public static let SQLITE_CANTOPEN_FULLPATH = ResultCode.SQLITE_CANTOPEN_FULLPATH public static let SQLITE_CANTOPEN_CONVPATH = ResultCode.SQLITE_CANTOPEN_CONVPATH public static let SQLITE_CANTOPEN_DIRTYWAL = ResultCode.SQLITE_CANTOPEN_DIRTYWAL + public static let SQLITE_CANTOPEN_SYMLINK = ResultCode.SQLITE_CANTOPEN_SYMLINK public static let SQLITE_CORRUPT_VTAB = ResultCode.SQLITE_CORRUPT_VTAB public static let SQLITE_CORRUPT_SEQUENCE = ResultCode.SQLITE_CORRUPT_SEQUENCE + public static let SQLITE_CORRUPT_INDEX = ResultCode.SQLITE_CORRUPT_INDEX public static let SQLITE_READONLY_RECOVERY = ResultCode.SQLITE_READONLY_RECOVERY public static let SQLITE_READONLY_CANTLOCK = ResultCode.SQLITE_READONLY_CANTLOCK public static let SQLITE_READONLY_ROLLBACK = ResultCode.SQLITE_READONLY_ROLLBACK @@ -361,11 +374,14 @@ extension DatabaseError { public static let SQLITE_CONSTRAINT_UNIQUE = ResultCode.SQLITE_CONSTRAINT_UNIQUE public static let SQLITE_CONSTRAINT_VTAB = ResultCode.SQLITE_CONSTRAINT_VTAB public static let SQLITE_CONSTRAINT_ROWID = ResultCode.SQLITE_CONSTRAINT_ROWID + public static let SQLITE_CONSTRAINT_PINNED = ResultCode.SQLITE_CONSTRAINT_PINNED + public static let SQLITE_CONSTRAINT_DATATYPE = ResultCode.SQLITE_CONSTRAINT_DATATYPE public static let SQLITE_NOTICE_RECOVER_WAL = ResultCode.SQLITE_NOTICE_RECOVER_WAL public static let SQLITE_NOTICE_RECOVER_ROLLBACK = ResultCode.SQLITE_NOTICE_RECOVER_ROLLBACK public static let SQLITE_WARNING_AUTOINDEX = ResultCode.SQLITE_WARNING_AUTOINDEX public static let SQLITE_AUTH_USER = ResultCode.SQLITE_AUTH_USER public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode.SQLITE_OK_LOAD_PERMANENTLY + public static let SQLITE_OK_SYMLINK = ResultCode.SQLITE_OK_SYMLINK } extension DatabaseError { From 68f3e5586bdf4c97820675b83bb534755d7055f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jan 2022 16:48:31 +0100 Subject: [PATCH 39/42] Test strict tables, and table/index creation options --- Tests/GRDBTests/TableDefinitionTests.swift | 45 +++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/Tests/GRDBTests/TableDefinitionTests.swift b/Tests/GRDBTests/TableDefinitionTests.swift index 28e69df4d..f7b59facf 100644 --- a/Tests/GRDBTests/TableDefinitionTests.swift +++ b/Tests/GRDBTests/TableDefinitionTests.swift @@ -33,6 +33,46 @@ class TableDefinitionTests: GRDBTestCase { ) WITHOUT ROWID """) } + + try dbQueue.inDatabase { db in + try db.create(table: "test2", options: [.temporary, .ifNotExists, .withoutRowID]) { t in + t.column("id", .integer).primaryKey() + } + assertEqualSQL(lastSQLQuery!, """ + CREATE TEMPORARY TABLE IF NOT EXISTS "test2" (\ + "id" INTEGER PRIMARY KEY\ + ) WITHOUT ROWID + """) + } + +#if GRDBCUSTOMSQLITE + try dbQueue.inDatabase { db in + try db.create(table: "test3", options: [.strict, .withoutRowID]) { t in + t.column("id", .integer).primaryKey() + t.column("a", .integer) + t.column("b", .real) + t.column("c", .text) + t.column("d", .blob) + t.column("e", .any) + } + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test3" (\ + "id" INTEGER PRIMARY KEY, \ + "a" INTEGER, \ + "b" REAL, \ + "c" TEXT, \ + "d" BLOB, \ + "e" ANY\ + ) STRICT, WITHOUT ROWID + """) + + do { + try db.execute(sql: "INSERT INTO test3 (id, a) VALUES (1, 'foo')") + XCTFail("Expected DatabaseError.SQLITE_CONSTRAINT_DATATYPE") + } catch DatabaseError.SQLITE_CONSTRAINT_DATATYPE { + } + } +#endif } func testColumnLiteral() throws { @@ -663,8 +703,11 @@ class TableDefinitionTests: GRDBTestCase { try db.create(index: "test_on_a_b", on: "test", columns: ["a", "b"], unique: true, ifNotExists: true) assertEqualSQL(lastSQLQuery!, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b\" ON \"test\"(\"a\", \"b\")") + try db.create(index: "test_on_a_b_2", on: "test", columns: ["a", "b"], options: [.unique, .ifNotExists]) + assertEqualSQL(lastSQLQuery!, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b_2\" ON \"test\"(\"a\", \"b\")") + // Sanity check - XCTAssertEqual(try Set(db.indexes(on: "test").map(\.name)), ["test_on_a", "test_on_a_b"]) + XCTAssertEqual(try Set(db.indexes(on: "test").map(\.name)), ["test_on_a", "test_on_a_b", "test_on_a_b_2"]) } } From a1c0c6d1f332d5b82989d32b74ba381e19ed74d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jan 2022 16:59:35 +0100 Subject: [PATCH 40/42] Update documentation for the new table/index creation options --- README.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5bb3617ce..1d85eeda2 100644 --- a/README.md +++ b/README.md @@ -4187,7 +4187,7 @@ SQLite itself has many reference documents about table creation: [CREATE TABLE]( try db.create(table: "example") { t in ... } // CREATE TEMPORARY TABLE example IF NOT EXISTS ( -try db.create(table: "example", temporary: true, ifNotExists: true) { t in ... } +try db.create(table: "example", options: [.temporary, .ifNotExists]) { t in ... } ``` > :bulb: **Tip**: database table names should be singular, and camelCased. Make them look like Swift identifiers: `place`, `country`, `postalAddress`, `httpRequest`. @@ -4335,8 +4335,11 @@ try db.drop(table: "obsolete") Create indexes with the `create(index:)` method: ```swift -// CREATE UNIQUE INDEX byEmail ON users(email) -try db.create(index: "byEmail", on: "users", columns: ["email"], unique: true) +// CREATE INDEX byName ON users(lastName, firstName) +try db.create(index: "byName", on: "users", columns: ["lastName, "firstName"]) + +// CREATE UNIQUE INDEX byEmail IF NOT EXISTS ON users(email) +try db.create(index: "byEmail", on: "users", columns: ["email"], options: [.unique, .ifNotExists]) ``` Relevant SQLite documentation: From fb6c695658e3d2afbc86eeaa8ede13ea8bac4816 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jan 2022 17:12:17 +0100 Subject: [PATCH 41/42] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fa3fc2d96..f4173d01e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -89,6 +89,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **New**: [#1075](https://github.com/groue/GRDB.swift/pull/1075) by [@mallman](https://github.com/mallman): Progress-reporting database backups - **New**: [#1129](https://github.com/groue/GRDB.swift/pull/1129) by [@groue](https://github.com/groue): Detached columns - **New**: [#1132](https://github.com/groue/GRDB.swift/pull/1132) by [@groue](https://github.com/groue): Bump custom SQLite builds v3.72.2 +- **New**: [#1133](https://github.com/groue/GRDB.swift/pull/1133) by [@groue](https://github.com/groue): Support for STRICT tables - **Fixed**: [#1120](https://github.com/groue/GRDB.swift/pull/1120) by [@jnross](https://github.com/jnross): Fix typos - **Fixed**: [#1121](https://github.com/groue/GRDB.swift/pull/1121) by [@byohay](https://github.com/byohay): Quote PROJECT_DIR and SRCROOT environment variables - **Fixed**: [#1128](https://github.com/groue/GRDB.swift/pull/1128) by [@groue](https://github.com/groue): Deal with authorization callbacks from cursors of FetchableRecord From 78df734f512b2ffc46c757cd85e280bef75aba63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jan 2022 17:36:31 +0100 Subject: [PATCH 42/42] v5.18.0 --- CHANGELOG.md | 5 +++- Documentation/FullTextSearch.md | 4 ++-- Documentation/Migrations.md | 2 +- GRDB.swift.podspec | 2 +- Makefile | 6 ++--- README.md | 42 ++++++++++++++++----------------- Support/Info.plist | 2 +- 7 files changed, 33 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f4173d01e..ccbf93269 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 5.x Releases +- `5.18.x` Releases - [5.17.0](#5180) - `5.17.x` Releases - [5.17.0](#5170) - `5.16.x` Releases - [5.16.0](#5160) - `5.15.x` Releases - [5.15.0](#5150) @@ -84,7 +85,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- -## Next Release +## 5.18.0 + +Released January 9, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.17.0...v5.18.0) - **New**: [#1075](https://github.com/groue/GRDB.swift/pull/1075) by [@mallman](https://github.com/mallman): Progress-reporting database backups - **New**: [#1129](https://github.com/groue/GRDB.swift/pull/1129) by [@groue](https://github.com/groue): Detached columns diff --git a/Documentation/FullTextSearch.md b/Documentation/FullTextSearch.md index 338487166..13015c76e 100644 --- a/Documentation/FullTextSearch.md +++ b/Documentation/FullTextSearch.md @@ -304,7 +304,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.17/Structs/StatementArguments.html): +FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.18/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, @@ -587,7 +587,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.17/Structs/StatementArguments.html): +FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.18/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index 297489ffd..e9d94d81d 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -77,7 +77,7 @@ try dbQueue.read { db in } ``` -See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.17/Structs/DatabaseMigrator.html) for more migrator methods. +See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.18/Structs/DatabaseMigrator.html) for more migrator methods. ## The `eraseDatabaseOnSchemaChange` Option diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index b5a347c38..f440b2a8e 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '5.17.0' + s.version = '5.18.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/Makefile b/Makefile index fed899a6c..4de7e8853 100644 --- a/Makefile +++ b/Makefile @@ -520,10 +520,10 @@ ifdef JAZZY --author 'Gwendal Roué' \ --author_url https://github.com/groue \ --github_url https://github.com/groue/GRDB.swift \ - --github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.17.0 \ - --module-version 5.17.0 \ + --github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.18.0 \ + --module-version 5.18.0 \ --module GRDB \ - --root-url http://groue.github.io/GRDB.swift/docs/5.17/ \ + --root-url http://groue.github.io/GRDB.swift/docs/5.18/ \ --output Documentation/Reference \ --xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS else diff --git a/README.md b/README.md index 1d85eeda2..a82c87be1 100644 --- a/README.md +++ b/README.md @@ -11,13 +11,13 @@ --- -**Latest release**: December 14, 2021 • [version 5.17.0](https://github.com/groue/GRDB.swift/tree/v5.17.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) +**Latest release**: January 9, 2022 • [version 5.18.0](https://github.com/groue/GRDB.swift/tree/v5.18.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) **Requirements**: iOS 11.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ • SQLite 3.8.5+ • Swift 5.3+ / Xcode 12+ | Swift version | GRDB version | | -------------- | ----------------------------------------------------------- | -| **Swift 5.3+** | **v5.17.0** | +| **Swift 5.3+** | **v5.18.0** | | Swift 5.2 | [v5.12.0](https://github.com/groue/GRDB.swift/tree/v5.12.0) | | Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | | Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | @@ -318,7 +318,7 @@ Documentation #### Reference -- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.17/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) +- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.18/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) #### Getting Started @@ -512,7 +512,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.17/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.18/Structs/Configuration.html) for more details. ## Database Pools @@ -592,7 +592,7 @@ let dbPool = try DatabasePool( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.17/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.18/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -652,7 +652,7 @@ try dbQueue.write { db in } ``` -The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.17/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. +The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.18/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. You can also embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details. @@ -910,7 +910,7 @@ try dbQueue.read { db in let dictionary = try Dictionary(uniqueKeysWithValues: cursor) ``` -- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.17/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: +- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.18/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: ```swift // Prints all Github links @@ -989,7 +989,7 @@ let rows = try Row.fetchAll(db, arguments: ["name": "Arthur"]) ``` -See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.17/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. +See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.18/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care: @@ -1274,7 +1274,7 @@ GRDB ships with built-in support for the following value types: - Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol. -Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.17/Structs/StatementArguments.html): +Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.18/Structs/StatementArguments.html): ```swift let url: URL = ... @@ -1721,7 +1721,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction } ``` -Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.17/Structs/Configuration.html) configuration flag: +Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.18/Structs/Configuration.html) configuration flag: ```swift // fatal error: A transaction has been left opened at the end of a database access @@ -1833,7 +1833,7 @@ try dbQueue.write { db in } ``` -The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.17/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). +The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.18/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). ```swift insertStatement.arguments = ["name": "Arthur", "score": 1000] @@ -1916,7 +1916,7 @@ See also `Database.execute(sql:)` in the [Executing Updates](#executing-updates) > :point_up: **Note**: it is a programmer error to reuse a prepared statement that has failed: GRDB may crash if you do so. -For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.17/Classes/Statement.html). +For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.18/Classes/Statement.html). ### Prepared Statements Cache @@ -2659,7 +2659,7 @@ try Place.fetchSet(db, sql: "SELECT ...", arguments:...) // Set try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place? ``` -See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.17/Structs/StatementArguments.html) for more information about the query arguments. +See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.18/Structs/StatementArguments.html) for more information about the query arguments. > :point_up: **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`. @@ -3099,7 +3099,7 @@ protocol EncodableRecord { } ``` -See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.17/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.17/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies. +See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.18/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.18/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies. ### Date and UUID Coding Strategies @@ -3121,7 +3121,7 @@ protocol EncodableRecord { } ``` -See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.17/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.17/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.17/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. +See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.18/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.18/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.18/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. There is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs and uuid strings, both uppercase and lowercase). @@ -4647,7 +4647,7 @@ Player // SELECT * FROM player ``` -Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.17/Structs/StatementArguments.html): +Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.18/Structs/StatementArguments.html): ```swift // SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate) @@ -5553,7 +5553,7 @@ try Player.customRequest().fetchAll(db) // [Player] - The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method. -- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.17/Structs/AnyFetchRequest.html): a type-erased request. +- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.18/Structs/AnyFetchRequest.html): a type-erased request. ## Joined Queries Support @@ -6857,7 +6857,7 @@ DatabaseRegion helps [ValueObservation] and [DatabaseRegionObservation] track ch For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table. -For more details, see the [reference](https://groue.github.io/GRDB.swift/docs/5.17/Structs/DatabaseRegion.html). +For more details, see the [reference](https://groue.github.io/GRDB.swift/docs/5.18/Structs/DatabaseRegion.html). #### The DatabaseRegionConvertible Protocol @@ -8199,7 +8199,7 @@ When this is the case, there are two possible explanations: try db.execute(sql: "UPDATE player SET name = ?", arguments: [name]) ``` -For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.17/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp). +For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.18/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp). @@ -8340,7 +8340,7 @@ This chapter has [moved](Documentation/Concurrency.md#database-snapshots). #### DatabaseWriter and DatabaseReader Protocols -This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.17/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.17/Protocols/DatabaseWriter.html). +This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.18/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.18/Protocols/DatabaseWriter.html). #### Asynchronous APIs @@ -8393,7 +8393,7 @@ This chapter was renamed to [Embedding SQL in Query Interface Requests]. [Sharing a Database]: Documentation/SharingADatabase.md [FAQ]: #faq [Database Observation]: #database-changes-observation -[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.17/Structs/SQLRequest.html +[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.18/Structs/SQLRequest.html [SQL literal]: Documentation/SQLInterpolation.md#sql-literal [Identifiable]: https://developer.apple.com/documentation/swift/identifiable [Query Interface Organization]: Documentation/QueryInterfaceOrganization.md diff --git a/Support/Info.plist b/Support/Info.plist index aa81dc9d7..de73120d9 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 5.17.0 + 5.18.0 CFBundleSignature ???? CFBundleVersion