Compare commits

...
Author SHA1 Message Date
Gwendal Roué 66e65db74e [BREAKING] Row refactor 2024-04-01 18:17:28 +02:00
Gwendal Roué 580f6967d1 SQL is Sendable 2024-03-31 18:05:32 +02:00
Gwendal Roué adc88820b8 SQLRelation is Sendable 2024-03-31 18:05:32 +02:00
Gwendal Roué d3f8013d68 Make TableAlias Sendable even if it is not yet. 2024-03-31 18:05:32 +02:00
Gwendal Roué 36e67c40b4 DatabasePromise is Sendable 2024-03-31 18:05:32 +02:00
Gwendal Roué 0078d68d51 FTS5 tokenizers don't need to be Sendable 2024-03-31 18:05:32 +02:00
Gwendal Roué 84876de3c6 Fix a concurrency warning 2024-03-31 18:05:32 +02:00
Gwendal Roué 6e6ac52bfc writePublisher(updates:thenRead:) requires a Sendable Value
... But I don't know if region-based isolation and SE-0430 can relax this constraint or not.
2024-03-31 18:05:32 +02:00
Gwendal Roué 99a178bffd Fix concurrency warning on SQLITE_TRANSIENT 2024-03-31 18:05:32 +02:00
Gwendal Roué 10e6b8c703 ValueObservation.handleEvents accept Sendable closures 2024-03-31 18:05:32 +02:00
Gwendal Roué 6319f3aeb2 ValueObservationScheduler async access requires a Sendable closure 2024-03-31 18:05:32 +02:00
Gwendal Roué c4a24fa578 SerializedDatabase async access requires a Sendable closure 2024-03-31 18:05:32 +02:00
Gwendal Roué 6539c1d8bf WALSnapshotTransaction is Sendable 2024-03-31 10:11:03 +02:00
Gwendal Roué 6b21a21e1f OnDemandFuture fulfill is Sendable 2024-03-31 10:11:03 +02:00
Gwendal Roué fc5ec15bc6 Pool is Sendable 2024-03-30 20:22:16 +01:00
Gwendal Roué b3a7e9f233 ReadWriteBox is Sendable 2024-03-30 20:12:23 +01:00
Gwendal Roué a915ba52c7 Fix concurrency warnings with DispatchSpecificKey 2024-03-30 20:05:41 +01:00
Gwendal Roué a6aa61e789 LogErrorFunction is Sendable 2024-03-30 19:45:28 +01:00
Gwendal Roué cf3f2fcf3a DatabaseCollation is Sendable 2024-03-30 19:45:28 +01:00
Gwendal Roué 9b18b29a3c ValueObservationScheduler is Sendable 2024-03-30 19:45:28 +01:00
Gwendal Roué c676931d76 Record can't be made Sendable
... so that subclasses do not have to be sendable
2024-03-30 19:45:28 +01:00
Gwendal Roué ba1e67b7d3 RowAdapter is Sendable 2024-03-30 19:45:28 +01:00
Gwendal Roué 0cdb2181b1 FilterCursor can't be made Sendable 2024-03-30 19:45:28 +01:00
Gwendal Roué f25d83ed7a Database publishers can't be made Sendable
... because they wrap base publishers that are not :-/
2024-03-30 19:45:28 +01:00
Gwendal Roué f7fdc25061 DatabaseMigrator is Sendable 2024-03-30 19:45:28 +01:00
Gwendal Roué 8a005e17ce DatabaseFunction is Sendable 2024-03-30 19:45:28 +01:00
Gwendal Roué fe474ab95f [BREAKING] Remove DatabaseFuture and concurrentRead
That's one less DispatchSemaphore. We don't need this method anymore.
2024-03-30 19:45:28 +01:00
Gwendal Roué 62ba1c8551 Coding strategies are Sendable 2024-03-30 19:45:28 +01:00
Gwendal Roué 9ae5726fe5 Configuration is Sendable 2024-03-30 19:45:28 +01:00
Gwendal Roué 5bfeeb9952 TransactionClock is Sendable 2024-03-30 17:44:24 +01:00
Gwendal Roué 9a4e65860f BusyCallback and BusyMode are Sendable 2024-03-30 17:44:24 +01:00
Gwendal Roué ec95c61ff3 Tests need a Mutex too 2024-03-30 17:44:24 +01:00
Gwendal Roué 9ad5d89d89 Rename LockedBox to Mutex
Maybe we'll be able to plug in the standard one eventually: https://forums.swift.org/t/pitch-synchronous-mutual-exclusion-lock/69889
2024-03-30 17:44:24 +01:00
Gwendal Roué c23036d168 DatabaseCancellable is Sendable 2024-03-30 17:44:24 +01:00
Gwendal Roué 974597b24e [BREAKING] Remove Configuration.defaultTransactionKind
GRDB know defaults read-only transactions to DEFERRED, and write transactions to IMMEDIATE. See https://github.com/groue/GRDB.swift/issues/1483 for some context.
2024-03-30 17:44:24 +01:00
Gwendal Roué 5289f5d93d [BREAKING] Bump requirements: watchOS 7
Rationale: https://github.com/groue/GRDB.swift/issues/1472#issuecomment-1960696836
2024-03-30 13:39:12 +01:00
Gwendal Roué f6ce2e82f9 [BREAKING] Stop exporting SQLite 2024-03-30 13:27:44 +01:00
Gwendal Roué 3b55e6a5d0 TODO 2024-03-27 17:52:26 +01:00
Gwendal Roué 233078979e [BREAKING] Remove AsyncValueObservation does not need any scheduler 2024-03-27 17:52:26 +01:00
Gwendal Roué cac01e270a [BREAKING] insertAndFetch, saveAndFetch, and updateAndFetch no longer return optionals.
Those optionals were just an annoyance. Now, nil results are replaced with `RecordError.recordNotFound`. Such an error is only expected with the IGNORE conflict policy.
2024-03-27 17:42:27 +01:00
Gwendal Roué c14b194637 Remove ill-advised TODO
This would force users to force-unwrap their custom `ColumnType(rawValue: "WHATEVER")!`
2024-03-27 17:39:10 +01:00
Gwendal Roué 57ac5ddbb3 [BREAKING] Bump requirements: Swift 5.10, Xcode 15.3, iOS 12, tvOS 12 2024-03-27 17:38:54 +01:00
214 changed files with 3697 additions and 3192 deletions

No files matched your search

+2 -2
View File
@@ -2169,7 +2169,7 @@ struct BookInfo: FetchableRecord {
var country: Country?
var coverImage: CoverImage?
init(row: Row) throws {
init(row: some RowProtocol) throws {
book = try Book(row: row)
author = row["author"]
country = row["country"]
@@ -2204,7 +2204,7 @@ struct AuthorInfo: FetchableRecord {
var author: Author
var books: [Book]
init(row: Row) throws {
init(row: some RowProtocol) throws {
author = try Author(row: row)
books = row["books"]
}
@@ -1,6 +1,7 @@
import WatchKit
import Foundation
import GRDB
import SQLite3
class InterfaceController: WKInterfaceController {
@@ -75,7 +75,7 @@ struct Place {
// Adopt FetchableRecord
extension Place : FetchableRecord {
init(row: Row) {
init(row: some RowProtocol) {
id = row["id"]
title = row["title"]
favorite = row["favorite"]
+1 -1
View File
@@ -9,7 +9,7 @@ Pod::Spec.new do |s|
s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" }
s.module_name = 'GRDB'
s.swift_versions = ['5.7']
s.swift_versions = ['5.10']
s.ios.deployment_target = '11.0'
s.osx.deployment_target = '10.13'
s.watchos.deployment_target = '4.0'
+21 -9
View File
@@ -186,7 +186,7 @@
566B912B1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; };
566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
566B9C2025C6CC24004542CF /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */; };
566BE71E2342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; };
566BE71E2342542F00A8254B /* Mutex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* Mutex.swift */; };
566DDE0D288D763C0000DCFB /* Fixits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566DDE0C288D763C0000DCFB /* Fixits.swift */; };
56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */; };
@@ -256,6 +256,8 @@
569BBA3622905FFA00478429 /* InflectionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA3522905FFA00478429 /* InflectionsTests.swift */; };
569BBA4622906A8200478429 /* InflectionsTests.json in Resources */ = {isa = PBXBuildFile; fileRef = 569BBA4522906A8200478429 /* InflectionsTests.json */; };
569BBA4E229170F800478429 /* Inflections+English.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA482291707D00478429 /* Inflections+English.swift */; };
569D55322BBAFE9E00B57CA5 /* DetachedRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569D55312BBAFE9E00B57CA5 /* DetachedRow.swift */; };
569D55342BBAFEC700B57CA5 /* StatementRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569D55332BBAFEC700B57CA5 /* StatementRow.swift */; };
569D6DDE220EF9E100A058A9 /* SQLInterpolation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */; };
569EF0E2200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */; };
56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238701B9C75030082EB20 /* Configuration.swift */; };
@@ -267,7 +269,6 @@
56A2388B1B9C75030082EB20 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238781B9C75030082EB20 /* Statement.swift */; };
56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; };
56A238A41B9C753B0082EB20 /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; };
56A2FA3624424D2A00E97D23 /* Export.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2FA3524424D2A00E97D23 /* Export.swift */; };
56A5EF0F1EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */; };
56A8C2301D1914540096E9D4 /* UUID.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C22F1D1914540096E9D4 /* UUID.swift */; };
56AACAA822ACED7100A40F2A /* Fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AACAA722ACED7100A40F2A /* Fetch.swift */; };
@@ -284,6 +285,7 @@
56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */; };
56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B81DA51D0A0002DA19 /* FTS5Pattern.swift */; };
56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */; };
56BCA65C2B79246300B3A7F8 /* Mutex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA65B2B79246300B3A7F8 /* Mutex.swift */; };
56BF2282241781C5003D86EB /* UtilsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF2281241781C5003D86EB /* UtilsTests.swift */; };
56CC922C201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */; };
56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */; };
@@ -411,6 +413,7 @@
56F89E152A585C0B002FE2AA /* SQLTableAlterationGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */; };
56FA0C3028B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */; };
56FA0C3928B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */; };
56FA602F2BB96AA50085DEB7 /* RowProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA602E2BB96AA50085DEB7 /* RowProtocol.swift */; };
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
56FEB8F8248403000081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */; };
56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; };
@@ -628,7 +631,7 @@
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = "<group>"; };
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = "<group>"; };
566B9C1F25C6CC24004542CF /* RowDecodingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowDecodingError.swift; sourceTree = "<group>"; };
566BE7172342542F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.swift; sourceTree = "<group>"; };
566BE7172342542F00A8254B /* Mutex.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Mutex.swift; sourceTree = "<group>"; };
566DDE0C288D763C0000DCFB /* Fixits.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Fixits.swift; sourceTree = "<group>"; };
56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = "<group>"; };
56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONRequiredEncoder.swift; sourceTree = "<group>"; };
@@ -721,6 +724,8 @@
569BBA4522906A8200478429 /* InflectionsTests.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = InflectionsTests.json; sourceTree = "<group>"; };
569BBA482291707D00478429 /* Inflections+English.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Inflections+English.swift"; sourceTree = "<group>"; };
569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdogTests.swift; sourceTree = "<group>"; };
569D55312BBAFE9E00B57CA5 /* DetachedRow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DetachedRow.swift; sourceTree = "<group>"; };
569D55332BBAFEC700B57CA5 /* StatementRow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementRow.swift; sourceTree = "<group>"; };
569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLInterpolation.swift; sourceTree = "<group>"; };
569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegion.swift; sourceTree = "<group>"; };
56A238131B9C74A90082EB20 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = "<group>"; };
@@ -755,7 +760,6 @@
56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseMigrator.swift; sourceTree = "<group>"; };
56A238A11B9C753B0082EB20 /* Record.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Record.swift; sourceTree = "<group>"; };
56A238B51B9CA2590082EB20 /* DatabaseTimestampTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTimestampTests.swift; sourceTree = "<group>"; };
56A2FA3524424D2A00E97D23 /* Export.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Export.swift; sourceTree = "<group>"; };
56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpressionLiteralTests.swift; sourceTree = "<group>"; };
56A5E4081BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordWithColumnNameManglingTests.swift; sourceTree = "<group>"; };
56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyInfoTests.swift; sourceTree = "<group>"; };
@@ -783,6 +787,7 @@
56B964C11DA521450002DA19 /* FTS5RecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5RecordTests.swift; sourceTree = "<group>"; };
56B964C21DA521450002DA19 /* FTS5TableBuilderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TableBuilderTests.swift; sourceTree = "<group>"; };
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdog.swift; sourceTree = "<group>"; };
56BCA65B2B79246300B3A7F8 /* Mutex.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Mutex.swift; sourceTree = "<group>"; };
56BF2281241781C5003D86EB /* UtilsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UtilsTests.swift; sourceTree = "<group>"; };
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSavepointTests.swift; sourceTree = "<group>"; };
56C48E731C9A9923005DF1D9 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = module.modulemap; sourceTree = "<group>"; };
@@ -846,6 +851,7 @@
56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLTableAlterationGenerator.swift; sourceTree = "<group>"; };
56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Upsert.swift"; sourceTree = "<group>"; };
56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Upsert.swift"; sourceTree = "<group>"; };
56FA602E2BB96AA50085DEB7 /* RowProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowProtocol.swift; sourceTree = "<group>"; };
56FBFED82210731A00945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = "<group>"; };
56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = "<group>"; };
56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseTraceTests.swift; sourceTree = "<group>"; };
@@ -1010,6 +1016,7 @@
children = (
56677C14241D14450050755D /* FailureTestCase.swift */,
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
56BCA65B2B79246300B3A7F8 /* Mutex.swift */,
562EA81E1F17B26F00FA528C /* Compilation */,
56A238111B9C74A90082EB20 /* Core */,
567B5BDA2AD3281B00629622 /* Dump */,
@@ -1318,7 +1325,7 @@
56717270261C68E900423B6F /* CaseInsensitiveIdentifier.swift */,
563EF4492161F179007DAACD /* Inflections.swift */,
569BBA482291707D00478429 /* Inflections+English.swift */,
566BE7172342542F00A8254B /* LockedBox.swift */,
566BE7172342542F00A8254B /* Mutex.swift */,
563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */,
563EF414215F87EB007DAACD /* OrderedDictionary.swift */,
5659F4971EA8D989004A4992 /* Pool.swift */,
@@ -1584,13 +1591,15 @@
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
569D55312BBAFE9E00B57CA5 /* DetachedRow.swift */,
569D55332BBAFEC700B57CA5 /* StatementRow.swift */,
5636E9BB1D22574100B9B05F /* FetchRequest.swift */,
56A238761B9C75030082EB20 /* Row.swift */,
567404871CEF84C8003ED5CC /* RowAdapter.swift */,
566B9C1F25C6CC24004542CF /* RowDecodingError.swift */,
56FA602E2BB96AA50085DEB7 /* RowProtocol.swift */,
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */,
56E9FAD7221053DC00C703A8 /* SQL.swift */,
569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */,
56FBFED82210731A00945324 /* SQLRequest.swift */,
@@ -1600,6 +1609,7 @@
56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */,
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
56B7EE822863781300C0525F /* WALSnapshot.swift */,
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */,
5605F1471C672E4000235C62 /* Support */,
);
path = Core;
@@ -1737,7 +1747,6 @@
DC37742D19C8CC90004FCF85 /* GRDB */ = {
isa = PBXGroup;
children = (
56A2FA3524424D2A00E97D23 /* Export.swift */,
566DDE0C288D763C0000DCFB /* Fixits.swift */,
648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */,
56A2386F1B9C75030082EB20 /* Core */,
@@ -2101,6 +2110,7 @@
56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */,
56D496C11D81373A008276D7 /* DatabaseQueueBackupTests.swift in Sources */,
562393721DEE104400A6B01F /* MapCursorTests.swift in Sources */,
56BCA65C2B79246300B3A7F8 /* Mutex.swift in Sources */,
56D496571D81303E008276D7 /* FoundationDateComponentsTests.swift in Sources */,
568C3F7A2A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift in Sources */,
56D496701D81309E008276D7 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
@@ -2222,13 +2232,13 @@
5617294E223533F40006E219 /* EncodableRecord.swift in Sources */,
56B7EE832863781300C0525F /* WALSnapshot.swift in Sources */,
5698AD181DAAD17A0056AF8C /* FTS5Tokenizer.swift in Sources */,
56A2FA3624424D2A00E97D23 /* Export.swift in Sources */,
56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
4E13D2F32769B87F0037588C /* DatabaseBackupProgress.swift in Sources */,
560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
563B8FAC24A1CE43007A48C9 /* DatabasePublishers.swift in Sources */,
56F89E0C2A57EC16002FE2AA /* SQLTableGenerator.swift in Sources */,
56F89DFC2A57EAEA002FE2AA /* ForeignKeyDefinition.swift in Sources */,
569D55322BBAFE9E00B57CA5 /* DetachedRow.swift in Sources */,
56FA0C3028B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */,
5605F1691C672E4000235C62 /* NSString.swift in Sources */,
560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */,
@@ -2263,9 +2273,10 @@
5656A8AD2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */,
56D110C428AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */,
5690C3401D23E82A00E59934 /* Data.swift in Sources */,
56FA602F2BB96AA50085DEB7 /* RowProtocol.swift in Sources */,
5659F4881EA8D94E004A4992 /* Utils.swift in Sources */,
567B5BE82AD3284100629622 /* DumpFormat.swift in Sources */,
566BE71E2342542F00A8254B /* LockedBox.swift in Sources */,
566BE71E2342542F00A8254B /* Mutex.swift in Sources */,
56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
5603CEBB2AC862EC00CF097D /* SQLJSONExpressible.swift in Sources */,
56F89DF72A57EAA9002FE2AA /* ColumnDefinition.swift in Sources */,
@@ -2319,6 +2330,7 @@
567B5BEC2AD3284100629622 /* Database+Dump.swift in Sources */,
56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */,
567B5BEB2AD3284100629622 /* DebugDumpFormat.swift in Sources */,
569D55342BBAFEC700B57CA5 /* StatementRow.swift in Sources */,
56B9649D1DA51B4C0002DA19 /* FTS5.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
+32 -28
View File
@@ -1,7 +1,17 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Dispatch
import Foundation
public struct Configuration {
// TODO: remove @unchecked when DispatchQoS is Sendable
public struct Configuration: @unchecked Sendable {
// MARK: - Misc options
@@ -186,7 +196,7 @@ public struct Configuration {
// MARK: - Managing SQLite Connections
private var setups: [(Database) throws -> Void] = []
private var setups: [@Sendable (Database) throws -> Void] = []
/// Defines a function to run whenever an SQLite connection is opened.
///
@@ -223,34 +233,12 @@ public struct Configuration {
///
/// On newly created databases files, ``DatabasePool`` activates the WAL
/// mode after the preparation functions have run.
public mutating func prepareDatabase(_ setup: @escaping (Database) throws -> Void) {
public mutating func prepareDatabase(_ setup: @escaping @Sendable (Database) throws -> Void) {
setups.append(setup)
}
// MARK: - Transactions
/// The default kind of write transactions.
///
/// The default is ``Database/TransactionKind/deferred``.
///
/// You can change the default transaction kind. For example, you can force
/// all write transactions to be `IMMEDIATE`:
///
/// ```swift
/// var config = Configuration()
/// config.defaultTransactionKind = .immediate
/// let dbQueue = try DatabaseQueue(configuration: config)
///
/// // BEGIN IMMEDIATE TRANSACTION; ...; COMMIT TRANSACTION;
/// try dbQueue.write { db in ... }
/// ```
///
/// This property is ignored for read-only transactions. Those always open
/// `DEFERRED` SQLite transactions.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>
public var defaultTransactionKind: Database.TransactionKind = .deferred
/// A boolean value indicating whether it is valid to leave a transaction
/// opened at the end of a database access method.
///
@@ -445,9 +433,25 @@ public struct Configuration {
/// through a `SerializedDatabase`.
var threadingMode = Database.ThreadingMode.default
var SQLiteConnectionDidOpen: (() -> Void)?
var SQLiteConnectionWillClose: ((SQLiteConnection) -> Void)?
var SQLiteConnectionDidClose: (() -> Void)?
private(set) var SQLiteConnectionDidOpen: (@Sendable () -> Void)?
private(set) var SQLiteConnectionWillClose: (@Sendable (SQLiteConnection) -> Void)?
private(set) var SQLiteConnectionDidClose: (@Sendable () -> Void)?
// Workaround https://github.com/apple/swift/issues/72727
mutating func onConnectionDidOpen(_ callback: @escaping @Sendable () -> Void) {
SQLiteConnectionDidOpen = callback
}
// Workaround https://github.com/apple/swift/issues/72727
mutating func onConnectionWillClose(_ callback: @escaping @Sendable (SQLiteConnection) -> Void) {
SQLiteConnectionWillClose = callback
}
// Workaround https://github.com/apple/swift/issues/72727
mutating func onConnectionDidClose(_ callback: @escaping @Sendable () -> Void) {
SQLiteConnectionDidClose = callback
}
var SQLiteOpenFlags: CInt {
var flags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE)
if sqlite3_libversion_number() >= 3037000 {
+4
View File
@@ -865,6 +865,10 @@ public final class FilterCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable.
@available(*, unavailable)
extension FilterCursor: Sendable { }
extension FilterCursor: Cursor {
public func next() throws -> Base.Element? {
while let element = try base.next() {
+13 -4
View File
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
extension Database {
/// A cache for the available database schemas.
struct SchemaCache {
@@ -1063,7 +1072,7 @@ public struct ColumnInfo: FetchableRecord, Sendable {
/// For columns that are not part of the primary key, it is zero.
public let primaryKeyIndex: Int
public init(row: Row) {
public init(row: some RowProtocol) {
cid = row["cid"]
name = row["name"]
type = row["type"]
@@ -1229,7 +1238,7 @@ public struct ForeignKeyViolation: Sendable {
}
extension ForeignKeyViolation: FetchableRecord {
public init(row: Row) {
public init(row: some RowProtocol) {
originTable = row[0]
originRowID = row[1]
destinationTable = row[2]
@@ -1472,7 +1481,7 @@ struct TableInfo: FetchableRecord {
var hasRowID: Bool
var strict: Bool
init(row: Row) throws {
init(row: some RowProtocol) throws {
switch row[0] as String {
case "main":
schemaID = .main
@@ -1506,7 +1515,7 @@ struct SchemaObject: Hashable, FetchableRecord {
var tbl_name: String?
var sql: String?
init(row: Row) throws {
init(row: some RowProtocol) throws {
// "rootpage" column is not always there: avoid using numerical indexes
type = row["type"]
name = row["name"]
+10 -1
View File
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
extension Database {
@@ -538,7 +547,7 @@ struct StatementCache {
let statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT))
#else
let statement: Statement
if #available(iOS 12, macOS 10.14, watchOS 5, *) { // SQLite 3.20+
if #available(macOS 10.14, *) { // SQLite 3.20+
statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT))
} else {
statement = try db.makeStatement(sql: sql)
+79 -42
View File
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A raw SQLite connection, suitable for the SQLite C API.
@@ -6,7 +15,7 @@ public typealias SQLiteConnection = OpaquePointer
/// A raw SQLite function argument.
typealias SQLiteValue = OpaquePointer
let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_destructor_type.self)
nonisolated(unsafe) let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_destructor_type.self)
/// An SQLite connection.
///
@@ -113,8 +122,14 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// - ``logError``
/// - ``releaseMemory()``
/// - ``trace(options:_:)``
///
/// ### Supporting Types
///
/// - ``BusyCallback``
/// - ``BusyMode``
/// - ``CheckpointMode``
/// - ``DatabaseBackupProgress``
/// - ``LogErrorFunction``
/// - ``StorageClass``
/// - ``TraceEvent``
/// - ``TracingOptions``
@@ -124,8 +139,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// MARK: - SQLite C API
// TODO: make it non optional, since one can't get a `Database` instance
// after `close()`.
/// The raw SQLite connection, suitable for the SQLite C API.
///
/// The result is nil after the database has been successfully closed with
@@ -136,8 +149,26 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// The error logging function.
///
/// SQLite can be configured to invoke a callback function containing
/// an error code and a terse error message whenever anomalies occur.
///
/// This global error callback must be configured early in the lifetime
/// of your application:
///
/// ```swift
/// Database.logError = { (resultCode, message) in
/// NSLog("%@", "SQLite error \(resultCode): \(message)")
/// }
/// ```
///
/// - warning: Database.logError must be set before any database
/// connection is opened. This includes the connections that your
/// application opens with GRDB, but also connections opened by
/// other tools, such as third-party libraries. Setting it after a
/// connection has been opened is an SQLite misuse, and has no effect.
///
/// Related SQLite documentation: <https://www.sqlite.org/errlog.html>
public static var logError: LogErrorFunction? = nil {
nonisolated(unsafe) public static var logError: LogErrorFunction? = nil {
didSet {
if logError != nil {
_registerErrorLogCallback { (_, code, message) in
@@ -285,7 +316,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
var isInsideTransactionBlock = false
/// Support for `checkForSuspensionViolation(from:)`
@LockedBox var isSuspended = false
let isSuspendedMutex = Mutex(false)
/// Support for `checkForSuspensionViolation(from:)`
/// This cache is never cleared: we assume journal mode never changes.
@@ -1116,22 +1147,25 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
///
/// Suspension ends with `resume()`.
func suspend() {
$isSuspended.update { isSuspended in
let needsInterrupt = isSuspendedMutex.withLock { isSuspended in
if isSuspended {
return
return false
}
// Prevent future lock acquisition
isSuspended = true
// Interrupt the database because this may trigger an
// SQLITE_INTERRUPT error which may itself abort a transaction and
// release a lock. See <https://www.sqlite.org/c3ref/interrupt.html>
return true
}
if needsInterrupt {
// Interrupting the database can trigger an SQLITE_INTERRUPT
// error which may itself abort a transaction and
// release a database lock, which is our goal.
// See <https://www.sqlite.org/c3ref/interrupt.html>
//
// Maybe interrupt will not release any lock. To address this,
// we'll issue a rollback on next database access which requires
// a lock. See `checkForSuspensionViolation(from:).`
interrupt()
// Now what about the eventual remaining lock? We'll issue a
// rollback on next database access which requires a lock, in
// checkForSuspensionViolation(from:).
}
}
@@ -1143,7 +1177,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
///
/// See suspend().
func resume() {
isSuspended = false
isSuspendedMutex.value = false
}
/// Support for `checkForSuspensionViolation(from:)`
@@ -1173,9 +1207,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
///
/// See `suspend()` and ``Configuration/observesSuspensionNotifications``.
func checkForSuspensionViolation(from statement: Statement) throws {
try $isSuspended.read { isSuspended in
let needsAbort = try isSuspendedMutex.withLock { isSuspended in
guard isSuspended else {
return
return false
}
if try journalMode() == "wal" && statement.isReadonly {
@@ -1186,7 +1220,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// Those are not read-only:
// - INSERT ...
// - BEGIN IMMEDIATE TRANSACTION
return
return false
}
if statement.releasesDatabaseLock {
@@ -1195,9 +1229,14 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// - ROLLBACK
// - ROLLBACK TRANSACTION TO SAVEPOINT
// - RELEASE SAVEPOINT
return
return false
}
// Assume statement can acquire a write lock: abort.
return true
}
if needsAbort {
// Attempt at releasing an eventual lock with ROLLBACk,
// as explained in Database.suspend().
//
@@ -1273,14 +1312,10 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// Use ``inSavepoint(_:)`` instead.
///
/// - parameters:
/// - kind: The transaction type (default nil).
/// - kind: The transaction type.
///
/// If nil, and the database connection is read-only, the transaction
/// kind is ``TransactionKind/deferred``.
///
/// If nil, and the database connection is not read-only, the
/// transaction kind is the ``Configuration/defaultTransactionKind``
/// of the ``configuration``.
/// If nil, the transaction kind is DEFERRED when the current
/// database access is read-only, and IMMEDIATE otherwise.
/// - operations: A function that executes SQL statements and returns
/// either ``TransactionCompletion/commit`` or ``TransactionCompletion/rollback``.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or the
@@ -1404,8 +1439,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// By default, top level SQLite savepoints open a
// deferred transaction.
//
// But GRDB database configuration mandates a default transaction
// kind that we have to honor.
// But GRDB prefers immediate transactions for writes.
//
// Besides, starting some (?) SQLCipher/SQLite version, SQLite has a
// bug. Returning 1 from `sqlite3_commit_hook` does not leave the
@@ -1495,16 +1529,20 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// - parameters:
/// - kind: The transaction type (default nil).
///
/// If nil, and the database connection is read-only, the transaction
/// kind is ``TransactionKind/deferred``.
///
/// If nil, and the database connection is not read-only, the
/// transaction kind is the ``Configuration/defaultTransactionKind``
/// of the ``configuration``.
/// If nil, the transaction kind is DEFERRED when the current
/// database access is read-only, and IMMEDIATE otherwise.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func beginTransaction(_ kind: TransactionKind? = nil) throws {
// SQLite throws an error for non-deferred transactions when read-only.
let kind = kind ?? (isReadOnly ? .deferred : configuration.defaultTransactionKind)
// We prefer immediate transactions for writes, so that write
// transactions can not overlap. This reduces the opportunity for
// SQLITE_BUSY, which is immediately thrown whenever a transaction
// is upgraded after an initial read and a concurrent processes
// has acquired the write lock beforehand. This SQLITE_BUSY error
// can not be avoided with a busy timeout.
//
// See <https://github.com/groue/GRDB.swift/issues/1483>.
let kind = kind ?? (isReadOnly ? .deferred : .immediate)
try execute(sql: "BEGIN \(kind.rawValue) TRANSACTION")
assert(sqlite3_get_autocommit(sqliteConnection) == 0)
}
@@ -1814,8 +1852,8 @@ extension Database {
// MARK: - Database-Related Types
/// See BusyMode and <https://www.sqlite.org/c3ref/busy_handler.html>
public typealias BusyCallback = (_ numberOfTries: Int) -> Bool
/// See ``BusyMode`` and <https://www.sqlite.org/c3ref/busy_handler.html>
public typealias BusyCallback = @Sendable (_ numberOfTries: Int) -> Bool
/// When there are several connections to a database, a connection may try
/// to access the database while it is locked by another connection.
@@ -1843,7 +1881,7 @@ extension Database {
/// - <https://www.sqlite.org/c3ref/busy_handler.html>
/// - <https://www.sqlite.org/lang_transaction.html>
/// - <https://www.sqlite.org/wal.html>
public enum BusyMode {
public enum BusyMode: Sendable {
/// The `SQLITE_BUSY` error is immediately returned to the connection
/// that tries to access the locked database.
case immediateError
@@ -1921,7 +1959,6 @@ extension Database {
/// The SQL for the column type (`"TEXT"`, `"BLOB"`, etc.)
public let rawValue: String
// TODO: GRDB7 make it an failable initializer that returns nil when rawValue is empty (or blank).
/// Creates an SQL column type.
public init(rawValue: String) {
self.rawValue = rawValue
@@ -2004,7 +2041,7 @@ extension Database {
}
/// An error log function that takes an error code and message.
public typealias LogErrorFunction = (_ resultCode: ResultCode, _ message: String) -> Void
public typealias LogErrorFunction = @Sendable (_ resultCode: ResultCode, _ message: String) -> Void
/// An SQLite storage class.
///
+12 -3
View File
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// `DatabaseCollation` is a custom string comparison function used by SQLite.
@@ -20,10 +29,10 @@ import Foundation
/// - ``localizedCompare``
/// - ``localizedStandardCompare``
/// - ``unicodeCompare``
public final class DatabaseCollation {
public final class DatabaseCollation: Sendable {
/// The name of the collation.
public let name: String
let function: (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
let function: @Sendable (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
/// Creates a collation.
///
@@ -40,7 +49,7 @@ public final class DatabaseCollation {
/// - parameters:
/// - name: The collation name.
/// - function: A function that compares two strings.
public init(_ name: String, function: @escaping (String, String) -> ComparisonResult) {
public init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
self.name = name
self.function = { (length1, buffer1, length2, buffer2) in
// Buffers are not C strings: they do not end with \0.
+13
View File
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// An SQLite result code.
@@ -406,6 +415,10 @@ extension DatabaseError {
static func connectionIsClosed() -> Self {
DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")
}
static func snapshotIsLost() -> Self {
DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.")
}
}
// Support for `catch DatabaseError.SQLITE_XXX`
+15 -6
View File
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A custom SQL function or aggregate.
///
/// ## Topics
@@ -20,7 +29,7 @@
/// - ``localizedUppercase``
/// - ``lowercase``
/// - ``uppercase``
public final class DatabaseFunction: Hashable {
public final class DatabaseFunction: Hashable, Sendable {
// SQLite identifies functions by (name + argument count)
private struct Identity: Hashable {
let name: String
@@ -73,11 +82,11 @@ public final class DatabaseFunction: Hashable {
_ name: String,
argumentCount: Int? = nil,
pure: Bool = false,
function: @escaping ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
function: @escaping @Sendable ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
{
self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
self.isPure = pure
self.kind = .function{ (argc, argv) in
self.kind = .function { (argc, argv) in
let arguments = (0..<Int(argc)).map { index in
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
}
@@ -265,12 +274,12 @@ public final class DatabaseFunction: Hashable {
/// A function kind: an "SQL function" or an "aggregate".
/// See <http://sqlite.org/capi3ref.html#sqlite3_create_function>
private enum Kind {
private enum Kind: Sendable {
/// A regular function: SELECT f(1)
case function((CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?)
case function(@Sendable (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?)
/// An aggregate: SELECT f(foo) FROM bar GROUP BY baz
case aggregate(() -> any DatabaseAggregate)
case aggregate(@Sendable () -> any DatabaseAggregate)
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
+21 -44
View File
@@ -11,7 +11,7 @@ public final class DatabasePool {
/// It is constant, until close() sets it to nil.
private var readerPool: Pool<SerializedDatabase>?
@LockedBox var databaseSnapshotCount = 0
let databaseSnapshotCountMutex = Mutex(0)
/// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers.
private var suspensionObservers: [NSObjectProtocol] = []
@@ -62,17 +62,15 @@ public final class DatabasePool {
// an opened transaction.
readerConfiguration.allowsUnsafeTransactions = false
var readerCount = 0
readerPool = Pool(
maximumCount: configuration.maximumReaderCount,
qos: configuration.readQoS,
makeElement: {
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
makeElement: { [readerConfiguration] index in
return try SerializedDatabase(
path: path,
configuration: readerConfiguration,
defaultLabel: "GRDB.DatabasePool",
purpose: "reader.\(readerCount)")
purpose: "reader.\(index)")
})
// Set up journal mode unless readonly
@@ -118,10 +116,6 @@ public final class DatabasePool {
configuration.readonly = true
// Readers use deferred transactions by default.
// Other transaction kinds are forbidden by SQLite in read-only connections.
configuration.defaultTransactionKind = .deferred
// <https://www.sqlite.org/wal.html#sometimes_queries_return_sqlite_busy_in_wal_mode>
// > But there are some obscure cases where a query against a WAL-mode
// > database can return SQLITE_BUSY, so applications should be prepared
@@ -148,7 +142,7 @@ public final class DatabasePool {
}
}
// @unchecked because of databaseSnapshotCount, readerPool and suspensionObservers
// @unchecked because of readerPool and suspensionObservers
extension DatabasePool: @unchecked Sendable { }
extension DatabasePool {
@@ -257,7 +251,9 @@ extension DatabasePool {
// has freed its memory. That's better than nothing.
releaseMemoryEventually()
writer.async { _ in
application.endBackgroundTask(task)
DispatchQueue.main.async {
application.endBackgroundTask(task)
}
}
}
}
@@ -357,7 +353,7 @@ extension DatabasePool: DatabaseReader {
}
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
@@ -401,7 +397,7 @@ extension DatabasePool: DatabaseReader {
}
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
@@ -446,25 +442,7 @@ extension DatabasePool: DatabaseReader {
}
}
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
// The semaphore that blocks until futureResult is defined:
let futureSemaphore = DispatchSemaphore(value: 0)
var futureResult: Result<T, Error>? = nil
asyncConcurrentRead { dbResult in
// Fetch and release the future
futureResult = dbResult.flatMap { db in Result { try value(db) } }
futureSemaphore.signal()
}
return DatabaseFuture {
// Block the future until results are fetched
_ = futureSemaphore.wait(timeout: .distantFuture)
return try futureResult!.get()
}
}
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
asyncConcurrentRead(value)
}
@@ -505,7 +483,7 @@ extension DatabasePool: DatabaseReader {
/// ```
///
/// - parameter value: A function that accesses the database.
public func asyncConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
// Check that we're on the writer queue...
writer.execute { db in
// ... and that no transaction is opened.
@@ -644,8 +622,7 @@ extension DatabasePool: DatabaseReader {
// MARK: - WAL Snapshot Transactions
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
/// Returns a long-lived WAL snapshot transaction on a reader connection.
func walSnapshotTransaction() throws -> WALSnapshotTransaction {
guard let readerPool else {
@@ -665,7 +642,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<WALSnapshotTransaction, Error>) -> Void) {
func asyncWALSnapshotTransaction(_ completion: @escaping @Sendable (Result<WALSnapshotTransaction, Error>) -> Void) {
guard let readerPool else {
completion(.failure(DatabaseError.connectionIsClosed()))
return
@@ -756,7 +733,7 @@ extension DatabasePool: DatabaseWriter {
}
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void) {
guard let readerPool else {
updates(.failure(DatabaseError.connectionIsClosed()))
return
@@ -788,9 +765,10 @@ extension DatabasePool: DatabaseWriter {
///
/// - precondition: This method is not reentrant.
/// - parameters:
/// - kind: The transaction type (default nil). If nil, the transaction
/// type is the ``Configuration/defaultTransactionKind`` of the
/// the ``configuration``.
/// - kind: The transaction type (default nil).
///
/// If nil, the transaction kind is DEFERRED when the database
/// connection is read-only, and IMMEDIATE otherwise.
/// - updates: A function that updates the database.
/// - throws: The error thrown by `updates`, or by the wrapping transaction.
public func writeInTransaction(
@@ -809,7 +787,7 @@ extension DatabasePool: DatabaseWriter {
try writer.reentrantSync(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
writer.async(updates)
}
}
@@ -867,11 +845,10 @@ extension DatabasePool {
path: path,
configuration: DatabasePool.readerConfiguration(writer.configuration),
defaultLabel: "GRDB.DatabasePool",
purpose: "snapshot.\($databaseSnapshotCount.increment())")
purpose: "snapshot.\(databaseSnapshotCountMutex.increment())")
}
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
/// Creates a database snapshot that allows concurrent accesses to an
/// unchanging database content, as it exists at the moment the snapshot
/// is created.
+1 -1
View File
@@ -1,5 +1,5 @@
#if canImport(Combine)
/// A namespace for database Combine publishers.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public enum DatabasePublishers { }
#endif
+12 -22
View File
@@ -169,7 +169,9 @@ extension DatabaseQueue {
// Release memory asynchronously
writer.async { db in
db.releaseMemory()
application.endBackgroundTask(task)
DispatchQueue.main.async {
application.endBackgroundTask(task)
}
}
}
}
@@ -233,7 +235,7 @@ extension DatabaseQueue: DatabaseReader {
}
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
writer.async { db in
defer {
// Ignore error because we can not notify it.
@@ -258,7 +260,7 @@ extension DatabaseQueue: DatabaseReader {
try writer.sync(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
writer.async { value(.success($0)) }
}
@@ -266,20 +268,7 @@ extension DatabaseQueue: DatabaseReader {
try writer.reentrantSync(value)
}
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
// DatabaseQueue can't perform parallel reads.
// Perform a blocking read instead.
return DatabaseFuture(Result {
// Check that we're on the writer queue, as documented
try writer.execute { db in
try db.isolated(readOnly: true) {
try value(db)
}
}
})
}
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func spawnConcurrentRead(_ value: (Result<Database, Error>) -> Void) {
// Check that we're on the writer queue...
writer.execute { db in
// ... and that no transaction is opened.
@@ -352,9 +341,10 @@ extension DatabaseQueue: DatabaseWriter {
/// ```
///
/// - parameters:
/// - kind: The transaction type (default nil). If nil, the transaction
/// type is the ``Configuration/defaultTransactionKind`` of the
/// the ``configuration``.
/// - kind: The transaction type (default nil).
///
/// If nil, the transaction kind is DEFERRED when the database
/// connection is read-only, and IMMEDIATE otherwise.
/// - updates: A function that updates the database.
/// - throws: The error thrown by `updates`, or by the wrapping transaction.
public func inTransaction(
@@ -379,7 +369,7 @@ extension DatabaseQueue: DatabaseWriter {
try writer.sync(updates)
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void) {
writer.async { updates(.success($0)) }
}
@@ -425,7 +415,7 @@ extension DatabaseQueue: DatabaseWriter {
try writer.reentrantSync(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
writer.async(updates)
}
}
+20 -22
View File
@@ -214,7 +214,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// - parameter value: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void)
func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void)
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -285,7 +285,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// - parameter value: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void)
func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void)
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -458,8 +458,8 @@ extension DatabaseReader {
/// - parameter value: A closure which accesses the database.
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
/// would happen while establishing the database access.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func read<T>(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T {
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(_ value: @escaping @Sendable (Database) throws -> T) async throws -> T {
try await withUnsafeThrowingContinuation { continuation in
asyncRead { result in
do {
@@ -504,8 +504,8 @@ extension DatabaseReader {
/// - parameter value: A closure which accesses the database.
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
/// would happen while establishing the database access.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func unsafeRead<T>(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T {
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func unsafeRead<T>(_ value: @escaping @Sendable (Database) throws -> T) async throws -> T {
try await withUnsafeThrowingContinuation { continuation in
asyncUnsafeRead { result in
do {
@@ -549,17 +549,15 @@ extension DatabaseReader {
///
/// - parameter scheduler: A Combine Scheduler.
/// - parameter value: A closure which accesses the database.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func readPublisher<Output>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
value: @escaping (Database) throws -> Output)
value: @escaping @Sendable (Database) throws -> Output)
-> DatabasePublishers.Read<Output>
{
Deferred {
Future { fulfill in
self.asyncRead { dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db) } })
}
OnDemandFuture { fulfill in
self.asyncRead { dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db) } })
}
}
.receiveValues(on: scheduler)
@@ -567,7 +565,7 @@ extension DatabaseReader {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension DatabasePublishers {
/// A publisher that reads from the database.
///
@@ -586,7 +584,7 @@ extension DatabasePublishers {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension Publisher where Failure == Error {
fileprivate func eraseToReadPublisher() -> DatabasePublishers.Read<Output> {
.init(upstream: eraseToAnyPublisher())
@@ -620,16 +618,16 @@ extension DatabaseReader {
}
return AnyDatabaseCancellable(cancel: { /* nothing to cancel */ })
} else {
var isCancelled = false
let cancellable = AnyDatabaseCancellable()
asyncRead { dbResult in
guard !isCancelled else { return }
if cancellable.isCancelled { return }
let result = dbResult.flatMap { db in
Result { try observation.fetchInitialValue(db) }
}
scheduler.schedule {
guard !isCancelled else { return }
if cancellable.isCancelled { return }
do {
try onChange(result.get())
} catch {
@@ -637,7 +635,7 @@ extension DatabaseReader {
}
}
}
return AnyDatabaseCancellable(cancel: { isCancelled = true })
return cancellable
}
}
}
@@ -678,7 +676,7 @@ extension AnyDatabaseReader: DatabaseReader {
try base.read(value)
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.asyncRead(value)
}
@@ -687,7 +685,7 @@ extension AnyDatabaseReader: DatabaseReader {
try base.unsafeRead(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.asyncUnsafeRead(value)
}
@@ -758,7 +756,7 @@ extension DatabaseSnapshotReader {
}
// There is no such thing as an unsafe access to a snapshot.
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
asyncRead(value)
}
}
+8 -8
View File
@@ -89,16 +89,16 @@ extension DatabaseRegionObservation {
onChange: @escaping (Database) -> Void)
-> AnyDatabaseCancellable
{
@LockedBox var state = ObservationState.pending
let stateMutex = Mutex(ObservationState.pending)
// Use unsafeReentrantWrite so that observation can start from any
// dispatch queue.
writer.unsafeReentrantWrite { db in
do {
let region = try observedRegion(db).observableRegion(db)
$state.update {
stateMutex.withLock { state in
let observer = DatabaseRegionObserver(region: region, onChange: {
if case .cancelled = state {
if case .cancelled = stateMutex.value {
return
}
onChange($0)
@@ -111,7 +111,7 @@ extension DatabaseRegionObservation {
// the observer.
db.add(transactionObserver: observer, extent: .observerLifetime)
$0 = .started(observer)
state = .started(observer)
}
} catch {
onError(error)
@@ -122,13 +122,13 @@ extension DatabaseRegionObservation {
// Deallocates the transaction observer. This makes sure that the
// `onChange` callback will never be called again, because the
// observation was started with the `.observerLifetime` extent.
state = .cancelled
stateMutex.value = .cancelled
}
}
}
#if canImport(Combine)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension DatabaseRegionObservation {
// MARK: - Publishing Impactful Transactions
@@ -140,7 +140,7 @@ extension DatabaseRegionObservation {
///
/// Do not reschedule the publisher with `receive(on:options:)` or any
/// `Publisher` method that schedules publisher elements.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func publisher(in writer: some DatabaseWriter) -> DatabasePublishers.DatabaseRegion {
DatabasePublishers.DatabaseRegion(self, in: writer)
}
@@ -186,7 +186,7 @@ private class DatabaseRegionObserver: TransactionObserver {
}
#if canImport(Combine)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension DatabasePublishers {
/// A publisher that tracks transactions that modify a database region.
///
+2 -6
View File
@@ -126,10 +126,6 @@ public final class DatabaseSnapshot {
// DatabaseSnapshot is read-only.
configuration.readonly = true
// DatabaseSnapshot uses deferred transactions by default.
// Other transaction kinds are forbidden by SQLite in read-only connections.
configuration.defaultTransactionKind = .deferred
// DatabaseSnapshot keeps a long-lived transaction.
configuration.allowsUnsafeTransactions = true
@@ -154,7 +150,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
try reader.sync(block)
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
reader.async { value(.success($0)) }
}
@@ -162,7 +158,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
try reader.sync(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
reader.async { value(.success($0)) }
}
+20 -19
View File
@@ -1,5 +1,13 @@
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A database connection that allows concurrent accesses to an unchanging
/// database content, as it existed at the moment the snapshot was created.
///
@@ -122,6 +130,7 @@ public final class DatabaseSnapshotPool {
/// `db` is used.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public init(_ db: Database, configuration: Configuration? = nil) throws {
let path = db.path
var configuration = Self.configure(configuration ?? db.configuration)
// Acquire and hold WAL snapshot
@@ -130,7 +139,7 @@ public final class DatabaseSnapshotPool {
}
var holderConfig = Configuration()
holderConfig.allowsUnsafeTransactions = true
snapshotHolder = try DatabaseQueue(path: db.path, configuration: holderConfig)
snapshotHolder = try DatabaseQueue(path: path, configuration: holderConfig)
try snapshotHolder.inDatabase { db in
try db.beginTransaction(.deferred)
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
@@ -150,20 +159,18 @@ public final class DatabaseSnapshotPool {
}
self.configuration = configuration
self.path = db.path
self.path = path
self.walSnapshot = walSnapshot
var readerCount = 0
readerPool = Pool(
maximumCount: configuration.maximumReaderCount,
qos: configuration.readQoS,
makeElement: {
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
makeElement: { [configuration] index in
return try SerializedDatabase(
path: db.path,
path: path,
configuration: configuration,
defaultLabel: "GRDB.DatabaseSnapshotPool",
purpose: "snapshot.\(readerCount)")
purpose: "snapshot.\(index)")
})
}
@@ -211,17 +218,15 @@ public final class DatabaseSnapshotPool {
self.path = path
self.walSnapshot = walSnapshot
var readerCount = 0
readerPool = Pool(
maximumCount: configuration.maximumReaderCount,
qos: configuration.readQoS,
makeElement: {
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
makeElement: { [configuration] index in
return try SerializedDatabase(
path: path,
configuration: configuration,
defaultLabel: "GRDB.DatabaseSnapshotPool",
purpose: "snapshot.\(readerCount)")
purpose: "snapshot.\(index)")
})
}
@@ -234,10 +239,6 @@ public final class DatabaseSnapshotPool {
// DatabaseSnapshotPool is read-only.
configuration.readonly = true
// DatabaseSnapshotPool uses deferred transactions by default.
// Other transaction kinds are forbidden by SQLite in read-only connections.
configuration.defaultTransactionKind = .deferred
// DatabaseSnapshotPool keeps a long-lived transaction.
configuration.allowsUnsafeTransactions = true
@@ -292,7 +293,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
@@ -317,7 +318,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
return try reader.reentrantSync { db in
let result = try value(db)
if snapshotIsLost(db) {
throw DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.")
throw DatabaseError.snapshotIsLost()
}
return result
}
+9
View File
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A value stored in a database table.
+13 -39
View File
@@ -129,45 +129,20 @@ extension DatabaseValueConvertible {
// MARK: - Conversions
extension DatabaseValueConvertible {
static func decode(
fromDatabaseValue dbValue: DatabaseValue,
context: @autoclosure () -> RowDecodingContext)
throws -> Self
{
if let value = fromDatabaseValue(dbValue) {
@inlinable
public static func _decode(
databaseValue: DatabaseValue,
context: @autoclosure () -> _RowDecodingContext
) throws -> Self {
if let value = fromDatabaseValue(databaseValue) {
return value
} else {
throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue)
throw RowDecodingError.valueMismatch(
Self.self,
context: context(),
databaseValue: databaseValue)
}
}
static func decode(
fromStatement sqliteStatement: SQLiteStatement,
atUncheckedIndex index: CInt,
context: @autoclosure () -> RowDecodingContext)
throws -> Self
{
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
return try decode(fromDatabaseValue: dbValue, context: context())
}
@usableFromInline
static func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Self {
if let sqliteStatement = row.sqliteStatement {
return try decode(
fromStatement: sqliteStatement,
atUncheckedIndex: CInt(index),
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
return try decode(
fromDatabaseValue: row.impl.databaseValue(atUncheckedIndex: index),
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
@usableFromInline
static func decodeIfPresent(fromRow row: Row, atUncheckedIndex index: Int) throws -> Self? {
try Optional<Self>.decode(fromRow: row, atUncheckedIndex: index)
}
}
// MARK: - Cursors
@@ -215,10 +190,9 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
}
public func _element(sqliteStatement: SQLiteStatement) throws -> Value {
try Value.decode(
fromStatement: sqliteStatement,
atUncheckedIndex: columnIndex,
context: RowDecodingContext(statement: _statement, index: Int(columnIndex)))
try Value._decode(
databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: columnIndex),
context: _RowDecodingContext(statement: _statement, index: Int(columnIndex)))
}
}
+31 -122
View File
@@ -38,9 +38,7 @@ import Dispatch
///
/// ### Reading from the Latest Committed Database State
///
/// - ``concurrentRead(_:)``
/// - ``spawnConcurrentRead(_:)``
/// - ``DatabaseFuture``
///
/// ### Unsafe Methods
///
@@ -181,7 +179,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// - parameter updates: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the barrier access to the database.
func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void)
func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void)
/// Schedules database operations for execution, and returns immediately.
///
@@ -213,7 +211,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// <doc:Concurrency#Rule-2:-Mind-your-transactions> for more information.
///
/// - parameter updates: A closure which accesses the database.
func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void)
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -251,49 +249,6 @@ public protocol DatabaseWriter: DatabaseReader {
// MARK: - Reading from Database
/// Schedules read-only database operations for execution, and returns a
/// future value.
///
/// This method must be called from the writer dispatch queue, outside of
/// any transaction. You'll get a fatal error otherwise.
///
/// Database operations performed by the `value` closure are isolated in a
/// transaction: they do not see changes performed by eventual concurrent
/// writes (even writes performed by other processes).
///
/// They see the database in the state left by the last updates performed
/// by the database writer.
///
/// To access the fetched results, you call the ``DatabaseFuture/wait()``
/// method of the returned future, on any dispatch queue.
///
/// In the example below, the number of players is fetched concurrently with
/// the player insertion. Yet the future is guaranteed to return zero:
///
/// ```swift
/// try writer.writeWithoutTransaction { db in
/// // Delete all players
/// try Player.deleteAll()
///
/// // Count players concurrently
/// let future = writer.concurrentRead { db in
/// return try Player.fetchCount()
/// }
///
/// // Insert a player
/// try Player(...).insert(db)
///
/// // Guaranteed to be zero
/// let count = try future.wait()
/// }
/// ```
///
/// - note: Usage of this method is discouraged, because waiting on the
/// returned ``DatabaseFuture`` blocks a thread. You may prefer
/// ``spawnConcurrentRead(_:)`` instead.
/// - parameter value: A closure which accesses the database.
func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T>
// Exposed for RxGRDB and GRBCombine. Naming is not stabilized.
/// Schedules read-only database operations for execution.
///
@@ -340,7 +295,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// - parameter value: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void)
func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void)
}
extension DatabaseWriter {
@@ -426,8 +381,8 @@ extension DatabaseWriter {
/// - parameter updates: A closure which accesses the database.
/// - parameter completion: A closure called with the transaction result.
public func asyncWrite<T>(
_ updates: @escaping (Database) throws -> T,
completion: @escaping (Database, Result<T, Error>) -> Void)
_ updates: @escaping @Sendable (Database) throws -> T,
completion: @escaping @Sendable (Database, Result<T, Error>) -> Void)
{
asyncWriteWithoutTransaction { db in
do {
@@ -541,7 +496,7 @@ extension DatabaseWriter {
///
/// - Parameter filePath: file path for new database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *)
@available(iOS 14, macOS 10.16, tvOS 14, *)
public func vacuum(into filePath: String) throws {
try writeWithoutTransaction {
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
@@ -607,8 +562,8 @@ extension DatabaseWriter {
/// - throws: The error thrown by `updates`, or any ``DatabaseError`` that
/// would happen while establishing the database access or committing
/// the transaction.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func write<T>(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T {
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func write<T>(_ updates: @escaping @Sendable (Database) throws -> T) async throws -> T {
try await withUnsafeThrowingContinuation { continuation in
asyncWrite(updates, completion: { _, result in
continuation.resume(with: result)
@@ -645,8 +600,8 @@ extension DatabaseWriter {
///
/// - parameter updates: A closure which accesses the database.
/// - throws: The error thrown by `updates`.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func writeWithoutTransaction<T>(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T {
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func writeWithoutTransaction<T>(_ updates: @escaping @Sendable (Database) throws -> T) async throws -> T {
try await withUnsafeThrowingContinuation { continuation in
asyncWriteWithoutTransaction { db in
do {
@@ -697,9 +652,9 @@ extension DatabaseWriter {
///
/// - parameter updates: A closure which accesses the database.
/// - throws: The error thrown by `updates`.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func barrierWriteWithoutTransaction<T>(
_ updates: @Sendable @escaping (Database) throws -> T)
_ updates: @escaping @Sendable (Database) throws -> T)
async throws -> T
{
try await withUnsafeThrowingContinuation { continuation in
@@ -712,7 +667,7 @@ extension DatabaseWriter {
/// Erase the database: delete all content, drop all tables, etc.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func erase() async throws {
try await writeWithoutTransaction { try $0.erase() }
}
@@ -723,7 +678,7 @@ extension DatabaseWriter {
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_vacuum.html>
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func vacuum() async throws {
try await writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
}
@@ -740,7 +695,7 @@ extension DatabaseWriter {
/// Related SQLite documentation: <https://www.sqlite.org/lang_vacuum.html#vacuuminto>
///
/// - Parameter filePath: file path for new database
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func vacuum(into filePath: String) async throws {
try await writeWithoutTransaction {
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
@@ -755,7 +710,7 @@ extension DatabaseWriter {
/// Related SQLite documentation: <https://www.sqlite.org/lang_vacuum.html#vacuuminto>
///
/// - Parameter filePath: file path for new database
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func vacuum(into filePath: String) async throws {
try await writeWithoutTransaction {
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
@@ -800,10 +755,10 @@ extension DatabaseWriter {
///
/// - parameter scheduler: A Combine Scheduler.
/// - parameter updates: A closure which accesses the database.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func writePublisher<Output>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
updates: @escaping (Database) throws -> Output)
updates: @escaping @Sendable (Database) throws -> Output)
-> DatabasePublishers.Write<Output>
{
OnDemandFuture { fulfill in
@@ -817,6 +772,7 @@ extension DatabaseWriter {
.eraseToWritePublisher()
}
// TODO: GRDB7 Can SE-0430 avoid the T: Sendable constraint?
/// Returns a publisher that publishes one value and completes.
///
/// The database is not accessed until subscription. Value and completion
@@ -865,13 +821,13 @@ extension DatabaseWriter {
/// - parameter scheduler: A Combine Scheduler.
/// - parameter updates: A closure which writes in the database.
/// - parameter value: A closure which reads from the database.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func writePublisher<S, T, Output>(
receiveOn scheduler: S = DispatchQueue.main,
updates: @escaping (Database) throws -> T,
thenRead value: @escaping (Database, T) throws -> Output)
updates: @escaping @Sendable (Database) throws -> T,
thenRead value: @escaping @Sendable (Database, T) throws -> Output)
-> DatabasePublishers.Write<Output>
where S: Scheduler
where S: Scheduler, T: Sendable
{
OnDemandFuture { fulfill in
self.asyncWriteWithoutTransaction { db in
@@ -885,7 +841,7 @@ extension DatabaseWriter {
fulfill(.failure(error))
return
}
self.spawnConcurrentRead { dbResult in
self.spawnConcurrentRead { [updatesValue] dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db, updatesValue!) } })
}
}
@@ -897,7 +853,7 @@ extension DatabaseWriter {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension DatabasePublishers {
/// A publisher that writes into the database.
///
@@ -916,7 +872,7 @@ extension DatabasePublishers {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension Publisher where Failure == Error {
fileprivate func eraseToWritePublisher() -> DatabasePublishers.Write<Output> {
.init(upstream: self.eraseToAnyPublisher())
@@ -924,49 +880,6 @@ extension Publisher where Failure == Error {
}
#endif
/// A future database value.
///
/// You get instances of `DatabaseFuture` from the `DatabaseWriter`
/// ``DatabaseWriter/concurrentRead(_:)`` method. For example:
///
/// ```swift
/// let futureCount: Future<Int> = try writer.writeWithoutTransaction { db in
/// try Player(...).insert()
///
/// // Count players concurrently
/// return writer.concurrentRead { db in
/// return try Player.fetchCount()
/// }
/// }
///
/// let count: Int = try futureCount.wait()
/// ```
public class DatabaseFuture<Value> {
private var consumed = false
private let _wait: () throws -> Value
init(_ wait: @escaping () throws -> Value) {
_wait = wait
}
init(_ result: Result<Value, Error>) {
_wait = result.get
}
/// Blocks the current thread until the value is available, and returns it.
///
/// It is a programmer error to call this method several times.
///
/// - throws: Any error that prevented the value from becoming available.
public func wait() throws -> Value {
// Not thread-safe and quick and dirty.
// Goal is that users learn not to call this method twice.
GRDBPrecondition(consumed == false, "DatabaseFuture.wait() must be called only once")
consumed = true
return try _wait()
}
}
/// A type-erased database writer.
///
/// An instance of `AnyDatabaseWriter` forwards its operations to an underlying
@@ -1003,7 +916,7 @@ extension AnyDatabaseWriter: DatabaseReader {
try base.read(value)
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.asyncRead(value)
}
@@ -1012,7 +925,7 @@ extension AnyDatabaseWriter: DatabaseReader {
try base.unsafeRead(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.asyncUnsafeRead(value)
}
@@ -1044,11 +957,11 @@ extension AnyDatabaseWriter: DatabaseWriter {
try base.barrierWriteWithoutTransaction(updates)
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.asyncBarrierWriteWithoutTransaction(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
base.asyncWriteWithoutTransaction(updates)
}
@@ -1056,11 +969,7 @@ extension AnyDatabaseWriter: DatabaseWriter {
try base.unsafeReentrantWrite(updates)
}
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
base.concurrentRead(value)
}
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.spawnConcurrentRead(value)
}
}
+8
View File
@@ -0,0 +1,8 @@
//#warning("TODO: document")
//struct DetachedRow {
//
//}
//
//extension DetachedRow: Row {
//
//}
+127 -973
View File
File diff suppressed because it is too large. Load diff
+6 -6
View File
@@ -83,7 +83,7 @@ import Foundation
/// }
///
/// extension PlayerInfo: FetchableRecord {
/// init(row: Row) {
/// init(row: some RowProtocol) {
/// player = row["player"]
/// team = row["team"]
/// }
@@ -318,7 +318,7 @@ extension Statement: _RowLayout {
/// - ``RenameColumnAdapter``
/// - ``ScopeAdapter``
/// - ``SuffixRowAdapter``
public protocol RowAdapter {
public protocol RowAdapter: Sendable {
/// You never call this method directly. It is called for you whenever an
/// adapter has to be applied.
///
@@ -656,11 +656,11 @@ struct ChainedAdapter: RowAdapter {
/// print(Array(adaptedRow.columnNames))
/// ```
public struct RenameColumnAdapter: RowAdapter {
let transform: (String) -> String
let transform: @Sendable (String) -> String
/// Creates a `RenameColumnAdapter` adapter that renames columns according to the
/// provided transform function.
public init(_ transform: @escaping (String) -> String) {
public init(_ transform: @escaping @Sendable (String) -> String) {
self.transform = transform
}
@@ -698,7 +698,7 @@ struct AdaptedRowImpl: RowImpl {
var count: Int { mapping._layoutColumns.count }
var isFetched: Bool { base.isFetched }
var isFetched: Bool { base._isFetched }
func scopes(prefetchedRows: Row.PrefetchedRowsView) -> Row.ScopesView {
Row.ScopesView(row: base, scopes: adapter._scopes, prefetchedRows: prefetchedRows)
@@ -720,7 +720,7 @@ struct AdaptedRowImpl: RowImpl {
throws -> Value
{
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
return try Value.fastDecode(fromRow: base, atUncheckedIndex: mappedIndex)
return try base._fastDecode(Value.self, atUncheckedIndex: mappedIndex)
}
func withUnsafeData<T>(atUncheckedIndex index: Int, _ body: (Data?) throws -> T) throws -> T {
+23 -33
View File
@@ -1,6 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A key that is used to decode a value in a row
@usableFromInline
enum RowKey: Hashable, Sendable {
public enum _RowKey: Hashable, Sendable {
/// A column name
case columnName(String)
@@ -29,7 +37,7 @@ enum RowDecodingError: Error {
var row: Row { Row(impl: rowImpl) }
/// Nil for RowDecodingError.keyNotFound, in order to avoid redundancy
let key: RowKey?
let key: _RowKey?
/// The SQL query
let sql: String?
@@ -37,7 +45,7 @@ enum RowDecodingError: Error {
/// The SQL query arguments
let statementArguments: StatementArguments?
init(decodingContext: RowDecodingContext, debugDescription: String) {
init(decodingContext: _RowDecodingContext, debugDescription: String) {
self.debugDescription = debugDescription
self.rowImpl = ArrayRowImpl(columns: decodingContext.row)
self.key = decodingContext.key
@@ -46,7 +54,7 @@ enum RowDecodingError: Error {
}
}
case keyNotFound(RowKey, Context)
case keyNotFound(_RowKey, Context)
case valueMismatch(Any.Type, Context)
var context: Context {
@@ -59,9 +67,10 @@ enum RowDecodingError: Error {
/// Convenience method that builds the
/// `could not decode <Type> from database value <value>` error message.
@usableFromInline
static func valueMismatch(
_ type: Any.Type,
context: RowDecodingContext,
context: _RowDecodingContext,
databaseValue: DatabaseValue)
-> Self
{
@@ -79,7 +88,7 @@ enum RowDecodingError: Error {
_ type: Any.Type,
sqliteStatement: SQLiteStatement,
index: CInt,
context: RowDecodingContext)
context: _RowDecodingContext)
-> Self
{
valueMismatch(
@@ -98,14 +107,14 @@ enum RowDecodingError: Error {
{
valueMismatch(
type,
context: RowDecodingContext(statement: statement, index: index),
context: _RowDecodingContext(statement: statement, index: index),
databaseValue: DatabaseValue(sqliteStatement: statement.sqliteStatement, index: CInt(index)))
}
/// Convenience method that builds the `column not found: <column>`
/// error message.
@usableFromInline
static func columnNotFound(_ columnName: String, context: RowDecodingContext) -> Self {
static func columnNotFound(_ columnName: String, context: _RowDecodingContext) -> Self {
keyNotFound(
.columnName(columnName),
RowDecodingError.Context(decodingContext: context, debugDescription: """
@@ -114,39 +123,20 @@ enum RowDecodingError: Error {
}
}
@usableFromInline
struct RowDecodingContext {
public struct _RowDecodingContext {
/// The row that is decoded
let row: Row
let key: RowKey?
let key: _RowKey?
/// The SQL query
let sql: String?
/// The SQL query arguments
let statementArguments: StatementArguments?
@usableFromInline
init(row: Row, key: RowKey? = nil) {
if let statement = row.statement {
self.key = key
self.row = row.copy()
self.sql = statement.sql
self.statementArguments = statement.arguments
} else if let sqliteStatement = row.sqliteStatement {
self.key = key
self.row = row.copy()
self.sql = String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
self.statementArguments = nil // Can't rebuild them
} else {
self.key = key
self.row = row.copy()
self.sql = nil
self.statementArguments = nil
}
}
}
extension _RowDecodingContext {
/// Convenience initializer
@usableFromInline
init(statement: Statement, index: Int) {
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -39,7 +39,7 @@
///
/// - ``append(literal:)``
/// - ``append(sql:arguments:)``
public struct SQL {
public struct SQL: Sendable {
/// `SQL.Element` is a component of an `SQL` literal.
///
/// Elements can be qualified with table aliases, and this is how `SQL`
+1 -1
View File
@@ -22,7 +22,7 @@ import Dispatch
/// - preconditionValidQueue() crashes whenever a database is used in an invalid
/// dispatch queue.
final class SchedulingWatchdog {
private static let watchDogKey = DispatchSpecificKey<SchedulingWatchdog>()
nonisolated(unsafe) private static let watchDogKey = DispatchSpecificKey<SchedulingWatchdog>()
private(set) var allowedDatabases: [Database]
var databaseObservationBroker: DatabaseObservationBroker?
+1 -1
View File
@@ -223,7 +223,7 @@ final class SerializedDatabase {
}
/// Schedules database operations for execution, and returns immediately.
func async(_ block: @escaping (Database) -> Void) {
func async(_ block: @escaping @Sendable (Database) -> Void) {
queue.async {
block(self.db)
self.preconditionNoUnsafeTransactionLeft(self.db)
+10 -1
View File
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A raw SQLite statement, suitable for the SQLite C API.
@@ -137,7 +146,7 @@ public final class Statement {
database.sqliteConnection, statementStart, -1, prepFlags,
&sqliteStatement, statementEnd)
#else
if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { // SQLite 3.20+
if #available(macOS 10.14, *) { // SQLite 3.20+
code = sqlite3_prepare_v3(
database.sqliteConnection, statementStart, -1, prepFlags,
&sqliteStatement, statementEnd)
+9
View File
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
#if os(Linux)
import Glibc
#endif
+26 -58
View File
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A type that can decode itself from the low-level C interface to
/// SQLite results.
///
@@ -23,7 +32,7 @@
/// var name: String
/// var score: Int
///
/// init(row: Row) {
/// init(row: some RowProtocol) {
/// // Optimized
/// name = row["name"]
/// score = row["score"]
@@ -127,62 +136,21 @@ extension StatementColumnConvertible {
// MARK: - Conversions
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
@usableFromInline
/* private */ static func _valueMismatch(
fromStatement sqliteStatement: SQLiteStatement,
extension StatementColumnConvertible {
@inlinable
public static func _fastDecode(
sqliteStatement: SQLiteStatement,
atUncheckedIndex index: CInt,
context: @autoclosure () -> RowDecodingContext)
throws -> Never
{
throw RowDecodingError.valueMismatch(
Self.self,
sqliteStatement: sqliteStatement,
index: index,
context: context())
}
@inline(__always)
@inlinable
static func fastDecode(
fromRow row: Row,
atUncheckedIndex index: Int)
throws -> Self
{
if let sqliteStatement = row.sqliteStatement {
return try fastDecode(
fromStatement: sqliteStatement,
atUncheckedIndex: CInt(index),
context: RowDecodingContext(row: row, key: .columnIndex(index)))
context: @autoclosure () -> _RowDecodingContext
) throws -> Self {
guard let value = fromStatement(sqliteStatement, atUncheckedIndex: index) else {
throw RowDecodingError.valueMismatch(
Self.self,
sqliteStatement: sqliteStatement,
index: index,
context: context())
}
// Support for fast decoding from adapted rows
return try row.fastDecode(Self.self, atUncheckedIndex: index)
}
@inline(__always)
@inlinable
static func fastDecode(
fromStatement sqliteStatement: SQLiteStatement,
atUncheckedIndex index: CInt,
context: @autoclosure () -> RowDecodingContext)
throws -> Self
{
if let value = fromStatement(sqliteStatement, atUncheckedIndex: index) {
return value
} else {
try _valueMismatch(fromStatement: sqliteStatement, atUncheckedIndex: index, context: context())
}
}
// Support for Decodable
@inline(__always)
@inlinable
static func fastDecodeIfPresent(
fromRow row: Row,
atUncheckedIndex index: Int)
throws -> Self?
{
try Optional<Self>.fastDecode(fromRow: row, atUncheckedIndex: index)
return value
}
}
@@ -234,10 +202,10 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
@inlinable
public func _element(sqliteStatement: SQLiteStatement) throws -> Value {
try Value.fastDecode(
fromStatement: sqliteStatement,
try Value._fastDecode(
sqliteStatement: sqliteStatement,
atUncheckedIndex: columnIndex,
context: RowDecodingContext(statement: _statement, index: Int(columnIndex)))
context: _RowDecodingContext(statement: _statement, index: Int(columnIndex)))
}
}
+152
View File
@@ -0,0 +1,152 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
#warning("TODO: document")
final class StatementRow {
private let statement: Statement
private let sqliteStatement: SQLiteStatement
private let lowercaseColumnIndexes: [String: Int]
init(statement: Statement) {
let sqliteStatement = statement.sqliteStatement
self.statement = statement
self.sqliteStatement = sqliteStatement
// Optimize index(forColumn:)
let lowercaseColumnNames = (0..<sqlite3_column_count(sqliteStatement))
.map { String(cString: sqlite3_column_name(sqliteStatement, CInt($0))).lowercased() }
self.lowercaseColumnIndexes = Dictionary(
lowercaseColumnNames
.enumerated()
.map { ($0.element, $0.offset) },
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
}
}
extension StatementRow: RowProtocol {
typealias Index = RowIndex
typealias Element = (String, DatabaseValue)
var prefetchedRows: Row.PrefetchedRowsView {
Row.PrefetchedRowsView()
}
#warning("TODO: wrong return type")
func copy() -> Row {
Row(copiedFromSQLiteStatement: sqliteStatement, statement: statement)
}
func _decode<Strategy: _RowDecodingStrategy>(
with strategy: Strategy,
atUncheckedIndex index: Int
) throws -> Strategy._RowDecodingOutput
{
let statementIndex = CInt(index)
if sqlite3_column_type(sqliteStatement, statementIndex) == SQLITE_NULL {
throw RowDecodingError.valueMismatch(
Strategy._RowDecodingOutput.self,
sqliteStatement: sqliteStatement,
index: statementIndex,
context: _makeRowDecodingContext(forKey: .columnIndex(index)))
}
return try strategy._decode(
sqliteStatement: sqliteStatement,
atUncheckedIndex: CInt(index),
context: _makeRowDecodingContext(forKey: .columnIndex(index)))
}
func _decode<Value: DatabaseValueConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int
) throws -> Value
{
try Value._decode(
databaseValue: _databaseValue(atUncheckedIndex: index),
context: _makeRowDecodingContext(forKey: .columnIndex(index)))
}
func _fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int
) throws -> Value
{
try Value._fastDecode(
sqliteStatement: sqliteStatement,
atUncheckedIndex: CInt(index),
context: _RowDecodingContext(statement: statement, index: index))
}
var _isFetched: Bool {
true
}
func _scopes(prefetchedRows: Row.PrefetchedRowsView) -> Row.ScopesView {
Row.ScopesView()
}
func _columnName(atUncheckedIndex index: Int) -> String {
statement.columnNames[index]
}
func _hasNull(atUncheckedIndex index: Int) -> Bool {
// Avoid extracting values, because this modifies the SQLite statement.
sqlite3_column_type(sqliteStatement, CInt(index)) == SQLITE_NULL
}
func _databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
DatabaseValue(sqliteStatement: sqliteStatement, index: CInt(index))
}
func _withUnsafeData<T>(atUncheckedIndex index: Int, _ body: (Data?) throws -> T) throws -> T {
guard sqlite3_column_type(sqliteStatement, CInt(index)) != SQLITE_NULL else {
return try body(nil)
}
guard let bytes = sqlite3_column_blob(sqliteStatement, CInt(index)) else {
return try body(Data())
}
let count = Int(sqlite3_column_bytes(sqliteStatement, CInt(index)))
let data = Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
return try body(data)
}
#warning("TODO: wrong return type")
var _unscopedRow: Row {
copy()
}
#warning("TODO: wrong return type")
var _unadaptedRow: Row {
copy()
}
#warning("TODO: wrong return type")
var _copiedRow: Row {
copy()
}
func _makeRowDecodingContext(forKey key: _RowKey?) -> _RowDecodingContext {
_RowDecodingContext(
row: copy(),
key: key,
sql: statement.sql,
statementArguments: statement.arguments)
}
func index(forColumn name: String) -> Int? {
if let index = lowercaseColumnIndexes[name] {
return index
}
return lowercaseColumnIndexes[name.lowercased()]
}
}
+9 -24
View File
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// Data is convertible to and from DatabaseValue.
@@ -60,27 +69,3 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible {
}
}
}
// MARK: - Conversions
extension Data {
static func fastDecodeNoCopy(
fromStatement sqliteStatement: SQLiteStatement,
atUncheckedIndex index: CInt,
context: @autoclosure () -> RowDecodingContext)
throws -> Data
{
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else {
throw RowDecodingError.valueMismatch(
Data.self,
sqliteStatement: sqliteStatement,
index: index,
context: context())
}
guard let bytes = sqlite3_column_blob(sqliteStatement, index) else {
return Data()
}
let count = Int(sqlite3_column_bytes(sqliteStatement, index))
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
}
}
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A database value that holds date components.
+9
View File
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
#if !os(Linux)
@@ -1,4 +1,13 @@
#if !os(Linux)
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// Decimal adopts DatabaseValueConvertible
+9
View File
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
#if !os(Linux)
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
extension Optional: StatementBinding where Wrapped: StatementBinding {
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
switch self {
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
// MARK: - Value Types
/// Bool adopts DatabaseValueConvertible and StatementColumnConvertible.
+4 -4
View File
@@ -10,7 +10,7 @@ import Foundation
///
/// - ``DefaultTransactionClock``
/// - ``CustomTransactionClock``
public protocol TransactionClock {
public protocol TransactionClock: Sendable {
/// Returns the date of the current transaction.
///
/// This function is called whenever a transaction starts - precisely
@@ -36,7 +36,7 @@ extension TransactionClock where Self == CustomTransactionClock {
///
/// It is also called when the ``Database/transactionDate`` property is
/// called, and the database connection is not in a transaction.
public static func custom(_ now: @escaping (Database) throws -> Date) -> Self {
public static func custom(_ now: @escaping @Sendable (Database) throws -> Date) -> Self {
CustomTransactionClock(now)
}
}
@@ -53,9 +53,9 @@ public struct DefaultTransactionClock: TransactionClock {
/// A custom transaction clock.
public struct CustomTransactionClock: TransactionClock {
let _now: (Database) throws -> Date
let _now: @Sendable (Database) throws -> Date
public init(_ now: @escaping (Database) throws -> Date) {
public init(_ now: @escaping @Sendable (Database) throws -> Date) {
self._now = now
}
+9
View File
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
extension Database {
// MARK: - Database Observation
+10 -2
View File
@@ -1,5 +1,13 @@
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// An instance of WALSnapshot records the state of a WAL mode database for some
/// specific point in history.
///
+57 -26
View File
@@ -1,12 +1,30 @@
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
/// A long-live read-only WAL transaction.
///
/// `WALSnapshotTransaction` **takes ownership** of its reader
/// `SerializedDatabase` (TODO: make it a move-only type eventually).
class WALSnapshotTransaction {
private let reader: SerializedDatabase
private let release: (_ isInsideTransaction: Bool) -> Void
final class WALSnapshotTransaction: @unchecked Sendable {
// @unchecked because `databaseAccess` is protected by a mutex.
private struct DatabaseAccess {
let reader: SerializedDatabase
let release: @Sendable (_ isInsideTransaction: Bool) -> Void
// MUST be called only once
func commitAndRelease() {
// WALSnapshotTransaction may be deinitialized in the dispatch
// queue of its reader: allow reentrancy.
let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in
try? db.commit()
return db.isInsideTransaction
}
release(isInsideTransaction)
}
}
// TODO: consider using the serialized DispatchQueue of reader instead of a lock.
/// nil when closed
private let databaseAccessMutex: Mutex<DatabaseAccess?>
/// The state of the database at the beginning of the transaction.
let walSnapshot: WALSnapshot
@@ -37,10 +55,11 @@ class WALSnapshotTransaction {
/// is no longer used.
init(
onReader reader: SerializedDatabase,
release: @escaping (_ isInsideTransaction: Bool) -> Void)
release: @escaping @Sendable (_ isInsideTransaction: Bool) -> Void)
throws
{
assert(reader.configuration.readonly)
let databaseAccess = DatabaseAccess(reader: reader, release: release)
do {
// Open a long-lived transaction, and enter snapshot isolation
@@ -51,44 +70,56 @@ class WALSnapshotTransaction {
try db.clearSchemaCacheIfNeeded()
return try WALSnapshot(db)
}
self.reader = reader
self.release = release
self.databaseAccessMutex = Mutex(databaseAccess)
} catch {
// self is not initialized, so deinit will not run.
Self.commitAndRelease(reader: reader, release: release)
databaseAccess.commitAndRelease()
throw error
}
}
deinit {
Self.commitAndRelease(reader: reader, release: release)
close()
}
/// Executes database operations in the snapshot transaction, and
/// returns their result after they have finished executing.
func read<T>(_ value: (Database) throws -> T) rethrows -> T {
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
try reader.sync(value)
func read<T>(_ value: (Database) throws -> T) throws -> T {
try databaseAccessMutex.withLock { databaseAccess in
guard let databaseAccess else {
throw DatabaseError.snapshotIsLost()
}
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
return try databaseAccess.reader.sync(value)
}
}
/// Schedules database operations for execution, and
/// returns immediately.
func asyncRead(_ value: @escaping (Database) -> Void) {
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
reader.async(value)
func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
databaseAccessMutex.withLock { databaseAccess in
guard let databaseAccess else {
value(.failure(DatabaseError.snapshotIsLost()))
return
}
databaseAccess.reader.async { db in
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
// At least check if self was closed:
if self.databaseAccessMutex.value == nil {
value(.failure(DatabaseError.snapshotIsLost()))
}
value(.success(db))
}
}
}
private static func commitAndRelease(
reader: SerializedDatabase,
release: (_ isInsideTransaction: Bool) -> Void)
{
// WALSnapshotTransaction may be deinitialized in the dispatch
// queue of its reader: allow reentrancy.
let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in
try? db.commit()
return db.isInsideTransaction
func close() {
databaseAccessMutex.withLock { databaseAccess in
databaseAccess?.commitAndRelease()
databaseAccess = nil
}
release(isInsideTransaction)
}
}
#endif
+2 -27
View File
@@ -277,31 +277,7 @@ let newPlayerCount = try dbPool.write { db in
}
```
➡️ The synchronous solution is the ``DatabaseWriter/concurrentRead(_:)`` method. It must be called from within a write access, outside of any transaction. It returns a ``DatabaseFuture`` which you consume any time later, with the ``DatabaseFuture/wait()`` method:
```swift
let future: DatabaseFuture<Int> = try dbPool.writeWithoutTransaction { db in
// Increment the number of players
try db.inTransaction {
try Player(...).insert(db)
return .commit
}
// <- Not in a transaction here
return dbPool.concurrentRead { db
try Player.fetchCount(db)
}
}
do {
// Handle the new player count - guaranteed greater than zero
let newPlayerCount = try future.wait()
} catch {
// Handle error
}
```
🔀 The asynchronous version of `concurrentRead` is ``DatabasePool/asyncConcurrentRead(_:)``:
🔀 The solution is ``DatabasePool/asyncConcurrentRead(_:)``. It must be called from within a write access, outside of any transaction:
```swift
try dbPool.writeWithoutTransaction { db in
@@ -324,11 +300,10 @@ try dbPool.writeWithoutTransaction { db in
}
```
Both ``DatabaseWriter/concurrentRead(_:)`` and ``DatabasePool/asyncConcurrentRead(_:)`` block until they can guarantee their closure argument an isolated access to the database, in the exact state left by the last transaction. It then asynchronously executes this closure.
The ``DatabasePool/asyncConcurrentRead(_:)`` method blocks until it can guarantee its closure argument an isolated access to the database, in the exact state left by the last transaction. It then asynchronously executes the closure.
In the illustration below, the striped band shows the delay needed for the reading thread to acquire isolation. Until then, no other thread can write:
![DatabasePool Concurrent Read](DatabasePoolConcurrentRead.png)
Types that conform to ``TransactionObserver`` can also use those methods in their ``TransactionObserver/databaseDidCommit(_:)`` method, in order to process database changes without blocking other threads that want to write into the database.
+1 -2
View File
@@ -152,12 +152,11 @@ 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)
```
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.
The busy timeout has write transactions wait, instead of throwing `SQLITE_BUSY`, whenever another process is writing. GRDB automatically opens all write transactions with the IMMEDIATE kind, preventing write transactions from overlapping.
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:
@@ -90,7 +90,6 @@ do {
### Configuring GRDB Connections
- ``allowsUnsafeTransactions``
- ``defaultTransactionKind``
- ``label``
- ``maximumReaderCount``
- ``observesSuspensionNotifications``
@@ -260,7 +260,7 @@ When needed, you can help GRDB optimize observations and reduce database content
- ``publisher(in:scheduling:)``
- ``start(in:scheduling:onError:onChange:)``
- ``values(in:scheduling:bufferingPolicy:)``
- ``values(in:bufferingPolicy:)``
- ``DatabaseCancellable``
- ``ValueObservationScheduler``
+2 -17
View File
@@ -214,6 +214,8 @@ SQLite savepoints are more than nested transactions, though. For advanced uses,
SQLite supports [three kinds of transactions](https://www.sqlite.org/lang_transaction.html): deferred (the default), immediate, and exclusive.
By default, GRDB opens DEFERRED transaction for reads, and IMMEDIATE transactions for writes.
The transaction kind can be chosen for individual transaction:
```swift
@@ -222,20 +224,3 @@ let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
// BEGIN EXCLUSIVE TRANSACTION ...
try dbQueue.inTransaction(.exclusive) { db in ... }
```
It is also possible to configure the ``Configuration/defaultTransactionKind``:
```swift
var config = Configuration()
config.defaultTransactionKind = .immediate
let dbQueue = try DatabaseQueue(
path: "/path/to/database.sqlite",
configuration: config)
// BEGIN IMMEDIATE TRANSACTION ...
try dbQueue.write { db in ... }
// BEGIN IMMEDIATE TRANSACTION ...
try dbQueue.inTransaction { db in ... }
```
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A format that prints one line per database row, suitable
+10 -1
View File
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A format that prints database rows as a JSON array.
@@ -43,7 +52,7 @@ public struct JSONDumpFormat: Sendable {
public static var defaultEncoder: JSONEncoder {
// This encoder MUST NOT CHANGE, because some people rely on this format.
let encoder = JSONEncoder()
if #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) {
if #available(iOS 13.0, macOS 10.15, tvOS 13.0, *) {
encoder.outputFormatting = .withoutEscapingSlashes
}
encoder.nonConformingFloatEncodingStrategy = .convertToString(
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A format that prints one line per database value. All blob values
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A format that prints one line per database row. All blob values
@@ -1,3 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A format that prints one line per database row, formatting values
/// as SQL literals.
///
-8
View File
@@ -1,8 +0,0 @@
// Export the underlying SQLite library
#if SWIFT_PACKAGE
@_exported import CSQLite
#elseif GRDBCIPHER
@_exported import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
@_exported import SQLite3
#endif
+1 -1
View File
@@ -47,7 +47,7 @@ public struct FTS3 {
#elseif !GRDBCIPHER
/// Remove diacritics from Latin script characters. This option matches
/// the `remove_diacritics=2` tokenizer argument.
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.27+
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.27+
case remove
#endif
}
+11 -2
View File
@@ -1,4 +1,13 @@
#if SQLITE_ENABLE_FTS5
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// The virtual table module for the FTS5 full-text engine.
@@ -60,7 +69,7 @@ public struct FTS5 {
/// Remove diacritics from Latin script characters. This
/// option matches the raw "remove_diacritics=2" tokenizer argument,
/// available from SQLite 3.27.0
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.27+
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.27+
case remove
#endif
}
@@ -121,7 +130,7 @@ public struct FTS5 {
return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer)
#else
// GRDB is linked against the system SQLite.
if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { // SQLite 3.20+
if #available(macOS 10.14, *) { // SQLite 3.20+
return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer)
} else {
return api_v1(db)
+9
View File
@@ -1,4 +1,13 @@
#if SQLITE_ENABLE_FTS5
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A type that implements a custom tokenizer for the ``FTS5`` full-text engine.
///
/// See [FTS5 Tokenizers](https://github.com/groue/GRDB.swift/blob/master/Documentation/FTS5Tokenizers.md)
+9
View File
@@ -1,4 +1,13 @@
#if SQLITE_ENABLE_FTS5
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A low-level SQLite function that lets FTS5Tokenizer notify tokens.
+9
View File
@@ -1,4 +1,13 @@
#if SQLITE_ENABLE_FTS5
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// Flags that tell SQLite how to register a token.
+3 -3
View File
@@ -119,7 +119,7 @@ extension PersistableRecord {
public func performSave(_ db: Database) throws { preconditionFailure() }
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension QueryInterfaceRequest where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible {
@available(*, unavailable, message: "selectID() has been removed. You may use selectPrimaryKey(as:) instead.")
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID> { preconditionFailure() }
@@ -144,13 +144,13 @@ extension SelectionRequest {
@available(*, unavailable, renamed: "SQLExpression.AssociativeBinaryOperator")
public typealias SQLAssociativeBinaryOperator = SQLExpression.AssociativeBinaryOperator
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible {
@available(*, unavailable, message: "selectID() has been removed. You may use selectPrimaryKey(as:) instead.")
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID> { preconditionFailure() }
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
@available(*, unavailable, message: "selectID() has been removed. You may use selectPrimaryKey(as:) instead.")
public static func selectID() -> QueryInterfaceRequest<ID> { preconditionFailure() }
+5 -5
View File
@@ -40,7 +40,7 @@ import Foundation
/// - ``completedMigrations(_:)``
/// - ``hasBeenSuperseded(_:)``
/// - ``hasCompletedMigrations(_:)``
public struct DatabaseMigrator {
public struct DatabaseMigrator: Sendable {
/// Controls how a migration handle foreign keys constraints.
public enum ForeignKeyChecks: Sendable {
/// The migration runs with disabled foreign keys.
@@ -207,7 +207,7 @@ public struct DatabaseMigrator {
public mutating func registerMigration(
_ identifier: String,
foreignKeyChecks: ForeignKeyChecks = .deferred,
migrate: @escaping (Database) throws -> Void)
migrate: @escaping @Sendable (Database) throws -> Void)
{
let migrationChecks: Migration.ForeignKeyChecks
switch foreignKeyChecks {
@@ -264,7 +264,7 @@ public struct DatabaseMigrator {
/// from succeeding.
public func asyncMigrate(
_ writer: some DatabaseWriter,
completion: @escaping (Result<Database, Error>) -> Void)
completion: @escaping @Sendable (Result<Database, Error>) -> Void)
{
writer.asyncBarrierWriteWithoutTransaction { dbResult in
do {
@@ -496,7 +496,7 @@ extension DatabaseMigrator {
/// - parameter writer: A DatabaseWriter.
/// where migrations should apply.
/// - parameter scheduler: A Combine Scheduler.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func migratePublisher(
_ writer: some DatabaseWriter,
receiveOn scheduler: some Scheduler = DispatchQueue.main)
@@ -514,7 +514,7 @@ extension DatabaseMigrator {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension DatabasePublishers {
/// A publisher that migrates a database.
///
+2 -2
View File
@@ -1,5 +1,5 @@
/// An internal struct that defines a migration.
struct Migration {
struct Migration: Sendable {
enum ForeignKeyChecks {
case deferred
case immediate
@@ -8,7 +8,7 @@ struct Migration {
let identifier: String
var foreignKeyChecks: ForeignKeyChecks
let migrate: (Database) throws -> Void
let migrate: @Sendable (Database) throws -> Void
func run(_ db: Database) throws {
if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false {
@@ -583,7 +583,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension TableRequest
where Self: FilteredRequest,
Self: TypedRequest,
@@ -23,7 +23,7 @@
/// see SQLRelation.filterPromise.
struct DatabasePromise<T> {
/// Returns the resolved value.
let resolve: (Database) throws -> T
let resolve: @Sendable (Database) throws -> T
/// Creates a promise that resolves to a value.
init(value: T) {
@@ -31,12 +31,12 @@ struct DatabasePromise<T> {
}
/// Creates a promise from a closure.
init(_ resolve: @escaping (Database) throws -> T) {
init(_ resolve: @escaping @Sendable (Database) throws -> T) {
self.resolve = resolve
}
/// Returns a promise whose value is transformed by the given closure.
func map<U>(_ transform: @escaping (T) throws -> U) -> DatabasePromise<U> {
func map<U>(_ transform: @escaping @Sendable (T) throws -> U) -> DatabasePromise<U> {
DatabasePromise<U> { db in
try transform(resolve(db))
}
+4 -4
View File
@@ -34,7 +34,7 @@
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_expr.html>
public struct SQLExpression {
public struct SQLExpression: Sendable {
private var impl: Impl
/// The preferred interpretation of the expression in JSON
@@ -1989,7 +1989,7 @@ struct SQLAggregateFunctionInvocation {
var arguments: [SQLExpression]
var isDistinct = false
var ordering: SQLOrdering? = nil // SQLite 3.44.0+
var filter: SQLExpression? = nil // @available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) SQLite 3.30+
var filter: SQLExpression? = nil // @available(iOS 14, macOS 10.16, tvOS 14, *) SQLite 3.30+
/// A boolean value indicating if a function is known to return a
/// JSON value.
@@ -2328,13 +2328,13 @@ extension SQLSpecificExpressible {
}
#elseif !GRDBCIPHER
/// An ordering term for ascending order (nulls last).
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+
public var ascNullsLast: SQLOrdering {
.ascNullsLast(sqlExpression)
}
/// An ordering term for descending order (nulls first).
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+
public var descNullsFirst: SQLOrdering {
.descNullsFirst(sqlExpression)
}
+5 -5
View File
@@ -34,7 +34,7 @@ public func average(
/// // AVG(length) FILTER (WHERE length > 0)
/// average(Column("length"), filter: Column("length") > 0)
/// ```
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+
public func average(
_ value: some SQLSpecificExpressible,
filter: some SQLSpecificExpressible)
@@ -145,7 +145,7 @@ public func max(
/// // MAX(score) FILTER (WHERE score < 0)
/// max(Column("score"), filter: Column("score") < 0)
/// ```
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+
public func max(
_ value: some SQLSpecificExpressible,
filter: some SQLSpecificExpressible)
@@ -190,7 +190,7 @@ public func min(
/// // MIN(score) FILTER (WHERE score > 0)
/// min(Column("score"), filter: Column("score") > 0)
/// ```
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+
public func min(
_ value: some SQLSpecificExpressible,
filter: some SQLSpecificExpressible)
@@ -248,7 +248,7 @@ public func sum(
/// See also ``total(_:)``.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+
public func sum(
_ value: some SQLSpecificExpressible,
filter: some SQLSpecificExpressible)
@@ -312,7 +312,7 @@ public func total(
/// See also ``total(_:)``.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+
public func total(
_ value: some SQLSpecificExpressible,
filter: some SQLSpecificExpressible)
+1 -1
View File
@@ -12,7 +12,7 @@
/// function arguments, prefer the ``SQLOrderingTerm`` protocol.
///
/// Related SQLite documentation: <https://www.sqlite.org/syntax/ordering-term.html>
public struct SQLOrdering {
public struct SQLOrdering: Sendable {
private var impl: Impl
private enum Impl {
+11 -11
View File
@@ -90,7 +90,7 @@
/// // JOIN passport ON passport.citizenId = citizens.id
/// // AND passport.countryCode IN ('BE', 'DE', 'FR', ...);
/// Country.including(all: Country.citizens)
struct SQLRelation {
struct SQLRelation: Sendable {
struct Child: Refinable {
enum Kind {
// Record.including(optional: association)
@@ -187,7 +187,7 @@ extension SQLRelation {
/// Convenience factory methods which selects all rows from a table.
static func all(
fromTable tableName: String,
selection: @escaping (Database) -> [SQLSelection] = { _ in [.allColumns] })
selection: @escaping @Sendable (Database) -> [SQLSelection] = { _ in [.allColumns] })
-> Self
{
SQLRelation(
@@ -197,7 +197,7 @@ extension SQLRelation {
}
extension SQLRelation: Refinable {
func selectWhenConnected(_ selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
func selectWhenConnected(_ selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self {
with {
$0.selectionPromise = DatabasePromise(selection)
}
@@ -228,7 +228,7 @@ extension SQLRelation: Refinable {
}
}
func annotatedWhenConnected(with selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
func annotatedWhenConnected(with selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self {
with {
let old = $0.selectionPromise
$0.selectionPromise = DatabasePromise { db in
@@ -242,7 +242,7 @@ extension SQLRelation: Refinable {
annotatedWhenConnected(with: { _ in selection })
}
func filterWhenConnected(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
func filterWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self {
with {
if let old = $0.filterPromise {
$0.filterPromise = DatabasePromise { db in
@@ -259,7 +259,7 @@ extension SQLRelation: Refinable {
filterWhenConnected { _ in predicate }
}
func orderWhenConnected(_ orderings: @escaping (Database) throws -> [SQLOrdering]) -> Self {
func orderWhenConnected(_ orderings: @escaping @Sendable (Database) throws -> [SQLOrdering]) -> Self {
with {
$0.ordering = SQLRelation.Ordering(orderings: orderings)
}
@@ -313,13 +313,13 @@ extension SQLRelation: Refinable {
}
}
func groupWhenConnected(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self {
func groupWhenConnected(_ expressions: @escaping @Sendable (Database) throws -> [SQLExpression]) -> Self {
with {
$0.groupPromise = DatabasePromise(expressions)
}
}
func havingWhenConnected(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
func havingWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self {
with {
if let old = $0.havingExpressionPromise {
$0.havingExpressionPromise = DatabasePromise { db in
@@ -672,7 +672,7 @@ struct SQLLimit {
// MARK: - SQLSource
struct SQLSource {
struct SQLSource: Sendable {
var tableName: String
var alias: TableAlias?
@@ -691,7 +691,7 @@ struct SQLSource {
extension SQLRelation {
/// SQLRelation.Ordering provides the order clause to SQLRelation.
struct Ordering {
struct Ordering: Sendable {
private enum Element {
case terms(DatabasePromise<[SQLOrdering]>)
case ordering(SQLRelation.Ordering)
@@ -740,7 +740,7 @@ extension SQLRelation {
isReversed: false)
}
init(orderings: @escaping (Database) throws -> [SQLOrdering]) {
init(orderings: @escaping @Sendable (Database) throws -> [SQLOrdering]) {
self.init(
elements: [.terms(DatabasePromise(orderings))],
isReversed: false)
+1 -1
View File
@@ -15,7 +15,7 @@
/// function arguments, prefer the ``SQLSelectable`` protocol.
///
/// Related SQLite documentation: <https://www.sqlite.org/syntax/result-column.html>
public struct SQLSelection {
public struct SQLSelection: Sendable {
private var impl: Impl
/// The private implementation of the public `SQLSelection`.
+1 -1
View File
@@ -1,7 +1,7 @@
/// An SQL subquery.
///
/// `SQLSubquery` is an opaque representation of an SQL subquery.
public struct SQLSubquery {
public struct SQLSubquery: Sendable {
private var impl: Impl
private enum Impl {
+3 -3
View File
@@ -723,7 +723,7 @@ extension Table {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible {
/// Returns a request filtered by primary key.
///
@@ -1546,7 +1546,7 @@ extension Table {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension Table
where RowDecoder: Identifiable,
RowDecoder.ID: DatabaseValueConvertible
@@ -1688,7 +1688,7 @@ extension Table {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension Table
where RowDecoder: Identifiable,
RowDecoder.ID: DatabaseValueConvertible
@@ -213,7 +213,9 @@ class StatementArgumentsSink {
/// See ``TableRequest/aliased(_:)`` for more information and examples.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
public class TableAlias {
public class TableAlias: @unchecked Sendable {
// This Sendable conformance is transient. TableAlias IS NOT really Sendable.
// TODO: GRDB7 Make TableAlias really Sendable
private enum Impl {
/// A TableAlias is undefined when it is created by the GRDB user:
///
@@ -129,7 +129,7 @@ public final class TableAlteration {
///
/// - parameter name: the old name of the column.
/// - parameter newName: the new name of the column.
@available(iOS 13, tvOS 13, watchOS 6, *) // SQLite 3.25+
@available(iOS 13, tvOS 13, *) // SQLite 3.25+
public func rename(column name: String, to newName: String) {
_rename(column: name, to: newName)
}
@@ -605,7 +605,7 @@ extension TableRecord {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
/// Returns a request filtered by primary key.
///
+7 -7
View File
@@ -466,7 +466,7 @@ extension Row {
/// var jsonData: Data
/// }
/// ```
public enum DatabaseDataEncodingStrategy {
public enum DatabaseDataEncodingStrategy: Sendable {
/// Encodes `Data` columns as SQL blob.
case deferredToData
@@ -474,7 +474,7 @@ public enum DatabaseDataEncodingStrategy {
case text
/// Encodes `Data` column as the result of the user-provided function.
case custom((Data) -> (any DatabaseValueConvertible)?)
case custom(@Sendable (Data) -> (any DatabaseValueConvertible)?)
func encode(_ data: Data) -> DatabaseValue {
switch self {
@@ -508,7 +508,7 @@ public enum DatabaseDataEncodingStrategy {
/// var creationDate: Date
/// }
/// ```
public enum DatabaseDateEncodingStrategy {
public enum DatabaseDateEncodingStrategy: Sendable {
/// The strategy that uses formatting from the Date structure.
///
/// It encodes dates using the format "YYYY-MM-DD HH:MM:SS.SSS" in the
@@ -538,7 +538,7 @@ public enum DatabaseDateEncodingStrategy {
case formatted(DateFormatter)
/// Encodes the result of the user-provided function
case custom((Date) -> (any DatabaseValueConvertible)?)
case custom(@Sendable (Date) -> (any DatabaseValueConvertible)?)
private static let iso8601Formatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
@@ -585,7 +585,7 @@ public enum DatabaseDateEncodingStrategy {
/// var uuid: UUID
/// }
/// ```
public enum DatabaseUUIDEncodingStrategy {
public enum DatabaseUUIDEncodingStrategy: Sendable {
/// The strategy that uses formatting from the UUID type.
///
/// It encodes UUIDs as 16-bytes data blobs.
@@ -626,7 +626,7 @@ public enum DatabaseUUIDEncodingStrategy {
/// var playerID: String
/// }
/// ```
public enum DatabaseColumnEncodingStrategy {
public enum DatabaseColumnEncodingStrategy: Sendable {
/// A key encoding strategy that doesn’t change key names during encoding.
case useDefaultKeys
@@ -634,7 +634,7 @@ public enum DatabaseColumnEncodingStrategy {
case convertToSnakeCase
/// A key encoding strategy defined by the closure you supply.
case custom((any CodingKey) -> String)
case custom(@Sendable (any CodingKey) -> String)
func column(forKey key: some CodingKey) -> String {
switch self {
+84 -189
View File
@@ -1,8 +1,17 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
extension FetchableRecord where Self: Decodable {
/// Creates a record from `row`, using the `Decodable` conformance.
public init(row: Row) throws {
public init(row: some RowProtocol) throws {
self = try FetchableRecordDecoder().decode(Self.self, from: row)
}
}
@@ -69,17 +78,26 @@ public class FetchableRecordDecoder {
/// - row: The database row to decode.
/// - Returns: An instance of the specified record type, if the decoder
/// can parse the database row.
public func decode<T: FetchableRecord & Decodable>(_ type: T.Type, from row: Row) throws -> T {
let decoder = _RowDecoder<T>(row: row, codingPath: [], columnDecodingStrategy: T.databaseColumnDecodingStrategy)
public func decode<RowType: RowProtocol, T: FetchableRecord & Decodable>(_ type: T.Type, from row: RowType) throws -> T {
let decoder = _RowDecoder<RowType, T>(row: row, codingPath: [], columnDecodingStrategy: T.databaseColumnDecodingStrategy)
return try T(from: decoder)
}
}
#warning("TODO: fetch if correct")
private struct NestedDecodingContext<R: FetchableRecord>: FetchableRecord {
init(row: some RowProtocol) throws { preconditionFailure() }
static var databaseColumnDecodingStrategy: DatabaseColumnDecodingStrategy { R.databaseColumnDecodingStrategy }
static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] { R.databaseDecodingUserInfo }
static var databaseDataDecodingStrategy: DatabaseDataDecodingStrategy { R.databaseDataDecodingStrategy }
static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { R.databaseDateDecodingStrategy }
}
// MARK: - _RowDecoder
/// The decoder that decodes a record from a database row
private struct _RowDecoder<R: FetchableRecord>: Decoder {
var row: Row
private struct _RowDecoder<RowType: RowProtocol, R: FetchableRecord>: Decoder {
var row: RowType
var codingPath: [CodingKey]
var columnDecodingStrategy: DatabaseColumnDecodingStrategy
var userInfo: [CodingUserInfoKey: Any] { R.databaseDecodingUserInfo }
@@ -109,17 +127,17 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
func singleValueContainer() throws -> SingleValueDecodingContainer {
guard let key = codingPath.last else {
// Decoding an array of scalars from rows: pick the first column
return ColumnDecoder<R>(row: row, columnIndex: 0, codingPath: codingPath)
return ColumnDecoder<RowType, R>(row: row, columnIndex: 0, codingPath: codingPath)
}
guard let index = row.index(forColumn: key.stringValue) else {
// Don't use DecodingError.keyNotFound:
// We need to specifically recognize missing columns in order to
// provide correct feedback.
throw RowDecodingError.columnNotFound(key.stringValue, context: RowDecodingContext(row: row))
throw RowDecodingError.columnNotFound(key.stringValue, context: row._makeRowDecodingContext(forKey: nil))
}
// TODO: test
// See DatabaseValueConversionErrorTests.testDecodableFetchableRecord2
return ColumnDecoder<R>(row: row, columnIndex: index, codingPath: codingPath)
return ColumnDecoder<RowType, R>(row: row, columnIndex: index, codingPath: codingPath)
}
class KeyedContainer<Key: CodingKey>: KeyedDecodingContainerProtocol {
@@ -239,12 +257,12 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
}
// TODO: this is not quite correct: key IS NOT a column name.
// So we shouldn't use RowKey.columnName. Yet this only impacts
// So we shouldn't use _RowKey.columnName. Yet this only impacts
// internal types, so the damage is limited.
throw RowDecodingError.keyNotFound(
.columnName(key.stringValue), // <- See above TODO
RowDecodingError.Context(
decodingContext: RowDecodingContext(row: decoder.row),
decodingContext: decoder.row._makeRowDecodingContext(forKey: nil),
debugDescription: "key not found: \(errorDescription)"))
}
@@ -261,18 +279,18 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
if type == Data.self {
return try R.databaseDataDecodingStrategy.decodeIfPresent(
fromRow: row,
return try row._decodeIfPresent(
with: R.databaseDataDecodingStrategy,
atUncheckedIndex: index) as! T?
} else if type == Date.self {
return try R.databaseDateDecodingStrategy.decodeIfPresent(
fromRow: row,
return try row._decodeIfPresent(
with: R.databaseDateDecodingStrategy,
atUncheckedIndex: index) as! T?
} else if let type = T.self as? any (DatabaseValueConvertible & StatementColumnConvertible).Type {
return try type.fastDecodeIfPresent(fromRow: row, atUncheckedIndex: index) as! T?
return try row._fastDecodeIfPresent(type, atUncheckedIndex: index) as! T?
} else if let type = T.self as? any DatabaseValueConvertible.Type {
return try type.decodeIfPresent(fromRow: row, atUncheckedIndex: index) as! T?
} else if row.impl.hasNull(atUncheckedIndex: index) {
return try row._decodeIfPresent(type, atUncheckedIndex: index) as! T?
} else if row._hasNull(atUncheckedIndex: index) {
return nil
} else {
return try decode(type, fromRow: row, columnAtIndex: index, key: key)
@@ -310,13 +328,13 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
if type == Data.self {
return try R.databaseDataDecodingStrategy.decode(fromRow: row, atUncheckedIndex: index) as! T
return try row._decode(with: R.databaseDataDecodingStrategy, atUncheckedIndex: index) as! T
} else if type == Date.self {
return try R.databaseDateDecodingStrategy.decode(fromRow: row, atUncheckedIndex: index) as! T
return try row._decode(with: R.databaseDateDecodingStrategy, atUncheckedIndex: index) as! T
} else if let type = T.self as? any (DatabaseValueConvertible & StatementColumnConvertible).Type {
return try type.fastDecode(fromRow: row, atUncheckedIndex: index) as! T
return try row._fastDecode(type, atUncheckedIndex: index) as! T
} else if let type = T.self as? any DatabaseValueConvertible.Type {
return try type.decode(fromRow: row, atUncheckedIndex: index) as! T
return try row._decode(type, atUncheckedIndex: index) as! T
} else {
return try decode(type, fromRow: row, columnAtIndex: index, key: key)
}
@@ -395,9 +413,10 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
// Helper methods
private func decode<T>(
#warning("TODO: make NestedRowType concrete once it is settled")
private func decode<NestedRowType: RowProtocol, T>(
_ type: T.Type,
fromRow row: Row,
fromRow row: NestedRowType,
codingPath: [CodingKey])
throws -> T
where T: Decodable
@@ -406,14 +425,14 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
// Prefer FetchableRecord decoding over Decodable.
return try type.init(row: row) as! T
} else {
let decoder = _RowDecoder(row: row, codingPath: codingPath, columnDecodingStrategy: .useDefaultKeys)
let decoder = _RowDecoder<NestedRowType, NestedDecodingContext<R>>(row: row, codingPath: codingPath, columnDecodingStrategy: .useDefaultKeys)
return try T(from: decoder)
}
}
private func decode<T>(
_ type: T.Type,
fromRow row: Row,
fromRow row: RowType,
columnAtIndex index: Int,
key: Key)
throws -> T
@@ -424,7 +443,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
// or unkeyed containers, because we're decoding a single
// value here (string, int, double, data, null). If such an
// error happens, we'll switch to JSON decoding.
let columnDecoder = ColumnDecoder<R>(
let columnDecoder = ColumnDecoder<RowType, R>(
row: row,
columnIndex: index,
codingPath: codingPath + [key])
@@ -488,7 +507,7 @@ extension PrefetchedRowsDecoder: UnkeyedDecodingContainer {
columnDecodingStrategy = .useDefaultKeys
}
let decoder = _RowDecoder<R>(
let decoder = _RowDecoder<Row, R>(
row: rows[currentIndex],
codingPath: codingPath,
columnDecodingStrategy: columnDecodingStrategy)
@@ -514,8 +533,8 @@ extension PrefetchedRowsDecoder: UnkeyedDecodingContainer {
// MARK: - ColumnDecoder
/// The decoder that decodes from a database column
private struct ColumnDecoder<R: FetchableRecord>: Decoder {
var row: Row
private struct ColumnDecoder<RowType: RowProtocol, R: FetchableRecord>: Decoder {
var row: RowType
var columnIndex: Int
var codingPath: [CodingKey]
var userInfo: [CodingUserInfoKey: Any] { R.databaseDecodingUserInfo }
@@ -556,13 +575,13 @@ extension ColumnDecoder: SingleValueDecodingContainer {
func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
// TODO: not tested
if type == Data.self {
return try R.databaseDataDecodingStrategy.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T
return try row._decode(with: R.databaseDataDecodingStrategy, atUncheckedIndex: columnIndex) as! T
} else if type == Date.self {
return try R.databaseDateDecodingStrategy.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T
return try row._decode(with: R.databaseDateDecodingStrategy, atUncheckedIndex: columnIndex) as! T
} else if let type = T.self as? any (DatabaseValueConvertible & StatementColumnConvertible).Type {
return try type.fastDecode(fromRow: row, atUncheckedIndex: columnIndex) as! T
return try row._fastDecode(type, atUncheckedIndex: columnIndex) as! T
} else if let type = T.self as? any DatabaseValueConvertible.Type {
return try type.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T
return try row._decode(type, atUncheckedIndex: columnIndex) as! T
} else {
return try T(from: self)
}
@@ -575,50 +594,12 @@ private let iso8601Formatter: ISO8601DateFormatter = {
return formatter
}()
extension DatabaseDataDecodingStrategy {
fileprivate func decodeIfPresent(fromRow row: Row, atUncheckedIndex index: Int) throws -> Data? {
if let sqliteStatement = row.sqliteStatement {
return try decodeIfPresent(
fromStatement: sqliteStatement,
atUncheckedIndex: CInt(index),
context: RowDecodingContext(row: row, key: .columnIndex(index)))
} else {
return try decodeIfPresent(
fromDatabaseValue: row[index],
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
}
fileprivate func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Data {
if let sqliteStatement = row.sqliteStatement {
let statementIndex = CInt(index)
if sqlite3_column_type(sqliteStatement, statementIndex) == SQLITE_NULL {
throw RowDecodingError.valueMismatch(
Data.self,
sqliteStatement: sqliteStatement,
index: statementIndex,
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
return try decode(
fromStatement: sqliteStatement,
atUncheckedIndex: statementIndex,
context: RowDecodingContext(row: row, key: .columnIndex(index)))
} else {
return try decode(
fromDatabaseValue: row[index],
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
}
/// - precondition: value is not NULL
fileprivate func decode(
fromStatement sqliteStatement: SQLiteStatement,
extension DatabaseDataDecodingStrategy: _RowDecodingStrategy {
public func _decode(
sqliteStatement: SQLiteStatement,
atUncheckedIndex index: CInt,
context: @autoclosure () -> RowDecodingContext)
throws -> Data
{
context: @autoclosure () -> _RowDecodingContext
) throws -> Data {
assert(sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL, "unexpected NULL value")
switch self {
case .deferredToData:
@@ -635,46 +616,22 @@ extension DatabaseDataDecodingStrategy {
}
}
fileprivate func decodeIfPresent(
fromStatement sqliteStatement: SQLiteStatement,
atUncheckedIndex index: CInt,
context: @autoclosure () -> RowDecodingContext)
throws -> Data?
{
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
return nil
}
return try decode(fromStatement: sqliteStatement, atUncheckedIndex: index, context: context())
}
fileprivate func decode(
fromDatabaseValue dbValue: DatabaseValue,
context: @autoclosure () -> RowDecodingContext)
throws -> Data
{
if let data = dataFromDatabaseValue(dbValue) {
public func _decode(
databaseValue: DatabaseValue,
context: @autoclosure () -> _RowDecodingContext
) throws -> Data {
if let data = decode(databaseValue) {
return data
} else {
throw RowDecodingError.valueMismatch(Data.self, context: context(), databaseValue: dbValue)
throw RowDecodingError.valueMismatch(
Data.self,
context: context(),
databaseValue: databaseValue)
}
}
fileprivate func decodeIfPresent(
fromDatabaseValue dbValue: DatabaseValue,
context: @autoclosure () -> RowDecodingContext)
throws -> Data?
{
if dbValue.isNull {
return nil
} else if let data = dataFromDatabaseValue(dbValue) {
return data
} else {
throw RowDecodingError.valueMismatch(Data.self, context: context(), databaseValue: dbValue)
}
}
// Returns nil if decoding fails
private func dataFromDatabaseValue(_ dbValue: DatabaseValue) -> Data? {
/// Returns nil if decoding fails
private func decode(_ dbValue: DatabaseValue) -> Data? {
switch self {
case .deferredToData:
return Data.fromDatabaseValue(dbValue)
@@ -684,50 +641,12 @@ extension DatabaseDataDecodingStrategy {
}
}
extension DatabaseDateDecodingStrategy {
fileprivate func decodeIfPresent(fromRow row: Row, atUncheckedIndex index: Int) throws -> Date? {
if let sqliteStatement = row.sqliteStatement {
return try decodeIfPresent(
fromStatement: sqliteStatement,
atUncheckedIndex: CInt(index),
context: RowDecodingContext(row: row, key: .columnIndex(index)))
} else {
return try decodeIfPresent(
fromDatabaseValue: row[index],
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
}
fileprivate func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Date {
if let sqliteStatement = row.sqliteStatement {
let statementIndex = CInt(index)
if sqlite3_column_type(sqliteStatement, statementIndex) == SQLITE_NULL {
throw RowDecodingError.valueMismatch(
Date.self,
sqliteStatement: sqliteStatement,
index: statementIndex,
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
return try decode(
fromStatement: sqliteStatement,
atUncheckedIndex: CInt(index),
context: RowDecodingContext(row: row, key: .columnIndex(index)))
} else {
return try decode(
fromDatabaseValue: row[index],
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
}
/// - precondition: value is not NULL
fileprivate func decode(
fromStatement sqliteStatement: SQLiteStatement,
extension DatabaseDateDecodingStrategy: _RowDecodingStrategy {
public func _decode(
sqliteStatement: SQLiteStatement,
atUncheckedIndex index: CInt,
context: @autoclosure () -> RowDecodingContext)
throws -> Date
{
context: @autoclosure () -> _RowDecodingContext
) throws -> Date {
assert(sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL, "unexpected NULL value")
switch self {
case .deferredToDate:
@@ -777,46 +696,22 @@ extension DatabaseDateDecodingStrategy {
}
}
fileprivate func decodeIfPresent(
fromStatement sqliteStatement: SQLiteStatement,
atUncheckedIndex index: CInt,
context: @autoclosure () -> RowDecodingContext)
throws -> Date?
{
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
return nil
}
return try decode(fromStatement: sqliteStatement, atUncheckedIndex: index, context: context())
}
fileprivate func decode(
fromDatabaseValue dbValue: DatabaseValue,
context: @autoclosure () -> RowDecodingContext)
throws -> Date
{
if let date = dateFromDatabaseValue(dbValue) {
public func _decode(
databaseValue: DatabaseValue,
context: @autoclosure () -> _RowDecodingContext
) throws -> Date {
if let date = decode(databaseValue) {
return date
} else {
throw RowDecodingError.valueMismatch(Date.self, context: context(), databaseValue: dbValue)
throw RowDecodingError.valueMismatch(
Date.self,
context: context(),
databaseValue: databaseValue)
}
}
fileprivate func decodeIfPresent(
fromDatabaseValue dbValue: DatabaseValue,
context: @autoclosure () -> RowDecodingContext)
throws -> Date?
{
if dbValue.isNull {
return nil
} else if let date = dateFromDatabaseValue(dbValue) {
return date
} else {
throw RowDecodingError.valueMismatch(Date.self, context: context(), databaseValue: dbValue)
}
}
// Returns nil if decoding fails
private func dateFromDatabaseValue(_ dbValue: DatabaseValue) -> Date? {
/// Returns nil if decoding fails
private func decode(_ dbValue: DatabaseValue) -> Date? {
switch self {
case .deferredToDate:
return Date.fromDatabaseValue(dbValue)
@@ -217,7 +217,7 @@ extension FetchableRecord where Self: TableRecord {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseValueConvertible {
// MARK: Fetching by Single-Column Primary Key
@@ -359,7 +359,7 @@ extension FetchableRecord where Self: TableRecord & Hashable {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension FetchableRecord where Self: TableRecord & Hashable & Identifiable, ID: DatabaseValueConvertible {
/// Returns a set of records identified by their primary keys.
///
+14 -7
View File
@@ -113,7 +113,7 @@ public protocol FetchableRecord {
///
/// - throws: An error is thrown if the record can't be decoded from the
/// database row.
init(row: Row) throws
init(row: some RowProtocol) throws
// MARK: - Customizing the Format of Database Columns
@@ -260,6 +260,13 @@ extension FetchableRecord {
}
}
extension FetchableRecord {
#warning("TODO: document")
public init(row columnsWithValues: KeyValuePairs<String, (any DatabaseValueConvertible)?>) throws {
try self.init(row: Row(columnsWithValues: columnsWithValues))
}
}
extension FetchableRecord {
// MARK: Fetching From Prepared Statement
@@ -880,7 +887,7 @@ extension RecordCursor: Sendable { }
/// var myData: Data
/// }
/// ```
public enum DatabaseDataDecodingStrategy {
public enum DatabaseDataDecodingStrategy: Sendable {
/// Decodes `Data` columns from SQL blobs and UTF8 text.
case deferredToData
@@ -889,7 +896,7 @@ public enum DatabaseDataDecodingStrategy {
/// If the database value does not contain a suitable value, the function
/// must return nil (GRDB will interpret this nil result as a conversion
/// error, and react accordingly).
case custom((DatabaseValue) -> Data?)
case custom(@Sendable (DatabaseValue) -> Data?)
}
// MARK: - DatabaseDateDecodingStrategy
@@ -906,7 +913,7 @@ public enum DatabaseDataDecodingStrategy {
/// var name: String
/// var registrationDate: Date // decoded from epoch timestamp
/// }
public enum DatabaseDateDecodingStrategy {
public enum DatabaseDateDecodingStrategy: Sendable {
/// The strategy that uses formatting from the Date structure.
///
/// It decodes numeric values as a number of seconds since Epoch
@@ -947,7 +954,7 @@ public enum DatabaseDateDecodingStrategy {
/// If the database value does not contain a suitable value, the function
/// must return nil (GRDB will interpret this nil result as a conversion
/// error, and react accordingly).
case custom((DatabaseValue) -> Date?)
case custom(@Sendable (DatabaseValue) -> Date?)
}
// MARK: - DatabaseColumnDecodingStrategy
@@ -964,7 +971,7 @@ public enum DatabaseDateDecodingStrategy {
/// // Decoded from the player_id column
/// var playerID: Int
/// }
public enum DatabaseColumnDecodingStrategy {
public enum DatabaseColumnDecodingStrategy: Sendable {
/// A key decoding strategy that doesn’t change key names during decoding.
case useDefaultKeys
@@ -972,7 +979,7 @@ public enum DatabaseColumnDecodingStrategy {
case convertFromSnakeCase
/// A key decoding strategy defined by the closure you supply.
case custom((String) -> CodingKey)
case custom(@Sendable (String) -> CodingKey)
func key<K: CodingKey>(forColumn column: String) -> K? {
switch self {
@@ -91,7 +91,6 @@ extension MutablePersistableRecord {
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
@@ -108,22 +107,22 @@ extension MutablePersistableRecord {
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The inserted record, if any. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - returns: The inserted record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the insertion failed due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
public func insertAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self?
throws -> Self
where Self: FetchableRecord
{
var result = self
return try result.insertAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
@@ -161,11 +160,10 @@ extension MutablePersistableRecord {
/// var partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING *
/// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) {
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self)
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// ```
///
@@ -174,19 +172,24 @@ extension MutablePersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`, if any. The result can be
/// nil when the conflict policy is `IGNORE`.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the insertion failed due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
public mutating func insertAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
throws -> T
{
try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
try T.fetchOne($0)
let record = self
return try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
if let result = try T.fetchOne($0) {
return result
}
throw record.recordNotFound(db)
}
}
@@ -266,7 +269,6 @@ extension MutablePersistableRecord {
return success.returned
}
#else
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
@@ -283,23 +285,23 @@ extension MutablePersistableRecord {
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The inserted record, if any. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - returns: The inserted record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the insertion failed due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func insertAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self?
throws -> Self
where Self: FetchableRecord
{
var result = self
return try result.insertAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
@@ -337,11 +339,10 @@ extension MutablePersistableRecord {
/// var partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING *
/// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) {
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self)
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// ```
///
@@ -350,20 +351,25 @@ extension MutablePersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`, if any. The result can be
/// nil when the conflict policy is `IGNORE`.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the insertion failed due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public mutating func insertAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
throws -> T
{
try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
try T.fetchOne($0)
let record = self
return try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
if let result = try T.fetchOne($0) {
return result
}
throw record.recordNotFound(db)
}
}
+28 -20
View File
@@ -87,7 +87,6 @@ extension MutablePersistableRecord {
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
@@ -107,22 +106,22 @@ extension MutablePersistableRecord {
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The saved record. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - returns: The saved record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the database changes fail due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
public func saveAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self?
throws -> Self
where Self: FetchableRecord
{
var result = self
return try result.saveAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
@@ -135,26 +134,31 @@ extension MutablePersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the database changes fail due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
public mutating func saveAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
throws -> T
{
try willSave(db)
var success: (saved: PersistenceSuccess, returned: T?)?
var success: (saved: PersistenceSuccess, returned: T)?
try aroundSave(db) {
let record = self
success = try updateOrInsertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: T.databaseSelection,
fetch: {
try T.fetchOne($0)
if let result = try T.fetchOne($0) {
return result
}
throw record.recordNotFound(db)
})
return success!.saved
}
@@ -211,7 +215,6 @@ extension MutablePersistableRecord {
return success.returned
}
#else
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
@@ -231,23 +234,23 @@ extension MutablePersistableRecord {
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The saved record. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - returns: The saved record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the database changes fail due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func saveAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self?
throws -> Self
where Self: FetchableRecord
{
var result = self
return try result.saveAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
@@ -260,27 +263,32 @@ extension MutablePersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the database changes fail due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public mutating func saveAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
throws -> T
{
try willSave(db)
var success: (saved: PersistenceSuccess, returned: T?)?
var success: (saved: PersistenceSuccess, returned: T)?
try aroundSave(db) {
let record = self
success = try updateOrInsertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: T.databaseSelection,
fetch: {
try T.fetchOne($0)
if let result = try T.fetchOne($0) {
return result
}
throw record.recordNotFound(db)
})
return success!.saved
}
@@ -218,7 +218,6 @@ extension MutablePersistableRecord {
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// TODO: GRDB7 make it unable to return an optional
/// Executes an `UPDATE RETURNING` statement on all columns, and returns a
/// new record built from the updated row.
///
@@ -226,23 +225,23 @@ extension MutablePersistableRecord {
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The updated record. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - returns: The updated record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the update fails due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
public func updateAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self?
throws -> Self
where Self: FetchableRecord
{
try updateAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
// TODO: GRDB7 make it unable to return an optional
/// Executes an `UPDATE RETURNING` statement on all columns, and returns a
/// new record built from the updated row.
///
@@ -251,25 +250,28 @@ extension MutablePersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the update fails due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
public func updateAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
throws -> T
{
try updateAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
try T.fetchOne($0)
if let result = try T.fetchOne($0) {
return result
}
throw recordNotFound(db)
}
}
// TODO: GRDB7 make it unable to return an optional
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE RETURNING` statement that updates the modified
/// columns, if and only if the record was modified. The method returns a
@@ -280,12 +282,13 @@ extension MutablePersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter modify: A closure that modifies the record.
/// - returns: An updated record, or nil if the record has no change, or
/// in case of a failed update due to the `IGNORE` conflict policy.
/// - returns: An updated record, or nil if the record has no change.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the update fails due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
public mutating func updateChangesAndFetch(
_ db: Database,
@@ -297,7 +300,6 @@ extension MutablePersistableRecord {
try updateChangesAndFetch(db, onConflict: conflictResolution, as: Self.self, modify: modify)
}
// TODO: GRDB7 make it unable to return an optional
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE RETURNING` statement that updates the modified
/// columns, if and only if the record was modified. The method returns a
@@ -310,12 +312,13 @@ extension MutablePersistableRecord {
/// - parameter returnedType: The type of the returned record.
/// - parameter modify: A closure that modifies the record.
/// - returns: A record of type `returnedType`, or nil if the record has
/// no change, or in case of a failed update due to the `IGNORE`
/// conflict policy.
/// no change.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the update fails due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
public mutating func updateChangesAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
@@ -324,10 +327,16 @@ extension MutablePersistableRecord {
modify: (inout Self) throws -> Void)
throws -> T?
{
try updateChangesAndFetch(
let record = self
return try updateChangesAndFetch(
db, onConflict: conflictResolution,
selection: T.databaseSelection,
fetch: { try T.fetchOne($0) },
fetch: {
if let result = try T.fetchOne($0) {
return result
}
throw record.recordNotFound(db)
},
modify: modify)
}
@@ -482,7 +491,6 @@ extension MutablePersistableRecord {
fetch: fetch)
}
// TODO: GRDB7 make it unable to return an optional
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE RETURNING` statement that updates the modified
/// columns, if and only if the record was modified. The method returns a
@@ -495,7 +503,8 @@ extension MutablePersistableRecord {
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes it ``Statement`` argument.
/// - parameter modify: A closure that modifies the record.
/// - returns: The result of the `fetch` function.
/// - returns: The result of the `fetch` function, or nil if the record
/// has no change.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
@@ -506,7 +515,7 @@ extension MutablePersistableRecord {
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T?,
fetch: (Statement) throws -> T,
modify: (inout Self) throws -> Void)
throws -> T?
{
@@ -519,7 +528,6 @@ extension MutablePersistableRecord {
fetch: fetch)
}
#else
// TODO: GRDB7 make it unable to return an optional
/// Executes an `UPDATE RETURNING` statement on all columns, and returns a
/// new record built from the updated row.
///
@@ -527,18 +535,19 @@ extension MutablePersistableRecord {
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The updated record. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - returns: The updated record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the update fails due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self?
throws -> Self
where Self: FetchableRecord
{
try updateAndFetch(db, onConflict: conflictResolution, as: Self.self)
@@ -552,26 +561,29 @@ extension MutablePersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the update fails due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
throws -> T
{
try updateAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
try T.fetchOne($0)
if let result = try T.fetchOne($0) {
return result
}
throw recordNotFound(db)
}
}
// TODO: GRDB7 make it unable to return an optional
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE RETURNING` statement that updates the modified
/// columns, if and only if the record was modified. The method returns a
@@ -582,12 +594,13 @@ extension MutablePersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter modify: A closure that modifies the record.
/// - returns: An updated record, or nil if the record has no change, or
/// in case of a failed update due to the `IGNORE` conflict policy.
/// - returns: An updated record, or nil if the record has no change.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the update fails due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public mutating func updateChangesAndFetch(
@@ -600,7 +613,6 @@ extension MutablePersistableRecord {
try updateChangesAndFetch(db, onConflict: conflictResolution, as: Self.self, modify: modify)
}
// TODO: GRDB7 make it unable to return an optional
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE RETURNING` statement that updates the modified
/// columns, if and only if the record was modified. The method returns a
@@ -613,12 +625,13 @@ extension MutablePersistableRecord {
/// - parameter returnedType: The type of the returned record.
/// - parameter modify: A closure that modifies the record.
/// - returns: A record of type `returnedType`, or nil if the record has
/// no change, or in case of a failed update due to the `IGNORE`
/// conflict policy.
/// no change.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the update fails due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public mutating func updateChangesAndFetch<T: FetchableRecord & TableRecord>(
@@ -628,10 +641,16 @@ extension MutablePersistableRecord {
modify: (inout Self) throws -> Void)
throws -> T?
{
try updateChangesAndFetch(
let record = self
return try updateChangesAndFetch(
db, onConflict: conflictResolution,
selection: T.databaseSelection,
fetch: { try T.fetchOne($0) },
fetch: {
if let result = try T.fetchOne($0) {
return result
}
throw record.recordNotFound(db)
},
modify: modify)
}
@@ -789,7 +808,6 @@ extension MutablePersistableRecord {
fetch: fetch)
}
// TODO: GRDB7 make it unable to return an optional
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE RETURNING` statement that updates the modified
/// columns, if and only if the record was modified. The method returns a
@@ -802,7 +820,8 @@ extension MutablePersistableRecord {
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes it ``Statement`` argument.
/// - parameter modify: A closure that modifies the record.
/// - returns: The result of the `fetch` function.
/// - returns: The result of the `fetch` function, or nil if the record
/// has no change.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
@@ -814,7 +833,7 @@ extension MutablePersistableRecord {
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T?,
fetch: (Statement) throws -> T,
modify: (inout Self) throws -> Void)
throws -> T?
{
@@ -839,7 +858,7 @@ extension MutablePersistableRecord {
onConflict conflictResolution: Database.ConflictResolution?,
from container: PersistenceContainer,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T?)
fetch: (Statement) throws -> T)
throws -> T?
{
let changes = try PersistenceContainer(db, self).changesIterator(from: container)
@@ -861,7 +880,7 @@ extension MutablePersistableRecord {
onConflict conflictResolution: Database.ConflictResolution?,
from container: PersistenceContainer,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T?)
fetch: (Statement) throws -> T)
throws -> T?
{
let changes = try PersistenceContainer(db, self).changesIterator(from: container)
+24 -20
View File
@@ -56,7 +56,6 @@ extension PersistableRecord {
extension PersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
@@ -94,11 +93,10 @@ extension PersistableRecord {
/// let partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING *
/// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) {
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self)
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// ```
///
@@ -107,19 +105,23 @@ extension PersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`, if any. The result can be
/// nil when the conflict policy is `IGNORE`.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the insertion failed due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
public func insertAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
throws -> T
{
try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
try T.fetchOne($0)
if let result = try T.fetchOne($0) {
return result
}
throw recordNotFound(db)
}
}
@@ -199,7 +201,6 @@ extension PersistableRecord {
return success.returned
}
#else
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
@@ -237,11 +238,10 @@ extension PersistableRecord {
/// let partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING *
/// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) {
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self)
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// ```
///
@@ -250,20 +250,24 @@ extension PersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`, if any. The result can be
/// nil when the conflict policy is `IGNORE`.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the insertion failed due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func insertAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
throws -> T
{
try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
try T.fetchOne($0)
if let result = try T.fetchOne($0) {
return result
}
throw recordNotFound(db)
}
}
+18 -12
View File
@@ -39,7 +39,6 @@ extension PersistableRecord {
extension PersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
@@ -52,26 +51,30 @@ extension PersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the database changes fail due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
public func saveAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
throws -> T
{
try willSave(db)
var success: (saved: PersistenceSuccess, returned: T?)?
var success: (saved: PersistenceSuccess, returned: T)?
try aroundSave(db) {
success = try updateOrInsertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: T.databaseSelection,
fetch: {
try T.fetchOne($0)
if let result = try T.fetchOne($0) {
return result
}
throw recordNotFound(db)
})
return success!.saved
}
@@ -128,7 +131,6 @@ extension PersistableRecord {
return success.returned
}
#else
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
@@ -141,27 +143,31 @@ extension PersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the database changes fail due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func saveAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
throws -> T
{
try willSave(db)
var success: (saved: PersistenceSuccess, returned: T?)?
var success: (saved: PersistenceSuccess, returned: T)?
try aroundSave(db) {
success = try updateOrInsertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: T.databaseSelection,
fetch: {
try T.fetchOne($0)
if let result = try T.fetchOne($0) {
return result
}
throw recordNotFound(db)
})
return success!.saved
}
+2 -2
View File
@@ -41,8 +41,8 @@ open class Record {
public init() { }
/// Creates a Record from a row.
public required init(row: Row) throws {
if row.isFetched {
public required init(row: some RowProtocol) throws {
if row._isFetched {
// Take care of the hasDatabaseChanges flag.
//
// Row may be a reused row which will turn invalid as soon as the
+37 -3
View File
@@ -29,6 +29,7 @@ import Foundation
/// - ``exists(_:id:)``
/// - ``exists(_:key:)-60hf2``
/// - ``exists(_:key:)-6ha6``
/// - ``recordNotFound(_:)``
///
/// ### Throwing Record Not Found Errors
///
@@ -318,7 +319,7 @@ extension TableRecord {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
/// Returns whether a record exists for this primary key.
///
@@ -454,7 +455,7 @@ extension TableRecord {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
/// Deletes records identified by their primary keys, and returns the number
/// of deleted records.
@@ -697,6 +698,15 @@ extension TableRecord {
public enum RecordError: Error {
/// A record does not exist in the database.
///
/// This error can be thrown from methods that update, such as
/// ``MutablePersistableRecord/update(_:onConflict:)``. In this case,
/// the error means that the database was not changed.
///
/// It can also be thrown from methods that inserts or update with a
/// `RETURNING` clause, and the `IGNORE` conflict policy. In this case,
/// the error notifies that a conflict has prevented the change from
/// being applied.
///
/// - parameters:
/// - databaseTableName: The table of the missing record.
/// - key: The key of the missing record (column and values).
@@ -740,7 +750,31 @@ extension TableRecord {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
extension TableRecord where Self: EncodableRecord {
/// Returns an error that tells that the record does not exist in
/// the database.
///
/// - returns: ``RecordError/recordNotFound(databaseTableName:key:)``, or
/// any error that prevented the `RecordError` from being constructed.
public func recordNotFound(_ db: Database) -> any Error {
do {
let databaseTableName = type(of: self).databaseTableName
let primaryKey = try db.primaryKey(databaseTableName)
let container = try PersistenceContainer(db, self)
let key = Dictionary(uniqueKeysWithValues: primaryKey.columns.map {
($0, container[caseInsensitive: $0]?.databaseValue ?? .null)
})
return RecordError.recordNotFound(
databaseTableName: databaseTableName,
key: key)
} catch {
return error
}
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
/// Returns an error for a record that does not exist in the database.
///
-72
View File
@@ -1,72 +0,0 @@
import Foundation
/// A LockedBox protects a value with an NSLock.
@propertyWrapper
final class LockedBox<T> {
private var _wrappedValue: T
private var lock = NSLock()
var wrappedValue: T {
get { read { $0 } }
set { update { $0 = newValue } }
}
var projectedValue: LockedBox<T> { self }
init(wrappedValue: T) {
_wrappedValue = wrappedValue
}
/// Runs the provided closure while holding a lock on the value.
///
/// For example:
///
/// // Prints "0"
/// @LockedBox var count = 0
/// $count.read { print($0) }
///
/// - parameter block: A closure that accepts the value.
@inline(__always)
@usableFromInline
func read<U>(_ block: (T) throws -> U) rethrows -> U {
lock.lock()
defer { lock.unlock() }
return try block(_wrappedValue)
}
/// Runs the provided closure while holding a lock on the value.
///
/// For example:
///
/// // Prints "1"
/// @LockedBox var count = 0
/// $count.update { $0 += 1 }
/// print(count)
///
/// - parameter block: A closure that can modify the value.
func update<U>(_ block: (inout T) throws -> U) rethrows -> U {
lock.lock()
defer { lock.unlock() }
return try block(&_wrappedValue)
}
}
extension LockedBox where T: Numeric {
@discardableResult
func increment() -> T {
update { n in
n += 1
return n
}
}
@discardableResult
func decrement() -> T {
update { n in
n -= 1
return n
}
}
}
extension LockedBox: @unchecked Sendable where T: Sendable { }
+45
View File
@@ -0,0 +1,45 @@
import Foundation
/// A Mutex protects a value with an NSLock.
final class Mutex<T> {
private var _value: T
private var lock = NSLock()
var value: T {
get { withLock { $0 } }
set { withLock { $0 = newValue } }
}
init(_ value: T) {
_value = value
}
/// Runs the provided closure while holding a lock on the value.
///
/// - parameter body: A closure that can modify the value.
func withLock<U>(_ body: (inout T) throws -> U) rethrows -> U {
lock.lock()
defer { lock.unlock() }
return try body(&_value)
}
}
extension Mutex where T: Numeric {
@discardableResult
func increment() -> T {
withLock { n in
n += 1
return n
}
}
@discardableResult
func decrement() -> T {
withLock { n in
n -= 1
return n
}
}
}
extension Mutex: @unchecked Sendable where T: Sendable { }
+9 -5
View File
@@ -14,9 +14,12 @@ import Foundation
/// Both two extra scheduling guarantees are used by GRDB in order to be
/// able to spawn concurrent database reads right from the database writer
/// queue, and fulfill GRDB preconditions.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
///
/// OnDemandFuture also adds Sendable requirements that avoid
/// compiler warnings.
@available(iOS 13, macOS 10.15, tvOS 13, *)
struct OnDemandFuture<Output, Failure: Error>: Publisher {
typealias Promise = (Result<Output, Failure>) -> Void
typealias Promise = @Sendable (Result<Output, Failure>) -> Void
typealias Output = Output
typealias Failure = Failure
fileprivate let attemptToFulfill: (@escaping Promise) -> Void
@@ -33,9 +36,10 @@ struct OnDemandFuture<Output, Failure: Error>: Publisher {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
private class OnDemandFutureSubscription<Downstream: Subscriber>: Subscription {
typealias Promise = (Result<Downstream.Input, Downstream.Failure>) -> Void
@available(iOS 13, macOS 10.15, tvOS 13, *)
private class OnDemandFutureSubscription<Downstream: Subscriber>: Subscription, @unchecked Sendable {
// @unchecked because `state` is protected with `lock`.
typealias Promise = @Sendable (Result<Downstream.Input, Downstream.Failure>) -> Void
private enum State {
case waitingForDemand(downstream: Downstream, attemptToFulfill: (@escaping Promise) -> Void)
+33 -19
View File
@@ -35,8 +35,9 @@ import Dispatch
/// got 2
/// got 1
/// got 3
final class Pool<T> {
private class Item {
final class Pool<T: Sendable>: Sendable {
private class Item: @unchecked Sendable {
// @unchecked because `isAvailable` is protected by `content`.
let element: T
var isAvailable: Bool
@@ -46,8 +47,19 @@ final class Pool<T> {
}
}
private let makeElement: () throws -> T
@ReadWriteBox private var items: [Item] = []
private struct Content {
var items: [Item]
/// The number of created items. May become greater than the number
/// of elements in items, as some items are destroyed and other
/// are created.
var createdCount = 0
}
typealias ElementAndRelease = (element: T, release: @Sendable (PoolCompletion) -> Void)
private let makeElement: @Sendable (Int) throws -> T
private let content = ReadWriteBox(wrappedValue: Content(items: [], createdCount: 0))
private let itemsSemaphore: DispatchSemaphore // limits the number of elements
private let itemsGroup: DispatchGroup // knows when no element is used
private let barrierQueue: DispatchQueue
@@ -59,11 +71,12 @@ final class Pool<T> {
/// - maximumCount: The maximum number of elements.
/// - qos: The quality of service of asynchronous accesses.
/// - makeElement: A function that creates an element. It is called
/// on demand.
/// on demand. Its argument is the index of the created elements
/// (1, then 2, etc).
init(
maximumCount: Int,
qos: DispatchQoS = .unspecified,
makeElement: @escaping () throws -> T)
makeElement: @escaping @Sendable (_ index: Int) throws -> T)
{
GRDBPrecondition(maximumCount > 0, "Pool size must be at least 1")
self.makeElement = makeElement
@@ -75,19 +88,20 @@ final class Pool<T> {
/// Returns a tuple (element, release)
/// Client must call release(), only once, after the element has been used.
func get() throws -> (element: T, release: (PoolCompletion) -> Void) {
func get() throws -> ElementAndRelease {
try barrierQueue.sync {
itemsSemaphore.wait()
itemsGroup.enter()
do {
let item = try $items.update { items -> Item in
if let item = items.first(where: \.isAvailable) {
let item = try content.update { content -> Item in
if let item = content.items.first(where: \.isAvailable) {
item.isAvailable = false
return item
} else {
let element = try makeElement()
content.createdCount += 1
let element = try makeElement(content.createdCount)
let item = Item(element: element, isAvailable: false)
items.append(item)
content.items.append(item)
return item
}
}
@@ -107,7 +121,7 @@ final class Pool<T> {
///
/// - important: The `execute` argument is executed in a serial dispatch
/// queue, so make sure you use the element asynchronously.
func asyncGet(_ execute: @escaping (Result<(element: T, release: (PoolCompletion) -> Void), Error>) -> Void) {
func asyncGet(_ execute: @escaping @Sendable (Result<ElementAndRelease, Error>) -> Void) {
// Inspired by https://khanlou.com/2016/04/the-GCD-handbook/
// > We wait on the semaphore in the serial queue, which means that
// > we’ll have at most one blocked thread when we reach maximum
@@ -128,7 +142,7 @@ final class Pool<T> {
}
private func release(_ item: Item, completion: PoolCompletion) {
$items.update { items in
content.update { content in
switch completion {
case .reuse:
// This is why Item is a class, not a struct: so that we can
@@ -136,8 +150,8 @@ final class Pool<T> {
item.isAvailable = true
case .discard:
// Discard should be rare: perform lookup.
if let index = items.firstIndex(where: { $0 === item }) {
items.remove(at: index)
if let index = content.items.firstIndex(where: { $0 === item }) {
content.items.remove(at: index)
}
}
}
@@ -148,8 +162,8 @@ final class Pool<T> {
/// Performs a block on each pool element, available or not.
/// The block is run is some arbitrary dispatch queue.
func forEach(_ body: (T) throws -> Void) rethrows {
try $items.read { items in
for item in items {
try content.read { content in
for item in content.items {
try body(item.element)
}
}
@@ -158,7 +172,7 @@ final class Pool<T> {
/// Removes all elements from the pool.
/// Currently used elements won't be reused.
func removeAll() {
items = []
content.update { $0.items.removeAll() }
}
/// Blocks until no element is used, and runs the `barrier` function before
@@ -172,7 +186,7 @@ final class Pool<T> {
/// Asynchronously runs the `barrier` function when no element is used, and
/// before any other element is dequeued.
func asyncBarrier(execute barrier: @escaping () -> Void) {
func asyncBarrier(execute barrier: @escaping @Sendable () -> Void) {
barrierQueue.async(flags: [.barrier]) {
self.itemsGroup.wait()
barrier()
+2 -1
View File
@@ -3,7 +3,8 @@ import Dispatch
/// A ReadWriteBox grants multiple readers and single-writer guarantees on a
/// value. It is backed by a concurrent DispatchQueue.
@propertyWrapper
final class ReadWriteBox<T> {
final class ReadWriteBox<T: Sendable>: @unchecked Sendable {
// @unchecked because `_wrappedValue` is protected by `queue`
private var _wrappedValue: T
private var queue: DispatchQueue
+3 -3
View File
@@ -11,7 +11,7 @@ import Foundation
/// This scheduling guarantee is used by GRDB in order to be able
/// to make promises on the scheduling of database values without surprising
/// the users as in <https://forums.swift.org/t/28631>.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
struct ReceiveValuesOn<Upstream: Publisher, Context: Scheduler>: Publisher {
typealias Output = Upstream.Output
typealias Failure = Upstream.Failure
@@ -30,7 +30,7 @@ struct ReceiveValuesOn<Upstream: Publisher, Context: Scheduler>: Publisher {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
private class ReceiveValuesOnSubscription<Upstream, Context, Downstream>: Subscription, Subscriber
where
Upstream: Publisher,
@@ -211,7 +211,7 @@ where
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension Publisher {
/// Specifies the scheduler on which to receive values from the publisher
///
+3 -3
View File
@@ -67,7 +67,7 @@ extension Dictionary {
}
extension DispatchQueue {
private static var mainKey: DispatchSpecificKey<()> = {
nonisolated(unsafe) private static let mainKey: DispatchSpecificKey<()> = {
let key = DispatchSpecificKey<()>()
DispatchQueue.main.setSpecific(key: key, value: ())
return key
@@ -125,7 +125,7 @@ struct PrintOutputStream: TextOutputStream {
}
/// Concatenates two functions
func concat(_ rhs: (() -> Void)?, _ lhs: (() -> Void)?) -> (() -> Void)? {
func concat(_ rhs: (@Sendable () -> Void)?, _ lhs: (@Sendable () -> Void)?) -> (@Sendable () -> Void)? {
switch (rhs, lhs) {
case let (rhs, nil):
return rhs
@@ -140,7 +140,7 @@ func concat(_ rhs: (() -> Void)?, _ lhs: (() -> Void)?) -> (() -> Void)? {
}
/// Concatenates two functions
func concat<T>(_ rhs: ((T) -> Void)?, _ lhs: ((T) -> Void)?) -> ((T) -> Void)? {
func concat<T>(_ rhs: (@Sendable (T) -> Void)?, _ lhs: (@Sendable (T) -> Void)?) -> (@Sendable (T) -> Void)? {
switch (rhs, lhs) {
case let (rhs, nil):
return rhs
+21 -10
View File
@@ -1,3 +1,5 @@
import Foundation
/// A protocol indicating that an activity or action supports cancellation.
///
/// ## Topics
@@ -15,31 +17,40 @@ public protocol DatabaseCancellable {
///
/// An `AnyDatabaseCancellable` instance automatically calls ``cancel()``
/// when deinitialized.
public class AnyDatabaseCancellable: DatabaseCancellable {
private var _cancel: (() -> Void)?
public final class AnyDatabaseCancellable: DatabaseCancellable, @unchecked Sendable {
// @unchecked Sendable due to `_cancel`, which is protected by `lock`.
private let lock = NSLock()
private var _cancel: (@Sendable () -> Void)?
var isCancelled: Bool {
lock.withLock { _cancel == nil }
}
convenience init() {
self.init(cancel: { })
}
/// Initializes the cancellable object with the given cancel-time closure.
public init(cancel: @escaping () -> Void) {
public init(cancel: @escaping @Sendable () -> Void) {
_cancel = cancel
}
/// Creates a cancellable object that forwards cancellation to `base`.
public convenience init(_ base: some DatabaseCancellable) {
var cancellable = Optional.some(base)
self.init {
cancellable?.cancel()
cancellable = nil // Release memory
base.cancel()
}
}
deinit {
_cancel?()
cancel()
}
public func cancel() {
// Don't prevent multiple concurrent calls to _cancel, because it is
// pointless. But release memory!
_cancel?()
lock.lock()
let cancel = _cancel
_cancel = nil
lock.unlock()
cancel?()
}
}
@@ -146,7 +146,7 @@ final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObser
private var notificationCallbacks: NotificationCallbacks?
/// The fetching state for observation of constant regions.
@LockedBox private var fetchingState = FetchingState.idle
private let fetchingStateMutex = Mutex(FetchingState.idle)
/// Support for `TransactionObserver`, protected by the serialized writer
/// dispatch queue.
@@ -273,8 +273,7 @@ extension ValueConcurrentObserver {
}
}
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
extension ValueConcurrentObserver {
/// Synchronously starts the observation, and returns the initial value.
///
@@ -353,10 +352,11 @@ extension ValueConcurrentObserver {
let initialFetchTransaction = try result.get()
// Second async jump because that's how
// `DatabasePool.asyncWALSnapshotTransaction` has to be used.
initialFetchTransaction.asyncRead { db in
initialFetchTransaction.asyncRead { dbResult in
do {
let fetchedValue: Reducer.Fetched
let initialRegion: DatabaseRegion
let db = try dbResult.get()
switch self.trackingMode {
case let .constantRegion(regions):
@@ -430,11 +430,9 @@ extension ValueConcurrentObserver {
// checkpointed. That's why we'll keep `initialFetchTransaction`
// alive until the comparison is done.
//
// However, we want to release `initialFetchTransaction` as soon as
// However, we want to close `initialFetchTransaction` as soon as
// possible, so that the reader connection it holds becomes
// available for other reads. It will be released when this optional
// is set to nil:
var initialFetchTransaction: WALSnapshotTransaction? = initialFetchTransaction
// available for other reads.
databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in
let events = self.lock.synchronized { self.notificationCallbacks?.events }
@@ -447,7 +445,7 @@ extension ValueConcurrentObserver {
// Was the database modified since the initial fetch?
let isModified: Bool
if let currentWALSnapshot = try? WALSnapshot(writerDB) {
let ordering = initialFetchTransaction!.walSnapshot.compare(currentWALSnapshot)
let ordering = initialFetchTransaction.walSnapshot.compare(currentWALSnapshot)
assert(ordering <= 0, "Unexpected snapshot ordering")
isModified = ordering < 0
} else {
@@ -455,9 +453,9 @@ extension ValueConcurrentObserver {
isModified = true
}
// Comparison done: end the WAL snapshot transaction
// Comparison done: close the WAL snapshot transaction
// and release its reader connection.
initialFetchTransaction = nil
initialFetchTransaction.close()
if isModified {
events.databaseDidChange?()
@@ -781,7 +779,7 @@ extension ValueConcurrentObserver: TransactionObserver {
}
private func setNeedsFetching(databaseAccess: DatabaseAccess) {
$fetchingState.update { state in
fetchingStateMutex.withLock { state in
switch state {
case .idle:
state = .fetching
@@ -807,7 +805,7 @@ extension ValueConcurrentObserver: TransactionObserver {
self.reduce(fetchResult)
$fetchingState.update { state in
fetchingStateMutex.withLock { state in
switch state {
case .idle:
// GRDB bug
@@ -291,7 +291,7 @@ public final class SharedValueObservation<Element> {
/// print("fresh players: \(players)")
/// }
/// ```
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func publisher() -> DatabasePublishers.Value<Element> {
DatabasePublishers.Value { onError, onChange in
self.start(onError: onError, onChange: onChange)
@@ -368,7 +368,7 @@ extension SharedValueObservation {
/// print("Fresh players: \(players)")
/// }
/// ```
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func values(bufferingPolicy: AsyncValueObservation<Element>.BufferingPolicy = .unbounded)
-> AsyncValueObservation<Element>
{
+42 -41
View File
@@ -74,15 +74,15 @@ enum ValueObservationTrackingMode {
}
struct ValueObservationEvents: Refinable {
var willStart: (() -> Void)?
var willTrackRegion: ((DatabaseRegion) -> Void)?
var databaseDidChange: (() -> Void)?
var didFail: ((Error) -> Void)?
var didCancel: (() -> Void)?
var willStart: (@Sendable () -> Void)?
var willTrackRegion: (@Sendable (DatabaseRegion) -> Void)?
var databaseDidChange: (@Sendable () -> Void)?
var didFail: (@Sendable (Error) -> Void)?
var didCancel: (@Sendable () -> Void)?
}
typealias ValueObservationStart<T> = (
_ onError: @escaping (Error) -> Void,
_ onError: @escaping @Sendable (Error) -> Void,
_ onChange: @escaping (T) -> Void)
-> AnyDatabaseCancellable
@@ -138,7 +138,7 @@ extension ValueObservation: Refinable {
public func start(
in reader: some DatabaseReader,
scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main),
onError: @escaping (Error) -> Void,
onError: @escaping @Sendable (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
where Reducer: ValueReducer
@@ -175,13 +175,13 @@ extension ValueObservation: Refinable {
/// - returns: A `ValueObservation` that performs the specified closures
/// when ValueObservation events occur.
public func handleEvents(
willStart: (() -> Void)? = nil,
willFetch: (() -> Void)? = nil,
willTrackRegion: ((DatabaseRegion) -> Void)? = nil,
databaseDidChange: (() -> Void)? = nil,
didReceiveValue: ((Reducer.Value) -> Void)? = nil,
didFail: ((Error) -> Void)? = nil,
didCancel: (() -> Void)? = nil)
willStart: (@Sendable () -> Void)? = nil,
willFetch: (@Sendable () -> Void)? = nil,
willTrackRegion: (@Sendable (DatabaseRegion) -> Void)? = nil,
databaseDidChange: (@Sendable () -> Void)? = nil,
didReceiveValue: (@Sendable (Reducer.Value) -> Void)? = nil,
didFail: (@Sendable (Error) -> Void)? = nil,
didCancel: (@Sendable () -> Void)? = nil)
-> ValueObservation<ValueReducers.Trace<Reducer>>
{
self
@@ -234,31 +234,30 @@ extension ValueObservation: Refinable {
to stream: TextOutputStream? = nil)
-> ValueObservation<ValueReducers.Trace<Reducer>>
{
let lock = NSLock()
let streamMutex = Mutex(stream ?? PrintOutputStream())
let prefix = prefix.isEmpty ? "" : "\(prefix): "
var stream = stream ?? PrintOutputStream()
return handleEvents(
willStart: {
lock.lock(); defer { lock.unlock() }
stream.write("\(prefix)start") },
streamMutex.withLock { $0.write("\(prefix)start") }
},
willFetch: {
lock.lock(); defer { lock.unlock() }
stream.write("\(prefix)fetch") },
willTrackRegion: {
lock.lock(); defer { lock.unlock() }
stream.write("\(prefix)tracked region: \($0)") },
streamMutex.withLock { $0.write("\(prefix)fetch") }
},
willTrackRegion: { region in
streamMutex.withLock { $0.write("\(prefix)tracked region: \(region)") }
},
databaseDidChange: {
lock.lock(); defer { lock.unlock() }
stream.write("\(prefix)database did change") },
didReceiveValue: {
lock.lock(); defer { lock.unlock() }
stream.write("\(prefix)value: \($0)") },
didFail: {
lock.lock(); defer { lock.unlock() }
stream.write("\(prefix)failure: \($0)") },
streamMutex.withLock { $0.write("\(prefix)database did change") }
},
didReceiveValue: { value in
streamMutex.withLock { $0.write("\(prefix)value: \(value)") }
},
didFail: { error in
streamMutex.withLock { $0.write("\(prefix)failure: \(error)") }
},
didCancel: {
lock.lock(); defer { lock.unlock() }
stream.write("\(prefix)cancel") })
streamMutex.withLock { $0.write("\(prefix)cancel") }
})
}
// MARK: - Fetching Values
@@ -294,18 +293,20 @@ extension ValueObservation {
/// ```
///
/// - parameter reader: A DatabaseReader.
/// - parameter scheduler: A ValueObservationScheduler. By default, fresh
/// values are dispatched asynchronously on the main dispatch queue.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func values(
in reader: some DatabaseReader,
scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main),
bufferingPolicy: AsyncValueObservation<Reducer.Value>.BufferingPolicy = .unbounded)
-> AsyncValueObservation<Reducer.Value>
where Reducer: ValueReducer
{
AsyncValueObservation(bufferingPolicy: bufferingPolicy) { onError, onChange in
self.start(in: reader, scheduling: scheduler, onError: onError, onChange: onChange)
self.start(
in: reader,
// TODO: can we avoid this hop to the main queue?
scheduling: .async(onQueue: .main),
onError: onError,
onChange: onChange)
}
}
}
@@ -332,7 +333,7 @@ extension ValueObservation {
///
/// You build an `AsyncValueObservation` from ``ValueObservation`` or
/// ``SharedValueObservation``.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public struct AsyncValueObservation<Element>: AsyncSequence {
public typealias BufferingPolicy = AsyncThrowingStream<Element, Error>.Continuation.BufferingPolicy
public typealias AsyncIterator = Iterator
@@ -434,7 +435,7 @@ extension ValueObservation {
/// - parameter scheduler: A ValueObservationScheduler. By default, fresh
/// values are dispatched asynchronously on the main dispatch queue.
/// - returns: A Combine publisher
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func publisher(
in reader: some DatabaseReader,
scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main))
@@ -451,7 +452,7 @@ extension ValueObservation {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@available(iOS 13, macOS 10.15, tvOS 13, *)
extension DatabasePublishers {
/// A publisher that publishes the values of a ``ValueObservation``.
///
@@ -11,17 +11,17 @@ import Foundation
/// - ``immediate``
/// - ``AsyncValueObservationScheduler``
/// - ``ImmediateValueObservationScheduler``
public protocol ValueObservationScheduler {
public protocol ValueObservationScheduler: Sendable {
/// Returns whether the initial value should be immediately notified.
///
/// If the result is true, then this method was called on the main thread.
func immediateInitialValue() -> Bool
func schedule(_ action: @escaping () -> Void)
func schedule(_ action: @escaping @Sendable () -> Void)
}
extension ValueObservationScheduler {
func scheduleInitial(_ action: @escaping () -> Void) {
func scheduleInitial(_ action: @escaping @Sendable () -> Void) {
if immediateInitialValue() {
action()
} else {
@@ -42,7 +42,7 @@ public struct AsyncValueObservationScheduler: ValueObservationScheduler {
public func immediateInitialValue() -> Bool { false }
public func schedule(_ action: @escaping () -> Void) {
public func schedule(_ action: @escaping @Sendable () -> Void) {
queue.async(execute: action)
}
}
@@ -86,7 +86,7 @@ public struct ImmediateValueObservationScheduler: ValueObservationScheduler, Sen
return true
}
public func schedule(_ action: @escaping () -> Void) {
public func schedule(_ action: @escaping @Sendable () -> Void) {
DispatchQueue.main.async(execute: action)
}
}
Loaded 100 of 214 files, more files were not shown because too many files have changed in this diff. Show more