diff --git a/CHANGELOG.md b/CHANGELOG.md
index cf4270541..3b823d16b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,7 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 6.x Releases
-- `6.24.x` Releases - [6.24.0](#6240) - [6.24.1](#6241)
+- `6.24.x` Releases - [6.24.0](#6240) - [6.24.1](#6241) - [6.24.2](#6242)
- `6.23.x` Releases - [6.23.0](#6230)
- `6.22.x` Releases - [6.22.0](#6220)
- `6.21.x` Releases - [6.21.0](#6210)
@@ -122,6 +122,13 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
+## 6.24.2
+
+Released January 21, 2024
+
+- **Documentation Update**: [#1485](https://github.com/groue/GRDB.swift/pull/1485) The [Sharing a Database](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing) guide was updated with a new recommendation for databases shared between multiple processes. Writers should always perform IMMEDIATE transactions in order to avoid the `SQLITE_BUSY` error that can occur when transactions overlap. The new recommendation fits in a single line of code: `configuration.defaultTransactionKind = .immediate`.
+- **New**: Associations that involve views instead of tables were already supported, with an explicit `ForeignKey` in their definition. When the foreign key is missing, a clear diagnostic message is now emitted, instead of an unhelpful "no such table" runtime error.
+
## 6.24.1
Released January 6, 2024
diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Info.plist b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Info.plist
index 831251030..0881b8b30 100644
--- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Info.plist
+++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Info.plist
@@ -25,7 +25,7 @@
NSExtensionAttributes
WKAppBundleIdentifier
- com.github.groue.GRDBDemoiOS.watchkitapp
+ com.github.groue.GRDBDemoiOS2.watchkitapp
NSExtensionPointIdentifier
com.apple.watchkit
diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Info.plist b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Info.plist
index 34395e2ee..0478fa15f 100644
--- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Info.plist
+++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Info.plist
@@ -26,7 +26,7 @@
UIInterfaceOrientationPortraitUpsideDown
WKCompanionAppBundleIdentifier
- com.github.groue.GRDBDemoiOS
+ com.github.groue.GRDBDemoiOS2
WKWatchKitApp
diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj
index 0aa7b8379..4d38142d0 100644
--- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj
+++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj
@@ -640,7 +640,7 @@
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
- PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension;
+ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -660,7 +660,7 @@
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
- PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension;
+ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -677,7 +677,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
IBSC_MODULE = GRDBDemoWatchOS_Extension;
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
- PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
+ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -694,7 +694,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
IBSC_MODULE = GRDBDemoWatchOS_Extension;
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
- PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
+ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -832,7 +832,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
- PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
+ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Debug;
@@ -849,7 +849,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
- PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
+ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Release;
diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec
index 466b8cf16..0c76d755e 100644
--- a/GRDB.swift.podspec
+++ b/GRDB.swift.podspec
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
- s.version = '6.24.1'
+ s.version = '6.24.2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
diff --git a/GRDB/Documentation.docc/DatabaseSharing.md b/GRDB/Documentation.docc/DatabaseSharing.md
index 1f2c3928e..50b9569f4 100644
--- a/GRDB/Documentation.docc/DatabaseSharing.md
+++ b/GRDB/Documentation.docc/DatabaseSharing.md
@@ -152,11 +152,14 @@ If several processes want to write in the database, configure the database pool
```swift
var configuration = Configuration()
+configuration.defaultTransactionKind = .immediate
configuration.busyMode = .timeout(/* a TimeInterval */)
let dbPool = try DatabasePool(path: ..., configuration: configuration)
```
-With such a setup, you may still get `SQLITE_BUSY` errors from all write operations. They will occur if the database remains locked by another process for longer than the specified timeout. You can catch those errors:
+Both the `defaultTransactionKind` and `busyMode` are important for preventing `SQLITE_BUSY`. The `immediate` transaction kind prevents write transactions from overlapping, and the busy timeout has write transactions wait, instead of throwing `SQLITE_BUSY`, whenever another process is writing.
+
+With such a setup, you will still get `SQLITE_BUSY` errors if the database remains locked by another process for longer than the specified timeout. You can catch those errors:
```swift
do {
diff --git a/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift b/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift
index 3dbe56009..f1b38d7b5 100644
--- a/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift
+++ b/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift
@@ -32,41 +32,76 @@ struct SQLForeignKeyRequest {
}
// Incomplete information: let's look for schema foreign keys
- let foreignKeys = try db.foreignKeys(on: originTable).filter { foreignKey in
- if destinationTable.lowercased() != foreignKey.destinationTable.lowercased() {
- return false
- }
- if let originColumns {
- let originColumns = Set(originColumns.lazy.map { $0.lowercased() })
- let foreignKeyColumns = Set(foreignKey.mapping.lazy.map { $0.origin.lowercased() })
- if originColumns != foreignKeyColumns {
- return false
- }
- }
- if let destinationColumns {
- // TODO: test
- let destinationColumns = Set(destinationColumns.lazy.map { $0.lowercased() })
- let foreignKeyColumns = Set(foreignKey.mapping.lazy.map { $0.destination.lowercased() })
- if destinationColumns != foreignKeyColumns {
- return false
- }
- }
- return true
+ //
+ // But maybe the tables are views. In this case, don't throw
+ // "no such table" error, because this is confusing for the user,
+ // as discovered in .
+ // Instead, we'll crash with a clear message.
+
+ guard let originType = try tableType(db, for: originTable) else {
+ throw DatabaseError.noSuchTable(originTable)
}
- // Matching foreign key(s) found
- if let foreignKey = foreignKeys.first {
- if foreignKeys.count == 1 {
- // Non-ambiguous
- return foreignKey.mapping
- } else {
- // Ambiguous: can't choose
- fatalError("Ambiguous foreign key from \(originTable) to \(destinationTable)")
+ if originType.isView {
+ if originColumns == nil {
+ fatalError("""
+ Could not infer foreign key from '\(originTable)' \
+ to '\(destinationTable)'. To fix this error, provide an \
+ explicit `ForeignKey` in the association definition.
+ """)
+ }
+ } else {
+ let foreignKeys = try db.foreignKeys(on: originTable).filter { foreignKey in
+ if destinationTable.lowercased() != foreignKey.destinationTable.lowercased() {
+ return false
+ }
+ if let originColumns {
+ let originColumns = Set(originColumns.lazy.map { $0.lowercased() })
+ let foreignKeyColumns = Set(foreignKey.mapping.lazy.map { $0.origin.lowercased() })
+ if originColumns != foreignKeyColumns {
+ return false
+ }
+ }
+ if let destinationColumns {
+ // TODO: test
+ let destinationColumns = Set(destinationColumns.lazy.map { $0.lowercased() })
+ let foreignKeyColumns = Set(foreignKey.mapping.lazy.map { $0.destination.lowercased() })
+ if destinationColumns != foreignKeyColumns {
+ return false
+ }
+ }
+ return true
+ }
+
+ // Matching foreign key(s) found
+ if let foreignKey = foreignKeys.first {
+ if foreignKeys.count == 1 {
+ // Non-ambiguous
+ return foreignKey.mapping
+ } else {
+ // Ambiguous: can't choose
+ fatalError("""
+ Ambiguous foreign key from '\(originTable)' to \
+ '\(destinationTable)'. To fix this error, provide an \
+ explicit `ForeignKey` in the association definition.
+ """)
+ }
}
}
// No matching foreign key found: use the destination primary key
if let originColumns {
+ guard let destinationType = try tableType(db, for: destinationTable) else {
+ throw DatabaseError.noSuchTable(destinationTable)
+ }
+ if destinationType.isView {
+ fatalError("""
+ Could not infer foreign key from '\(originTable)' \
+ to '\(destinationTable)'. To fix this error, provide an \
+ explicit `ForeignKey` in the association definition, \
+ with both origin and destination columns.
+ """)
+ }
let destinationColumns = try db.primaryKey(destinationTable).columns
if originColumns.count == destinationColumns.count {
let mapping = zip(originColumns, destinationColumns).map {
@@ -76,7 +111,28 @@ struct SQLForeignKeyRequest {
}
}
- fatalError("Could not infer foreign key from \(originTable) to \(destinationTable)")
+ fatalError("""
+ Could not infer foreign key from '\(originTable)' to \
+ '\(destinationTable)'. To fix this error, provide an \
+ explicit `ForeignKey` in the association definition.
+ """)
+ }
+
+ private struct TableType {
+ var isView: Bool
+ }
+
+ private func tableType(_ db: Database, for name: String) throws -> TableType? {
+ for schemaID in try db.schemaIdentifiers() {
+ if try db.schema(schemaID).containsObjectNamed(name, ofType: .table) {
+ return TableType(isView: false)
+ }
+ if try db.schema(schemaID).containsObjectNamed(name, ofType: .view) {
+ return TableType(isView: true)
+ }
+ }
+
+ return nil
}
}
diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift
index 696eae6a1..31a481ccf 100644
--- a/GRDB/ValueObservation/ValueObservation.swift
+++ b/GRDB/ValueObservation/ValueObservation.swift
@@ -310,6 +310,7 @@ extension ValueObservation {
}
}
+// TODO: [GRDB7] Make it Sendable for easier integration with AsyncAlgorithms
/// An asynchronous sequence of values observed by a ``ValueObservation``.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
diff --git a/README.md b/README.md
index e7c052d6e..3fe201971 100644
--- a/README.md
+++ b/README.md
@@ -15,7 +15,7 @@
-**Latest release**: January 6, 2024 • [version 6.24.1](https://github.com/groue/GRDB.swift/tree/v6.24.1) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
+**Latest release**: January 6, 2024 • [version 6.24.2](https://github.com/groue/GRDB.swift/tree/v6.24.2) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
**Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ • SQLite 3.19.3+ • Swift 5.7+ / Xcode 14+
diff --git a/Support/Info.plist b/Support/Info.plist
index b009897a4..ea5eba44d 100644
--- a/Support/Info.plist
+++ b/Support/Info.plist
@@ -15,7 +15,7 @@
CFBundlePackageType
FMWK
CFBundleShortVersionString
- 6.24.1
+ 6.24.2
CFBundleSignature
????
CFBundleVersion
diff --git a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift
index 75f26a493..2e44dfc36 100644
--- a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift
+++ b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift
@@ -1733,6 +1733,81 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
}
}
+ func testTableBelongsToView() throws {
+ try makeDatabaseQueue().write { db in
+ try db.execute(sql: """
+ CREATE TABLE child (foo);
+ CREATE VIEW parent AS SELECT 1 AS bar;
+ """)
+
+ let child = Table("child")
+ let parent = Table("parent")
+ let foreignKey = ForeignKey(["foo"], to: ["bar"])
+ let association = child.belongsTo(parent, using: foreignKey)
+
+ try assertEqualSQL(db, child.joining(required: association), """
+ SELECT "child".* \
+ FROM "child" \
+ JOIN "parent" ON "parent"."bar" = "child"."foo"
+ """)
+ try assertEqualSQL(db, child.joining(optional: association), """
+ SELECT "child".* \
+ FROM "child" \
+ LEFT JOIN "parent" ON "parent"."bar" = "child"."foo"
+ """)
+ }
+ }
+
+ func testViewBelongsToTable() throws {
+ try makeDatabaseQueue().write { db in
+ try db.execute(sql: """
+ CREATE VIEW child AS SELECT 1 AS foo;
+ CREATE TABLE parent(id INTEGER PRIMARY KEY);
+ """)
+
+ let child = Table("child")
+ let parent = Table("parent")
+ let foreignKey = ForeignKey(["foo"])
+ let association = child.belongsTo(parent, using: foreignKey)
+
+ try assertEqualSQL(db, child.joining(required: association), """
+ SELECT "child".* \
+ FROM "child" \
+ JOIN "parent" ON "parent"."id" = "child"."foo"
+ """)
+ try assertEqualSQL(db, child.joining(optional: association), """
+ SELECT "child".* \
+ FROM "child" \
+ LEFT JOIN "parent" ON "parent"."id" = "child"."foo"
+ """)
+ }
+ }
+
+ func testViewBelongsToView() throws {
+ try makeDatabaseQueue().write { db in
+ try db.execute(sql: """
+ CREATE VIEW child AS SELECT 1 AS foo;
+ CREATE VIEW parent AS SELECT 1 AS bar;
+ """)
+
+ let child = Table("child")
+ let parent = Table("parent")
+ let foreignKey = ForeignKey(["foo"], to: ["bar"])
+ let association = child.belongsTo(parent, using: foreignKey)
+
+ try assertEqualSQL(db, child.joining(required: association), """
+ SELECT "child".* \
+ FROM "child" \
+ JOIN "parent" ON "parent"."bar" = "child"."foo"
+ """)
+ try assertEqualSQL(db, child.joining(optional: association), """
+ SELECT "child".* \
+ FROM "child" \
+ LEFT JOIN "parent" ON "parent"."bar" = "child"."foo"
+ """)
+ }
+ }
+
// Regression test for https://github.com/groue/GRDB.swift/issues/495
func testFetchCount() throws {
let dbQueue = try makeDatabaseQueue()
diff --git a/Tests/GRDBTests/DatabaseQueueTests.swift b/Tests/GRDBTests/DatabaseQueueTests.swift
index 4a1b5f333..7bd5adf2b 100644
--- a/Tests/GRDBTests/DatabaseQueueTests.swift
+++ b/Tests/GRDBTests/DatabaseQueueTests.swift
@@ -258,6 +258,140 @@ class DatabaseQueueTests: GRDBTestCase {
try test(qos: .userInitiated)
}
+ // MARK: - SQLITE_BUSY prevention
+
+ // See
+ func test_busy_timeout_does_not_prevent_SQLITE_BUSY_when_write_lock_is_acquired_by_other_connection() throws {
+ var configuration = dbConfiguration!
+ configuration.journalMode = .wal
+ configuration.busyMode = .timeout(1) // Does not help in this case
+
+ let dbQueue1 = try makeDatabaseQueue(filename: "test", configuration: configuration)
+ let dbQueue2 = try makeDatabaseQueue(filename: "test", configuration: configuration)
+
+ // DB1 DB2
+ // BEGIN DEFERRED TRANSACTION
+ // READ
+ let s1 = DispatchSemaphore(value: 0)
+ // BEGIN DEFERRED TRANSACTION
+ // WRITE
+ let s2 = DispatchSemaphore(value: 0)
+ // WRITE -> SQLITE_BUSY because DB2 is already holding the write lock.
+ let s3 = DispatchSemaphore(value: 0)
+ // COMMIT
+
+ let block1 = {
+ try! dbQueue1.inDatabase { db in
+ try db.inTransaction(.deferred) {
+ try db.execute(sql: "SELECT * FROM sqlite_master")
+ s1.signal()
+ s2.wait()
+ do {
+ try db.execute(sql: "CREATE TABLE test1(a)")
+ XCTFail("Expected error")
+ } catch DatabaseError.SQLITE_BUSY {
+ // Test success
+ }
+ s3.signal()
+ return .commit
+ }
+ }
+ }
+
+ let block2 = {
+ try! dbQueue2.inDatabase { db in
+ s1.wait()
+ try db.inTransaction(.deferred) {
+ try db.execute(sql: "CREATE TABLE test2(a)")
+ s2.signal()
+ s3.wait()
+ return .commit
+ }
+ }
+ }
+
+ let blocks = [block1, block2]
+ DispatchQueue.concurrentPerform(iterations: blocks.count) { index in
+ blocks[index]()
+ }
+ }
+
+ // See
+ func test_busy_timeout_does_not_prevent_SQLITE_BUSY_when_write_lock_was_acquired_by_other_connection() throws {
+ var configuration = dbConfiguration!
+ configuration.journalMode = .wal
+ configuration.busyMode = .timeout(1) // Does not help in this case
+
+ let dbQueue1 = try makeDatabaseQueue(filename: "test", configuration: configuration)
+ let dbQueue2 = try makeDatabaseQueue(filename: "test", configuration: configuration)
+
+ // DB1 DB2
+ // BEGIN DEFERRED TRANSACTION
+ // READ
+ let s1 = DispatchSemaphore(value: 0)
+ // WRITE
+ let s2 = DispatchSemaphore(value: 0)
+ // WRITE -> SQLITE_BUSY because write lock can't be acquired,
+ // even though DB2 does no longer hold any lock.
+
+ let block1 = {
+ try! dbQueue1.inDatabase { db in
+ try db.inTransaction(.deferred) {
+ try db.execute(sql: "SELECT * FROM sqlite_master")
+ s1.signal()
+ s2.wait()
+ do {
+ try db.execute(sql: "CREATE TABLE test1(a)")
+ XCTFail("Expected error")
+ } catch DatabaseError.SQLITE_BUSY {
+ // Test success
+ }
+ return .commit
+ }
+ }
+ }
+
+ let block2 = {
+ try! dbQueue2.inDatabase { db in
+ s1.wait()
+ try db.execute(sql: "CREATE TABLE test2(a)")
+ s2.signal()
+ }
+ }
+
+ let blocks = [block1, block2]
+ DispatchQueue.concurrentPerform(iterations: blocks.count) { index in
+ blocks[index]()
+ }
+ }
+
+ // See
+ func test_busy_timeout_and_IMMEDIATE_transactions_do_prevent_SQLITE_BUSY() throws {
+ var configuration = dbConfiguration!
+ // Test fails when this line is commented
+ configuration.defaultTransactionKind = .immediate
+ // Test fails when this line is commented
+ configuration.busyMode = .timeout(10)
+
+ let dbQueue = try makeDatabaseQueue(filename: "test")
+ try dbQueue.inDatabase { db in
+ try db.execute(sql: "PRAGMA journal_mode = wal")
+ try db.execute(sql: "CREATE TABLE test(a)")
+ }
+
+ let parallelWritesCount = 50
+ DispatchQueue.concurrentPerform(iterations: parallelWritesCount) { index in
+ let dbQueue = try! makeDatabaseQueue(filename: "test", configuration: configuration)
+ try! dbQueue.write { db in
+ _ = try Table("test").fetchCount(db)
+ try db.execute(sql: "INSERT INTO test VALUES (1)")
+ }
+ }
+
+ let count = try dbQueue.read(Table("test").fetchCount)
+ XCTAssertEqual(count, parallelWritesCount)
+ }
+
// MARK: - Closing
func testClose() throws {