Merge pull request #1384 from groue/dev/issue-1383

Allow ValueObservation to start from a truncated wal file
This commit is contained in:
Gwendal Roué authored and GitHub committed 2023-06-02 13:29:27 +02:00
commit 26b875f64c
14 files changed
+298 -32

No files matched your search

+5
View File
@@ -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)
+4
View File
@@ -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 = "<group>"; };
56256ED825D1B316008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = "<group>"; };
562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = "<group>"; };
562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = "<group>"; };
562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = "<group>"; };
562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = "<group>"; };
56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = "<group>"; };
@@ -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 */,
);
+19 -9
View File
@@ -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 exists.
//
// The presence of the wal file avoids an SQLITE_CANTOPEN (14)
// error when the user opens a pool and reads from it.
// See <https://github.com/groue/GRDB.swift/issues/102>.
//
// 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 <https://github.com/groue/GRDB.swift/issues/1383>.
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);
@@ -900,9 +908,11 @@ 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: <https://www.sqlite.org/c3ref/snapshot_get.html>
public func makeSnapshotPool() throws -> DatabaseSnapshotPool {
try unsafeReentrantRead { db in
try DatabaseSnapshotPool(db)
+7 -9
View File
@@ -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: <https://www.sqlite.org/c3ref/snapshot_get.html>
///
@@ -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: <https://www.sqlite.org/c3ref/snapshot_get.html>
///
+27 -1
View File
@@ -30,11 +30,30 @@ final class WALSnapshot: Sendable {
return sqlite3_snapshot_get(db.sqliteConnection, "main", $0)
}
guard code == SQLITE_OK else {
// <https://www.sqlite.org/c3ref/snapshot_get.html>
//
// > 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?
@@ -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
@@ -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 <https://github.com/groue/GRDB.swift/issues/1383>
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 <https://github.com/groue/GRDB.swift/issues/1383>
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
+4
View File
@@ -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 = "<group>"; };
56256EDD25D1BC07008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = "<group>"; };
562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = "<group>"; };
562B58CC2A29BC0700E8C75D /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = "<group>"; };
562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = "<group>"; };
562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = "<group>"; };
56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = "<group>"; };
@@ -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 */,
);
+1
View File
@@ -73,6 +73,7 @@ let package = Package(
resources: [
.copy("GRDBTests/Betty.jpeg"),
.copy("GRDBTests/InflectionsTests.json"),
.copy("GRDBTests/Issue1383.sqlite"),
],
cSettings: cSettings,
swiftSettings: swiftSettings)
@@ -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 = "<group>"; };
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 = "<group>"; };
567B23162A29BFA400C61174 /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = "<group>"; };
5691D97427257CE40021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = "<group>"; };
56F61DEC283D484700AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
56F61DEE283D484700AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
@@ -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 */,
);
@@ -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 = "<group>"; };
567B23192A29BFE100C61174 /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = "<group>"; };
5691D97127257C930021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = "<group>"; };
56F61DF2283D4AB100AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
56F61DF4283D4AB100AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
@@ -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 */,
+103 -2
View File
@@ -3,11 +3,112 @@ 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 <https://github.com/groue/GRDB.swift/issues/1383>
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 <https://github.com/groue/GRDB.swift/issues/1383>
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 <https://github.com/groue/GRDB.swift/issues/1383>
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 <https://github.com/groue/GRDB.swift/issues/1383>
let walURL = URL(fileURLWithPath: dbPool.path + "-wal")
let walSize = try walURL.resourceValues(forKeys: [.fileSizeKey]).fileSize!
XCTAssertGreaterThan(walSize, 0)
#endif
}
}
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)
}
}
Binary file not shown.
@@ -1152,4 +1152,78 @@ class ValueObservationTests: GRDBTestCase {
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
}
// Regression test for <https://github.com/groue/GRDB.swift/issues/1383>
func testIssue1383() throws {
do {
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)
}
}
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
})
}
}
// Regression test for <https://github.com/groue/GRDB.swift/issues/1383>
func testIssue1383_async() throws {
do {
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)
}
}
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)
}
}
}
// Regression test for <https://github.com/groue/GRDB.swift/issues/1383>
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
})
}
}