From d66d2118b5fa4c17b185301db68eb7ae5727feb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Thu, 1 Jun 2023 17:05:06 +0200 Subject: [PATCH 01/14] Failing test for #1383 --- Tests/GRDBTests/ValueObservationTests.swift | 23 +++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index f8c49fb7e..d6697df2c 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -1152,4 +1152,27 @@ class ValueObservationTests: GRDBTestCase { try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } + + // Regression test for + func testIssue1383() throws { + do { + let dbPool = try makeDatabasePool(filename: "test") + try dbPool.writeWithoutTransaction { db in + try db.execute(sql: "CREATE TABLE t(a)") + try db.checkpoint(.truncate) + } + } + + do { + let dbPool = try makeDatabasePool(filename: "test") + let observation = ValueObservation.tracking(Table("t").fetchCount) + _ = observation.start( + in: dbPool, scheduling: .immediate, + onError: { error in + XCTFail("Unexpected error \(error)") + }, + onChange: { _ in + }) + } + } } From abd3ba39b1b38550986983acc2adab238eb8be33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Thu, 1 Jun 2023 17:20:25 +0200 Subject: [PATCH 02/14] Explicit tests that a DatabasePool can read from a new instance, and from a truncated wal file --- Tests/GRDBTests/DatabasePoolTests.swift | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/Tests/GRDBTests/DatabasePoolTests.swift b/Tests/GRDBTests/DatabasePoolTests.swift index 22813d232..379bb5a98 100644 --- a/Tests/GRDBTests/DatabasePoolTests.swift +++ b/Tests/GRDBTests/DatabasePoolTests.swift @@ -11,6 +11,26 @@ class DatabasePoolTests: GRDBTestCase { } } + func testCanReadFromNewInstance() throws { + let dbPool = try makeDatabasePool() + try dbPool.read { _ in } + } + + func testCanReadFromTruncatedWalFile() throws { + do { + let dbPool = try makeDatabasePool(filename: "test") + try dbPool.writeWithoutTransaction { db in + try db.execute(sql: "CREATE TABLE t(a)") + try db.checkpoint(.truncate) + } + } + do { + let dbPool = try makeDatabasePool(filename: "test") + let count = try dbPool.read(Table("t").fetchCount) + XCTAssertEqual(count, 0) + } + } + func testPersistentWALModeEnabled() throws { let path: String do { From cedcfbe33057ae84cc577e2a9caca00e3e7170fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Thu, 1 Jun 2023 17:26:04 +0200 Subject: [PATCH 03/14] Mark opportunities for snapshot creation failure (including #1383) --- GRDB/Core/DatabasePool.swift | 3 +++ GRDB/Core/DatabaseSnapshotPool.swift | 1 + 2 files changed, 4 insertions(+) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index b89f0c4c1..ed760e651 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -669,6 +669,7 @@ extension DatabasePool: DatabaseReader { #if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) /// Returns a long-lived WAL snapshot transaction on a reader connection. func walSnapshotTransaction() throws -> WALSnapshotTransaction { + // TODO #1383: might fail if wal file is truncated guard let readerPool else { throw DatabaseError.connectionIsClosed() } @@ -687,6 +688,7 @@ extension DatabasePool: DatabaseReader { /// - important: The `completion` argument is executed in a serial /// dispatch queue, so make sure you use the transaction asynchronously. func asyncWALSnapshotTransaction(_ completion: @escaping (Result) -> Void) { + // TODO #1383: might fail if wal file is truncated guard let readerPool else { completion(.failure(DatabaseError.connectionIsClosed())) return @@ -904,6 +906,7 @@ extension DatabasePool { /// if this method is called from a database access where a write /// transaction is open. public func makeSnapshotPool() throws -> DatabaseSnapshotPool { + // TODO #1383: might fail if wal file is truncated try unsafeReentrantRead { db in try DatabaseSnapshotPool(db) } diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index 8701754a4..8560ca7a7 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -186,6 +186,7 @@ public final class DatabaseSnapshotPool { /// - configuration: A configuration. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public init(path: String, configuration: Configuration = Configuration()) throws { + // TODO #1383: might fail if wal file is truncated var configuration = Self.configure(configuration) // Acquire and hold WAL snapshot From fa681fb8c6135e0bdc78fa83375425833f104c5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 1 Jun 2023 19:07:28 +0200 Subject: [PATCH 04/14] Enhance error message when WALSnapshot initializer fails --- GRDB/Core/WALSnapshot.swift | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/GRDB/Core/WALSnapshot.swift b/GRDB/Core/WALSnapshot.swift index f88509cd6..279f280c5 100644 --- a/GRDB/Core/WALSnapshot.swift +++ b/GRDB/Core/WALSnapshot.swift @@ -30,11 +30,30 @@ final class WALSnapshot: Sendable { return sqlite3_snapshot_get(db.sqliteConnection, "main", $0) } guard code == SQLITE_OK else { + // + // + // > The following must be true for sqlite3_snapshot_get() to succeed. [...] + // > + // > 1. The database handle must not be in autocommit mode. + // > 2. Schema S of database connection D must be a WAL + // > mode database. + // > 3. There must not be a write transaction open on schema S + // > of database connection D. + // > 4. One or more transactions must have been written to the + // > current wal file since it was created on disk (by any + // > connection). This means that a snapshot cannot be taken + // > on a wal mode database with no wal file immediately + // > after it is first opened. At least one transaction must + // > be written to it first. + + // Test condition 1: if sqlite3_get_autocommit(db.sqliteConnection) != 0 { throw DatabaseError(resultCode: code, message: """ Can't create snapshot because database is in autocommit mode. """) } + + // Test condition 2: if let journalMode = try? String.fetchOne(db, sql: "PRAGMA journal_mode"), journalMode != "wal" { @@ -42,7 +61,14 @@ final class WALSnapshot: Sendable { Can't create snapshot because database is not in WAL mode. """) } - throw DatabaseError(resultCode: code) + + // Condition 3 can't happen because GRDB only calls this + // initializer from read transactions. + // + // Hence it is condition 4 that is false: + throw DatabaseError(resultCode: code, message: """ + Can't create snapshot from a missing or empty wal file. + """) } guard let sqliteSnapshot else { throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite? From 73b279b5c17423a4ade015c9e923da5363ecc756 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 1 Jun 2023 19:15:21 +0200 Subject: [PATCH 05/14] Document methods that fail if the wal file is missing or truncated --- GRDB/Core/DatabasePool.swift | 9 +++++---- GRDB/Core/DatabaseSnapshotPool.swift | 17 +++++++---------- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index ed760e651..b01286ba9 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -902,11 +902,12 @@ extension DatabasePool { /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) /// /// A ``DatabaseError`` of code `SQLITE_ERROR` is thrown if the SQLite - /// database is not in the [WAL mode](https://www.sqlite.org/wal.html), or - /// if this method is called from a database access where a write - /// transaction is open. + /// database is not in the [WAL mode](https://www.sqlite.org/wal.html), + /// or if this method is called from a write transaction, or if the + /// wal file is missing or truncated (size zero). + /// + /// Related SQLite documentation: public func makeSnapshotPool() throws -> DatabaseSnapshotPool { - // TODO #1383: might fail if wal file is truncated try unsafeReentrantRead { db in try DatabaseSnapshotPool(db) } diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index 8560ca7a7..8535072b1 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -108,12 +108,10 @@ public final class DatabaseSnapshotPool { /// assert(count == 0) /// ``` /// - /// If any of the following statements are false when the snapshot is - /// created, a ``DatabaseError`` of code `SQLITE_ERROR` is thrown: - /// - /// - The database connection must be in the - /// [WAL mode](https://www.sqlite.org/wal.html). - /// - There must not be a write transaction open. + /// A ``DatabaseError`` of code `SQLITE_ERROR` is thrown if the SQLite + /// database is not in the [WAL mode](https://www.sqlite.org/wal.html), + /// or if this method is called from a write transaction, or if the + /// wal file is missing or truncated (size zero). /// /// Related SQLite documentation: /// @@ -175,9 +173,9 @@ public final class DatabaseSnapshotPool { /// let snapshot = try DatabaseSnapshotPool(path: "/path/to/database.sqlite") /// ``` /// - /// If the database at `path` is not in the - /// [WAL mode](https://www.sqlite.org/wal.html), a ``DatabaseError`` of code - /// `SQLITE_ERROR` is thrown. + /// A ``DatabaseError`` of code `SQLITE_ERROR` is thrown if the SQLite + /// database is not in the [WAL mode](https://www.sqlite.org/wal.html), + /// or if the wal file is missing or truncated (size zero). /// /// Related SQLite documentation: /// @@ -186,7 +184,6 @@ public final class DatabaseSnapshotPool { /// - configuration: A configuration. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public init(path: String, configuration: Configuration = Configuration()) throws { - // TODO #1383: might fail if wal file is truncated var configuration = Self.configure(configuration) // Acquire and hold WAL snapshot From 4ab8ac8d3f5a2b7507cdabc3b3b0b00db34d2a6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 1 Jun 2023 19:53:34 +0200 Subject: [PATCH 06/14] Failing test for #1383 (async version) --- Tests/GRDBTests/ValueObservationTests.swift | 30 +++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index d6697df2c..ebfd2a281 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -1175,4 +1175,34 @@ class ValueObservationTests: GRDBTestCase { }) } } + + // Regression test for + func testIssue1383_async() throws { + do { + let dbPool = try makeDatabasePool(filename: "test") + try dbPool.writeWithoutTransaction { db in + try db.execute(sql: "CREATE TABLE t(a)") + try db.checkpoint(.truncate) + } + } + + do { + let dbPool = try makeDatabasePool(filename: "test") + let observation = ValueObservation.tracking(Table("t").fetchCount) + let expectation = self.expectation(description: "completion") + expectation.assertForOverFulfill = false + let cancellable = observation.start( + in: dbPool, + onError: { error in + XCTFail("Unexpected error \(error)") + expectation.fulfill() + }, + onChange: { _ in + expectation.fulfill() + }) + withExtendedLifetime(cancellable) { _ in + wait(for: [expectation], timeout: 2) + } + } + } } From 725d4a3fba14c198ce8d3addd9f72a855e0947e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 1 Jun 2023 20:00:04 +0200 Subject: [PATCH 07/14] When a wal snapshot can't be created, ValueConcurrentObserver fallbacks to plain reads This commit fixes #1383 --- .../Observers/ValueConcurrentObserver.swift | 50 +++++++++++++++---- 1 file changed, 39 insertions(+), 11 deletions(-) diff --git a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift index b880a13c2..d9a81fd50 100644 --- a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift @@ -288,7 +288,17 @@ extension ValueConcurrentObserver { // We perform the initial read from a long-lived WAL snapshot // transaction, because it is a handy way to keep a read transaction // open until we grab a write access, and compare the database versions. - let initialFetchTransaction = try databaseAccess.dbPool.walSnapshotTransaction() + let initialFetchTransaction: WALSnapshotTransaction + do { + initialFetchTransaction = try databaseAccess.dbPool.walSnapshotTransaction() + } catch DatabaseError.SQLITE_ERROR { + // We can't create a WAL snapshot. The WAL file is probably + // missing, or is truncated. Let's degrade the observation + // by not using any snapshot. + // For more information, see + return try syncStartWithoutWALSnapshot(from: databaseAccess) + } + let (fetchedValue, initialRegion): (Reducer.Fetched, DatabaseRegion) = try initialFetchTransaction.read { db in switch trackingMode { case let .constantRegion(regions): @@ -334,8 +344,10 @@ extension ValueConcurrentObserver { // transaction, because it is a handy way to keep a read transaction // open until we grab a write access, and compare the database versions. databaseAccess.dbPool.asyncWALSnapshotTransaction { result in - let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil } - guard isNotifying else { return /* Cancelled */ } + let (isNotifying, databaseAccess) = self.lock.synchronized { + (self.notificationCallbacks != nil, self.databaseAccess) + } + guard isNotifying, let databaseAccess else { return /* Cancelled */ } do { let initialFetchTransaction = try result.get() @@ -390,6 +402,12 @@ extension ValueConcurrentObserver { self.notifyError(error) } } + } catch DatabaseError.SQLITE_ERROR { + // We can't create a WAL snapshot. The WAL file is probably + // missing, or is truncated. Let's degrade the observation + // by not using any snapshot. + // For more information, see + self.asyncStartWithoutWALSnapshot(from: databaseAccess) } catch { self.notifyError(error) } @@ -502,11 +520,22 @@ extension ValueConcurrentObserver { } } #else +extension ValueConcurrentObserver { + private func syncStart(from databaseAccess: DatabaseAccess) throws -> Reducer.Value { + try syncStartWithoutWALSnapshot(from: databaseAccess) + } + + private func asyncStart(from databaseAccess: DatabaseAccess) { + asyncStartWithoutWALSnapshot(from: databaseAccess) + } +} +#endif + extension ValueConcurrentObserver { /// Synchronously starts the observation, and returns the initial value. /// - /// Unlike `asyncStart()`, this method does not notify the initial value or error. - private func syncStart(from databaseAccess: DatabaseAccess) throws -> Reducer.Value { + /// Unlike `asyncStartWithoutWALSnapshot()`, this method does not notify the initial value or error. + private func syncStartWithoutWALSnapshot(from databaseAccess: DatabaseAccess) throws -> Reducer.Value { // Start from a read access. The whole point of using a DatabasePool // for observing the database is to be able to fetch the initial value // without having to wait for an eventual long-running write @@ -535,7 +564,7 @@ extension ValueConcurrentObserver { } // Start observation - asyncStartObservation( + asyncStartObservationWithoutWALSnapshot( from: databaseAccess, initialRegion: initialRegion) @@ -544,8 +573,8 @@ extension ValueConcurrentObserver { /// Asynchronously starts the observation /// - /// Unlike `syncStart()`, this method does notify the initial value or error. - private func asyncStart(from databaseAccess: DatabaseAccess) { + /// Unlike `syncStartWithoutWALSnapshot()`, this method does notify the initial value or error. + private func asyncStartWithoutWALSnapshot(from databaseAccess: DatabaseAccess) { // Start from a read access. The whole point of using a DatabasePool // for observing the database is to be able to fetch the initial value // without having to wait for an eventual long-running write @@ -595,7 +624,7 @@ extension ValueConcurrentObserver { } // Start observation - self.asyncStartObservation( + self.asyncStartObservationWithoutWALSnapshot( from: databaseAccess, initialRegion: initialRegion) } catch { @@ -604,7 +633,7 @@ extension ValueConcurrentObserver { } } - private func asyncStartObservation( + private func asyncStartObservationWithoutWALSnapshot( from databaseAccess: DatabaseAccess, initialRegion: DatabaseRegion) { @@ -669,7 +698,6 @@ extension ValueConcurrentObserver { } } } -#endif // MARK: - Observing Database Transactions From b840babb5570f352edb4a47d734f1e2af9bf742b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 1 Jun 2023 20:15:05 +0200 Subject: [PATCH 08/14] Document the intent of #1383 regression tests --- Tests/GRDBTests/ValueObservationTests.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index ebfd2a281..40c3e4d59 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -1159,6 +1159,7 @@ class ValueObservationTests: GRDBTestCase { let dbPool = try makeDatabasePool(filename: "test") try dbPool.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") + // Truncate the wal file (size zero) try db.checkpoint(.truncate) } } @@ -1182,6 +1183,7 @@ class ValueObservationTests: GRDBTestCase { let dbPool = try makeDatabasePool(filename: "test") try dbPool.writeWithoutTransaction { db in try db.execute(sql: "CREATE TABLE t(a)") + // Truncate the wal file (size zero) try db.checkpoint(.truncate) } } From 437b800d8ca223b988ba34fc1fc473fd859daac6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 2 Jun 2023 08:10:20 +0200 Subject: [PATCH 09/14] Add test for the SQLite file provided by @kustra https://github.com/groue/GRDB.swift/issues/1383#issuecomment-1572897011 --- GRDB.xcodeproj/project.pbxproj | 4 ++++ GRDBCustom.xcodeproj/project.pbxproj | 4 ++++ Package.swift | 1 + .../GRDBTests.xcodeproj/project.pbxproj | 6 ++++++ .../GRDBTests.xcodeproj/project.pbxproj | 6 ++++++ Tests/GRDBTests/Issue1383.sqlite | Bin 0 -> 8192 bytes Tests/GRDBTests/ValueObservationTests.swift | 19 ++++++++++++++++++ 7 files changed, 40 insertions(+) create mode 100644 Tests/GRDBTests/Issue1383.sqlite diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 1a7807a61..8fd0332e0 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -71,6 +71,7 @@ 56256ED025D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; }; 56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; }; 562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; }; + 562B58CB2A29BBEF00E8C75D /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */; }; 562EA8261F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; }; 562EA82F1F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; }; 56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; @@ -458,6 +459,7 @@ 56256ECF25D1ACD0008C2BDD /* Table.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = ""; }; 56256ED825D1B316008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = ""; }; 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = ""; }; + 562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = ""; }; 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = ""; }; 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = ""; }; 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = ""; }; @@ -1056,6 +1058,7 @@ 563B06BF2185CD1700B38F35 /* ValueObservation */ = { isa = PBXGroup; children = ( + 562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */, 560233C82724338800529DF3 /* SharedValueObservationTests.swift */, 563B06F621861D8300B38F35 /* ValueObservationCountTests.swift */, 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */, @@ -1733,6 +1736,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + 562B58CB2A29BBEF00E8C75D /* Issue1383.sqlite in Resources */, 569BBA4622906A8200478429 /* InflectionsTests.json in Resources */, 56D496C21D81374C008276D7 /* Betty.jpeg in Resources */, ); diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 1eead3f88..eb60e2f27 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -50,6 +50,7 @@ 562393751DEE104400A6B01F /* MapCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393711DEE104400A6B01F /* MapCursorTests.swift */; }; 56256EDE25D1BC07008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256EDD25D1BC07008C2BDD /* ForeignKey.swift */; }; 562756461E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; }; + 562B58CE2A29BC0700E8C75D /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 562B58CC2A29BC0700E8C75D /* Issue1383.sqlite */; }; 562EA8291F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; }; 562EA8321F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; }; 563082EA2430B6CD00C14A05 /* DatabaseCancellable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563082E82430B6CD00C14A05 /* DatabaseCancellable.swift */; }; @@ -470,6 +471,7 @@ 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = ""; }; 56256EDD25D1BC07008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = ""; }; 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = ""; }; + 562B58CC2A29BC0700E8C75D /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = ""; }; 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = ""; }; 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = ""; }; 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = ""; }; @@ -1057,6 +1059,7 @@ 563B06DB2185E04E00B38F35 /* ValueObservation */ = { isa = PBXGroup; children = ( + 562B58CC2A29BC0700E8C75D /* Issue1383.sqlite */, 560233CC2724339A00529DF3 /* SharedValueObservationTests.swift */, 563B06FE21861D9D00B38F35 /* ValueObservationCountTests.swift */, 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */, @@ -1793,6 +1796,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + 562B58CE2A29BC0700E8C75D /* Issue1383.sqlite in Resources */, 569BBA43229066CB00478429 /* InflectionsTests.json in Resources */, F3BA80CD1CFB2FDD003DC1BA /* Betty.jpeg in Resources */, ); diff --git a/Package.swift b/Package.swift index e5e9ef226..dfd0d59fa 100644 --- a/Package.swift +++ b/Package.swift @@ -73,6 +73,7 @@ let package = Package( resources: [ .copy("GRDBTests/Betty.jpeg"), .copy("GRDBTests/InflectionsTests.json"), + .copy("GRDBTests/Issue1383.sqlite"), ], cSettings: cSettings, swiftSettings: swiftSettings) diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index c3b31290c..778e2e8ab 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -443,6 +443,8 @@ 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 */; }; + 567B23172A29BFA400C61174 /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 567B23162A29BFA400C61174 /* Issue1383.sqlite */; }; + 567B23182A29BFA500C61174 /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 567B23162A29BFA400C61174 /* Issue1383.sqlite */; }; 5691D97527257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; }; 5691D97627257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; }; 56F61DF0283D484700AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DEE283D484700AF9884 /* getThreadsCount.c */; }; @@ -676,6 +678,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; }; 565A27CB27871FFF00659A62 /* BackupTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BackupTestCase.swift; sourceTree = ""; }; + 567B23162A29BFA400C61174 /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = ""; }; 5691D97427257CE40021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = ""; }; 56F61DEC283D484700AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = ""; }; 56F61DEE283D484700AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = ""; }; @@ -775,6 +778,7 @@ 56F61DEC283D484700AF9884 /* GRDBTests-Bridging-Header.h */, 564A1F6F226B89D6001F64F1 /* Betty.jpeg */, 56419CDA24A54058004967E1 /* InflectionsTests.json */, + 567B23162A29BFA400C61174 /* Issue1383.sqlite */, 56419CE724A54058004967E1 /* AnyCursorTests.swift */, 56419D2324A5405D004967E1 /* AssociationAggregateTests.swift */, 56419CC124A54056004967E1 /* AssociationBelongsToDecodableRecordTests.swift */, @@ -1086,6 +1090,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + 567B23172A29BFA400C61174 /* Issue1383.sqlite in Resources */, 56419DE324A54062004967E1 /* InflectionsTests.json in Resources */, 564A2026226B89E1001F64F1 /* Betty.jpeg in Resources */, ); @@ -1095,6 +1100,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + 567B23182A29BFA500C61174 /* Issue1383.sqlite in Resources */, 56419DE424A54062004967E1 /* InflectionsTests.json in Resources */, 564A2151226B8E18001F64F1 /* Betty.jpeg in Resources */, ); diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index a92a67097..a8948c5e7 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -445,6 +445,8 @@ 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 */; }; + 567B231A2A29BFE100C61174 /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 567B23192A29BFE100C61174 /* Issue1383.sqlite */; }; + 567B231B2A29BFE100C61174 /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 567B23192A29BFE100C61174 /* Issue1383.sqlite */; }; 5691D97227257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; }; 5691D97327257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; }; 56F61DF6283D4AB100AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */; }; @@ -679,6 +681,7 @@ 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 = ""; }; + 567B23192A29BFE100C61174 /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = ""; }; 5691D97127257C930021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = ""; }; 56F61DF2283D4AB100AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = ""; }; 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = ""; }; @@ -779,6 +782,7 @@ 564A1F6F226B89D6001F64F1 /* Betty.jpeg */, 56419F4E24A54098004967E1 /* InflectionsTests.json */, 564A2158226C8F24001F64F1 /* db.SQLCipher3 */, + 567B23192A29BFE100C61174 /* Issue1383.sqlite */, 56419FA524A5409E004967E1 /* AnyCursorTests.swift */, 56419F5A24A54098004967E1 /* AssociationAggregateTests.swift */, 56419FBD24A540A0004967E1 /* AssociationBelongsToDecodableRecordTests.swift */, @@ -1090,6 +1094,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + 567B231A2A29BFE100C61174 /* Issue1383.sqlite in Resources */, 5641A06A24A540A1004967E1 /* InflectionsTests.json in Resources */, 564A2026226B89E1001F64F1 /* Betty.jpeg in Resources */, 564A2159226C8F25001F64F1 /* db.SQLCipher3 in Resources */, @@ -1100,6 +1105,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + 567B231B2A29BFE100C61174 /* Issue1383.sqlite in Resources */, 5641A06B24A540A1004967E1 /* InflectionsTests.json in Resources */, 564A2151226B8E18001F64F1 /* Betty.jpeg in Resources */, 564A215A226C8F25001F64F1 /* db.SQLCipher3 in Resources */, diff --git a/Tests/GRDBTests/Issue1383.sqlite b/Tests/GRDBTests/Issue1383.sqlite new file mode 100644 index 0000000000000000000000000000000000000000..9b05e30b30c7d79ef3d3e4ee861cd0262cb1667f GIT binary patch literal 8192 zcmeI#F$w}P5QX7M5Sv9}XX%vMXyFB1CEYgaULe9QEGUA^eJuq~VHOl@?5yN}WXKDo z`noyns?Hj1FV}N2UCCIym$j;h6nT7}SKK|9!TXhO_tC%ALKf{~)PD{)$%i0-00Iag zfB*srAbH + func testIssue1383_createWal() throws { + let url = testBundle.url(forResource: "Issue1383", withExtension: "sqlite")! + // Delete files created by previous test runs + try? FileManager.default.removeItem(at: url.deletingLastPathComponent().appendingPathComponent("Issue1383.sqlite-wal")) + try? FileManager.default.removeItem(at: url.deletingLastPathComponent().appendingPathComponent("Issue1383.sqlite-shm")) + + let dbPool = try DatabasePool(path: url.path) + let observation = ValueObservation.tracking(Table("t").fetchCount) + _ = observation.start( + in: dbPool, scheduling: .immediate, + onError: { error in + XCTFail("Unexpected error \(error)") + }, + onChange: { _ in + }) + } + } From 5ab0d18055916eacd928fb2882bc547460ca7c80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Fri, 2 Jun 2023 09:34:02 +0200 Subject: [PATCH 10/14] Failing tests for non-empty wal files on DatabasePool creation --- Tests/GRDBTests/DatabasePoolTests.swift | 85 ++++++++++++++++++++++++- 1 file changed, 83 insertions(+), 2 deletions(-) diff --git a/Tests/GRDBTests/DatabasePoolTests.swift b/Tests/GRDBTests/DatabasePoolTests.swift index 379bb5a98..cc6e24df1 100644 --- a/Tests/GRDBTests/DatabasePoolTests.swift +++ b/Tests/GRDBTests/DatabasePoolTests.swift @@ -3,11 +3,92 @@ import GRDB class DatabasePoolTests: GRDBTestCase { func testDatabasePoolCreatesWalShm() throws { - let dbPool = try makeDatabasePool() - withExtendedLifetime(dbPool) { + let dbPool = try makeDatabasePool(filename: "test") + try withExtendedLifetime(dbPool) { let fm = FileManager() XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-wal")) XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-shm")) + +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) + // A non-empty wal file makes sure ValueObservation can use wal snapshots. + // See + let walURL = URL(fileURLWithPath: dbPool.path + "-wal") + let walSize = try walURL.resourceValues(forKeys: [.fileSizeKey]).fileSize! + XCTAssertGreaterThan(walSize, 0) +#endif + } + } + + func testDatabasePoolCreatesWalShmFromNonWalDatabase() throws { + do { + let dbQueue = try makeDatabaseQueue(filename: "test") + try dbQueue.writeWithoutTransaction { db in + try db.execute(sql: "CREATE TABLE t(a)") + } + } + do { + let dbPool = try makeDatabasePool(filename: "test") + try withExtendedLifetime(dbPool) { + let fm = FileManager() + XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-wal")) + XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-shm")) + +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) + // A non-empty wal file makes sure ValueObservation can use wal snapshots. + // See + let walURL = URL(fileURLWithPath: dbPool.path + "-wal") + let walSize = try walURL.resourceValues(forKeys: [.fileSizeKey]).fileSize! + XCTAssertGreaterThan(walSize, 0) +#endif + } + } + } + + func testDatabasePoolCreatesWalShmFromTruncatedWalFile() throws { + do { + let dbPool = try makeDatabasePool(filename: "test") + try dbPool.writeWithoutTransaction { db in + try db.execute(sql: "CREATE TABLE t(a)") + try db.checkpoint(.truncate) + } + } + do { + let dbPool = try makeDatabasePool(filename: "test") + try withExtendedLifetime(dbPool) { + let fm = FileManager() + XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-wal")) + XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-shm")) + +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) + // A non-empty wal file makes sure ValueObservation can use wal snapshots. + // See + let walURL = URL(fileURLWithPath: dbPool.path + "-wal") + let walSize = try walURL.resourceValues(forKeys: [.fileSizeKey]).fileSize! + XCTAssertGreaterThan(walSize, 0) +#endif + } + } + } + + func testDatabasePoolCreatesWalShmFromIssue1383() throws { + let url = testBundle.url(forResource: "Issue1383", withExtension: "sqlite")! + // Delete files created by previous test runs + try? FileManager.default.removeItem(at: url.deletingLastPathComponent().appendingPathComponent("Issue1383.sqlite-wal")) + try? FileManager.default.removeItem(at: url.deletingLastPathComponent().appendingPathComponent("Issue1383.sqlite-shm")) + + let dbPool = try DatabasePool(path: url.path) + try withExtendedLifetime(dbPool) { + let fm = FileManager() + XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-wal")) + XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-shm")) + +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) + // A non-empty wal file makes sure ValueObservation can use wal snapshots. + // See + let walURL = URL(fileURLWithPath: dbPool.path + "-wal") + let walSize = try walURL.resourceValues(forKeys: [.fileSizeKey]).fileSize! + XCTAssertGreaterThan(walSize, 0) +#endif } } From dc440d5a8f818023cd8cfb203543a1241dbe2457 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Fri, 2 Jun 2023 09:44:18 +0200 Subject: [PATCH 11/14] Fix failing tests for non-empty wal files on DatabasePool creation --- GRDB/Core/DatabasePool.swift | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index b01286ba9..97a6a3113 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -84,12 +84,20 @@ public final class DatabasePool { // > Many applications choose NORMAL when in WAL mode try db.execute(sql: "PRAGMA synchronous = NORMAL") - if !FileManager.default.fileExists(atPath: path + "-wal") { - // Create the -wal file if it does not exist yet. This - // avoids an SQLITE_CANTOPEN (14) error whenever a user - // opens a pool to an existing non-WAL database, and - // attempts to read from it. - // See https://github.com/groue/GRDB.swift/issues/102 + // Make sure a non-empty wal file exist. + // + // The presence of the wal file avoids an SQLITE_CANTOPEN (14) + // error when the user opens a pool and reads from it. + // See . + // + // The non-empty wal file avoids an SQLITE_ERROR (1) error + // when the user opens a pool and creates a wal snapshot + // (which happens when starting a ValueObservation). + // See . + let walPath = path + "-wal" + if try FileManager.default.fileExists(atPath: walPath) == false + || (URL(fileURLWithPath: walPath).resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0) == 0 + { try db.inSavepoint { try db.execute(sql: """ CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY); From 63d360053bb7b6ce1aa171fabdf406565956720e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Fri, 2 Jun 2023 10:20:42 +0200 Subject: [PATCH 12/14] Fix typo and obsolete comments --- GRDB/Core/DatabasePool.swift | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 97a6a3113..1a95430ce 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -84,7 +84,7 @@ public final class DatabasePool { // > Many applications choose NORMAL when in WAL mode try db.execute(sql: "PRAGMA synchronous = NORMAL") - // Make sure a non-empty wal file exist. + // Make sure a non-empty wal file exists. // // The presence of the wal file avoids an SQLITE_CANTOPEN (14) // error when the user opens a pool and reads from it. @@ -677,7 +677,6 @@ extension DatabasePool: DatabaseReader { #if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) /// Returns a long-lived WAL snapshot transaction on a reader connection. func walSnapshotTransaction() throws -> WALSnapshotTransaction { - // TODO #1383: might fail if wal file is truncated guard let readerPool else { throw DatabaseError.connectionIsClosed() } @@ -696,7 +695,6 @@ extension DatabasePool: DatabaseReader { /// - important: The `completion` argument is executed in a serial /// dispatch queue, so make sure you use the transaction asynchronously. func asyncWALSnapshotTransaction(_ completion: @escaping (Result) -> Void) { - // TODO #1383: might fail if wal file is truncated guard let readerPool else { completion(.failure(DatabaseError.connectionIsClosed())) return From fc641092f7177b22cbf7c1d3752e8f4aa41747fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Fri, 2 Jun 2023 12:04:28 +0200 Subject: [PATCH 13/14] Document how truncating wal checkpoints impact ValueObservation --- GRDB/Documentation.docc/Extension/ValueObservation.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/GRDB/Documentation.docc/Extension/ValueObservation.md b/GRDB/Documentation.docc/Extension/ValueObservation.md index fbb434d52..ac5fdb6ab 100644 --- a/GRDB/Documentation.docc/Extension/ValueObservation.md +++ b/GRDB/Documentation.docc/Extension/ValueObservation.md @@ -219,6 +219,9 @@ When needed, you can help GRDB optimize observations and reduce database content > Tip: When the observation tracks a constant database region, create an optimized observation with the ``trackingConstantRegion(_:)`` method. See the documentation of this method for more information about what constitutes a "constant region", and the nature of the optimization. +**Truncating WAL checkpoints impact ValueObservation.** Such checkpoints are performed with ``Database/checkpoint(_:on:)`` or [`PRAGMA wal_checkpoint`](https://www.sqlite.org/pragma.html#pragma_wal_checkpoint). When an observation is started on a ``DatabasePool``, from a database that has a missing or empty [wal file](https://www.sqlite.org/tempfiles.html#write_ahead_log_wal_files), the observation will always notify two values when it starts, even if the database content is not changed. This is a consequence of the impossibility to create the [wal snapshot](https://www.sqlite.org/c3ref/snapshot_get.html) needed for detecting that no changes were performed during the observation startup. If your application performs truncating checkpoints, you will avoid this behavior if you recreate a non-empty wal file before starting observations. To do so, perform any kind of no-op transaction (such a creating and dropping a dummy table). + + ## Topics ### Creating a ValueObservation From fdc8abfdbe6853c000bf80d401f836145061c2dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Fri, 2 Jun 2023 12:07:35 +0200 Subject: [PATCH 14/14] CHANGELOG --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b57e81b34..1be8bd713 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -112,6 +112,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## Next Release + +- **New**: [#1384](https://github.com/groue/GRDB.swift/pull/1384) Allow ValueObservation to start from a truncated wal file +- **Documentation Update**: The [ValueObservation Performance](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation#ValueObservation-Performance)) documentation chapter explains how truncating WAL checkpoints impact `ValueObservation`. + ## 6.14.0 Released May 25, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.13.0...v6.14.0)