Compare commits

..
Author SHA1 Message Date
Gwendal Roué 389b14ede0 Tests for super encoders WIP 2024-03-18 19:07:07 +01:00
227 changed files with 3332 additions and 3966 deletions

No files matched your search

+1 -6
View File
@@ -7,7 +7,6 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 6.x Releases
- `6.26.x` Releases - [6.26.0](#6260)
- `6.25.x` Releases - [6.25.0](#6250)
- `6.24.x` Releases - [6.24.0](#6240) - [6.24.1](#6241) - [6.24.2](#6242)
- `6.23.x` Releases - [6.23.0](#6230)
@@ -124,16 +123,12 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## 6.26.0
Released March 23, 2024
## Next Release
- **New**: [#1503](https://github.com/groue/GRDB.swift/pull/1503) by [@simba909](https://github.com/simba909): Conform Database.ColumnType to Sendable
- **New**: [#1510](https://github.com/groue/GRDB.swift/pull/1510) by [@groue](https://github.com/groue): Add Sendable conformances and unavailabilities
- **New**: [#1511](https://github.com/groue/GRDB.swift/pull/1511) by [@groue](https://github.com/groue): Database schema dump
- **New**: [#1515](https://github.com/groue/GRDB.swift/pull/1515) by [@groue](https://github.com/groue): Support for the CAST SQLite function
- **Fixed**: [#1508](https://github.com/groue/GRDB.swift/pull/1508) by [@groue](https://github.com/groue): Fix ValueObservation mishandling of database schema modification
- **Fixed**: [#1512](https://github.com/groue/GRDB.swift/issues/1512): Decoding errors are now correctly reported when decoding NULL into a non-optional property of type `Data` or `Date`.
## 6.25.0
+3 -3
View File
@@ -2169,7 +2169,7 @@ struct BookInfo: FetchableRecord {
var country: Country?
var coverImage: CoverImage?
init(row: some RowProtocol) throws {
init(row: Row) 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: some RowProtocol) throws {
init(row: Row) throws {
author = try Author(row: row)
books = row["books"]
}
@@ -2661,7 +2661,7 @@ Aggregates can be modified and combined with Swift operators:
let request = Team.annotated(with: Team.players.min(Column("score")) ?? 0)
```
- SQL functions `ABS`, `CAST`, and `LENGTH` are available as the `abs`, `cast`, and `length` Swift functions:
- SQL functions `ABS` and `LENGTH` are available as the `abs` and `length` Swift functions:
<details>
<summary>SQL</summary>
@@ -1,7 +1,6 @@
import WatchKit
import Foundation
import GRDB
import SQLite3
class InterfaceController: WKInterfaceController {
@@ -75,7 +75,7 @@ struct Place {
// Adopt FetchableRecord
extension Place : FetchableRecord {
init(row: some RowProtocol) {
init(row: Row) {
id = row["id"]
title = row["title"]
favorite = row["favorite"]
+2 -2
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '6.26.0'
s.version = '6.25.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
@@ -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.10']
s.swift_versions = ['5.7']
s.ios.deployment_target = '11.0'
s.osx.deployment_target = '10.13'
s.watchos.deployment_target = '4.0'
+9 -21
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 /* Mutex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* Mutex.swift */; };
566BE71E2342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.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,8 +256,6 @@
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 */; };
@@ -269,6 +267,7 @@
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 */; };
@@ -285,7 +284,6 @@
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 */; };
@@ -413,7 +411,6 @@
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 */; };
@@ -631,7 +628,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 /* Mutex.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Mutex.swift; sourceTree = "<group>"; };
566BE7172342542F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.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>"; };
@@ -724,8 +721,6 @@
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>"; };
@@ -760,6 +755,7 @@
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>"; };
@@ -787,7 +783,6 @@
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>"; };
@@ -851,7 +846,6 @@
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>"; };
@@ -1016,7 +1010,6 @@
children = (
56677C14241D14450050755D /* FailureTestCase.swift */,
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
56BCA65B2B79246300B3A7F8 /* Mutex.swift */,
562EA81E1F17B26F00FA528C /* Compilation */,
56A238111B9C74A90082EB20 /* Core */,
567B5BDA2AD3281B00629622 /* Dump */,
@@ -1325,7 +1318,7 @@
56717270261C68E900423B6F /* CaseInsensitiveIdentifier.swift */,
563EF4492161F179007DAACD /* Inflections.swift */,
569BBA482291707D00478429 /* Inflections+English.swift */,
566BE7172342542F00A8254B /* Mutex.swift */,
566BE7172342542F00A8254B /* LockedBox.swift */,
563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */,
563EF414215F87EB007DAACD /* OrderedDictionary.swift */,
5659F4971EA8D989004A4992 /* Pool.swift */,
@@ -1591,15 +1584,13 @@
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 */,
@@ -1609,7 +1600,6 @@
56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */,
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
56B7EE822863781300C0525F /* WALSnapshot.swift */,
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */,
5605F1471C672E4000235C62 /* Support */,
);
path = Core;
@@ -1747,6 +1737,7 @@
DC37742D19C8CC90004FCF85 /* GRDB */ = {
isa = PBXGroup;
children = (
56A2FA3524424D2A00E97D23 /* Export.swift */,
566DDE0C288D763C0000DCFB /* Fixits.swift */,
648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */,
56A2386F1B9C75030082EB20 /* Core */,
@@ -2110,7 +2101,6 @@
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 */,
@@ -2232,13 +2222,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 */,
@@ -2273,10 +2263,9 @@
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 /* Mutex.swift in Sources */,
566BE71E2342542F00A8254B /* LockedBox.swift in Sources */,
56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
5603CEBB2AC862EC00CF097D /* SQLJSONExpressible.swift in Sources */,
56F89DF72A57EAA9002FE2AA /* ColumnDefinition.swift in Sources */,
@@ -2330,7 +2319,6 @@
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;
+28 -32
View File
@@ -1,17 +1,7 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Dispatch
import Foundation
// TODO: remove @unchecked when DispatchQoS is Sendable
public struct Configuration: @unchecked Sendable {
public struct Configuration {
// MARK: - Misc options
@@ -196,7 +186,7 @@ public struct Configuration: @unchecked Sendable {
// MARK: - Managing SQLite Connections
private var setups: [@Sendable (Database) throws -> Void] = []
private var setups: [(Database) throws -> Void] = []
/// Defines a function to run whenever an SQLite connection is opened.
///
@@ -233,12 +223,34 @@ public struct Configuration: @unchecked Sendable {
///
/// On newly created databases files, ``DatabasePool`` activates the WAL
/// mode after the preparation functions have run.
public mutating func prepareDatabase(_ setup: @escaping @Sendable (Database) throws -> Void) {
public mutating func prepareDatabase(_ setup: @escaping (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.
///
@@ -433,25 +445,9 @@ public struct Configuration: @unchecked Sendable {
/// through a `SerializedDatabase`.
var threadingMode = Database.ThreadingMode.default
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 SQLiteConnectionDidOpen: (() -> Void)?
var SQLiteConnectionWillClose: ((SQLiteConnection) -> Void)?
var SQLiteConnectionDidClose: (() -> Void)?
var SQLiteOpenFlags: CInt {
var flags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE)
if sqlite3_libversion_number() >= 3037000 {
-4
View File
@@ -865,10 +865,6 @@ 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() {
+4 -13
View File
@@ -1,12 +1,3 @@
// 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 {
@@ -1072,7 +1063,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: some RowProtocol) {
public init(row: Row) {
cid = row["cid"]
name = row["name"]
type = row["type"]
@@ -1238,7 +1229,7 @@ public struct ForeignKeyViolation: Sendable {
}
extension ForeignKeyViolation: FetchableRecord {
public init(row: some RowProtocol) {
public init(row: Row) {
originTable = row[0]
originRowID = row[1]
destinationTable = row[2]
@@ -1481,7 +1472,7 @@ struct TableInfo: FetchableRecord {
var hasRowID: Bool
var strict: Bool
init(row: some RowProtocol) throws {
init(row: Row) throws {
switch row[0] as String {
case "main":
schemaID = .main
@@ -1515,7 +1506,7 @@ struct SchemaObject: Hashable, FetchableRecord {
var tbl_name: String?
var sql: String?
init(row: some RowProtocol) throws {
init(row: Row) throws {
// "rootpage" column is not always there: avoid using numerical indexes
type = row["type"]
name = row["name"]
+1 -10
View File
@@ -1,12 +1,3 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
extension Database {
@@ -547,7 +538,7 @@ struct StatementCache {
let statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT))
#else
let statement: Statement
if #available(macOS 10.14, *) { // SQLite 3.20+
if #available(iOS 12, macOS 10.14, watchOS 5, *) { // SQLite 3.20+
statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT))
} else {
statement = try db.makeStatement(sql: sql)
+42 -106
View File
@@ -1,12 +1,3 @@
// 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.
@@ -15,7 +6,7 @@ public typealias SQLiteConnection = OpaquePointer
/// A raw SQLite function argument.
typealias SQLiteValue = OpaquePointer
nonisolated(unsafe) let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_destructor_type.self)
let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_destructor_type.self)
/// An SQLite connection.
///
@@ -122,15 +113,8 @@ nonisolated(unsafe) let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPatter
/// - ``logError``
/// - ``releaseMemory()``
/// - ``trace(options:_:)``
///
/// ### Supporting Types
///
/// - ``BusyCallback``
/// - ``BusyMode``
/// - ``CheckpointMode``
/// - ``DatabaseBackupProgress``
/// - ``LogErrorFunction``
/// - ``StorageClass``
/// - ``TraceEvent``
/// - ``TracingOptions``
public final class Database: CustomStringConvertible, CustomDebugStringConvertible {
@@ -139,6 +123,8 @@ 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
@@ -149,26 +135,8 @@ 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>
nonisolated(unsafe) public static var logError: LogErrorFunction? = nil {
public static var logError: LogErrorFunction? = nil {
didSet {
if logError != nil {
_registerErrorLogCallback { (_, code, message) in
@@ -316,7 +284,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
var isInsideTransactionBlock = false
/// Support for `checkForSuspensionViolation(from:)`
let isSuspendedMutex = Mutex(false)
@LockedBox var isSuspended = false
/// Support for `checkForSuspensionViolation(from:)`
/// This cache is never cleared: we assume journal mode never changes.
@@ -1147,25 +1115,22 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
///
/// Suspension ends with `resume()`.
func suspend() {
let needsInterrupt = isSuspendedMutex.withLock { isSuspended in
$isSuspended.update { isSuspended in
if isSuspended {
return false
return
}
// Prevent future lock acquisition
isSuspended = true
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 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>
interrupt()
// Now what about the eventual remaining lock? We'll issue a
// rollback on next database access which requires a lock, in
// checkForSuspensionViolation(from:).
}
}
@@ -1177,7 +1142,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
///
/// See suspend().
func resume() {
isSuspendedMutex.value = false
isSuspended = false
}
/// Support for `checkForSuspensionViolation(from:)`
@@ -1207,9 +1172,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
///
/// See `suspend()` and ``Configuration/observesSuspensionNotifications``.
func checkForSuspensionViolation(from statement: Statement) throws {
let needsAbort = try isSuspendedMutex.withLock { isSuspended in
try $isSuspended.read { isSuspended in
guard isSuspended else {
return false
return
}
if try journalMode() == "wal" && statement.isReadonly {
@@ -1220,7 +1185,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// Those are not read-only:
// - INSERT ...
// - BEGIN IMMEDIATE TRANSACTION
return false
return
}
if statement.releasesDatabaseLock {
@@ -1229,14 +1194,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// - ROLLBACK
// - ROLLBACK TRANSACTION TO SAVEPOINT
// - RELEASE SAVEPOINT
return false
return
}
// 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().
//
@@ -1312,10 +1272,14 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// Use ``inSavepoint(_:)`` instead.
///
/// - parameters:
/// - kind: The transaction type.
/// - kind: The transaction type (default nil).
///
/// If nil, the transaction kind is DEFERRED when the current
/// database access is read-only, and IMMEDIATE otherwise.
/// 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``.
/// - 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
@@ -1439,7 +1403,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// By default, top level SQLite savepoints open a
// deferred transaction.
//
// But GRDB prefers immediate transactions for writes.
// But GRDB database configuration mandates a default transaction
// kind that we have to honor.
//
// Besides, starting some (?) SQLCipher/SQLite version, SQLite has a
// bug. Returning 1 from `sqlite3_commit_hook` does not leave the
@@ -1529,20 +1494,16 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// - parameters:
/// - kind: The transaction type (default nil).
///
/// If nil, the transaction kind is DEFERRED when the current
/// database access is read-only, and IMMEDIATE otherwise.
/// 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``.
/// - 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.
// 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)
let kind = kind ?? (isReadOnly ? .deferred : configuration.defaultTransactionKind)
try execute(sql: "BEGIN \(kind.rawValue) TRANSACTION")
assert(sqlite3_get_autocommit(sqliteConnection) == 0)
}
@@ -1852,8 +1813,8 @@ extension Database {
// MARK: - Database-Related Types
/// See ``BusyMode`` and <https://www.sqlite.org/c3ref/busy_handler.html>
public typealias BusyCallback = @Sendable (_ numberOfTries: Int) -> Bool
/// See BusyMode and <https://www.sqlite.org/c3ref/busy_handler.html>
public typealias BusyCallback = (_ 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.
@@ -1881,7 +1842,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: Sendable {
public enum BusyMode {
/// The `SQLITE_BUSY` error is immediately returned to the connection
/// that tries to access the locked database.
case immediateError
@@ -1959,6 +1920,7 @@ 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
@@ -2041,33 +2003,7 @@ extension Database {
}
/// An error log function that takes an error code and message.
public typealias LogErrorFunction = @Sendable (_ resultCode: ResultCode, _ message: String) -> Void
/// An SQLite storage class.
///
/// For more information, see
/// [Datatypes In SQLite](https://www.sqlite.org/datatype3.html).
public struct StorageClass: RawRepresentable, Hashable, Sendable {
/// The SQL for the storage class (`"INTEGER"`, `"REAL"`, etc.)
public let rawValue: String
/// Creates an SQL storage class.
public init(rawValue: String) {
self.rawValue = rawValue
}
/// The `INTEGER` storage class.
public static let integer = StorageClass(rawValue: "INTEGER")
/// The `REAL` storage class.
public static let real = StorageClass(rawValue: "REAL")
/// The `TEXT` storage class.
public static let text = StorageClass(rawValue: "TEXT")
/// The `BLOB` storage class.
public static let blob = StorageClass(rawValue: "BLOB")
}
public typealias LogErrorFunction = (_ resultCode: ResultCode, _ message: String) -> Void
/// An option for the SQLite tracing feature.
///
+3 -12
View File
@@ -1,12 +1,3 @@
// 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.
@@ -29,10 +20,10 @@ import Foundation
/// - ``localizedCompare``
/// - ``localizedStandardCompare``
/// - ``unicodeCompare``
public final class DatabaseCollation: Sendable {
public final class DatabaseCollation {
/// The name of the collation.
public let name: String
let function: @Sendable (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
let function: (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
/// Creates a collation.
///
@@ -49,7 +40,7 @@ public final class DatabaseCollation: Sendable {
/// - parameters:
/// - name: The collation name.
/// - function: A function that compares two strings.
public init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
public init(_ name: String, function: @escaping (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,12 +1,3 @@
// 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.
@@ -415,10 +406,6 @@ 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`
+6 -15
View File
@@ -1,12 +1,3 @@
// 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
@@ -29,7 +20,7 @@ import SQLite3
/// - ``localizedUppercase``
/// - ``lowercase``
/// - ``uppercase``
public final class DatabaseFunction: Hashable, Sendable {
public final class DatabaseFunction: Hashable {
// SQLite identifies functions by (name + argument count)
private struct Identity: Hashable {
let name: String
@@ -82,11 +73,11 @@ public final class DatabaseFunction: Hashable, Sendable {
_ name: String,
argumentCount: Int? = nil,
pure: Bool = false,
function: @escaping @Sendable ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
function: @escaping ([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]!)
}
@@ -274,12 +265,12 @@ public final class DatabaseFunction: Hashable, Sendable {
/// A function kind: an "SQL function" or an "aggregate".
/// See <http://sqlite.org/capi3ref.html#sqlite3_create_function>
private enum Kind: Sendable {
private enum Kind {
/// A regular function: SELECT f(1)
case function(@Sendable (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?)
case function((CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?)
/// An aggregate: SELECT f(foo) FROM bar GROUP BY baz
case aggregate(@Sendable () -> any DatabaseAggregate)
case aggregate(() -> any DatabaseAggregate)
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
+44 -21
View File
@@ -11,7 +11,7 @@ public final class DatabasePool {
/// It is constant, until close() sets it to nil.
private var readerPool: Pool<SerializedDatabase>?
let databaseSnapshotCountMutex = Mutex(0)
@LockedBox var databaseSnapshotCount = 0
/// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers.
private var suspensionObservers: [NSObjectProtocol] = []
@@ -62,15 +62,17 @@ public final class DatabasePool {
// an opened transaction.
readerConfiguration.allowsUnsafeTransactions = false
var readerCount = 0
readerPool = Pool(
maximumCount: configuration.maximumReaderCount,
qos: configuration.readQoS,
makeElement: { [readerConfiguration] index in
makeElement: {
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
return try SerializedDatabase(
path: path,
configuration: readerConfiguration,
defaultLabel: "GRDB.DatabasePool",
purpose: "reader.\(index)")
purpose: "reader.\(readerCount)")
})
// Set up journal mode unless readonly
@@ -116,6 +118,10 @@ 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
@@ -142,7 +148,7 @@ public final class DatabasePool {
}
}
// @unchecked because of readerPool and suspensionObservers
// @unchecked because of databaseSnapshotCount, readerPool and suspensionObservers
extension DatabasePool: @unchecked Sendable { }
extension DatabasePool {
@@ -251,9 +257,7 @@ extension DatabasePool {
// has freed its memory. That's better than nothing.
releaseMemoryEventually()
writer.async { _ in
DispatchQueue.main.async {
application.endBackgroundTask(task)
}
application.endBackgroundTask(task)
}
}
}
@@ -353,7 +357,7 @@ extension DatabasePool: DatabaseReader {
}
}
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
@@ -397,7 +401,7 @@ extension DatabasePool: DatabaseReader {
}
}
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
@@ -442,7 +446,25 @@ extension DatabasePool: DatabaseReader {
}
}
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
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) {
asyncConcurrentRead(value)
}
@@ -483,7 +505,7 @@ extension DatabasePool: DatabaseReader {
/// ```
///
/// - parameter value: A function that accesses the database.
public func asyncConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
// Check that we're on the writer queue...
writer.execute { db in
// ... and that no transaction is opened.
@@ -622,7 +644,8 @@ extension DatabasePool: DatabaseReader {
// MARK: - WAL Snapshot Transactions
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
/// Returns a long-lived WAL snapshot transaction on a reader connection.
func walSnapshotTransaction() throws -> WALSnapshotTransaction {
guard let readerPool else {
@@ -642,7 +665,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 @Sendable (Result<WALSnapshotTransaction, Error>) -> Void) {
func asyncWALSnapshotTransaction(_ completion: @escaping (Result<WALSnapshotTransaction, Error>) -> Void) {
guard let readerPool else {
completion(.failure(DatabaseError.connectionIsClosed()))
return
@@ -733,7 +756,7 @@ extension DatabasePool: DatabaseWriter {
}
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
guard let readerPool else {
updates(.failure(DatabaseError.connectionIsClosed()))
return
@@ -765,10 +788,9 @@ extension DatabasePool: DatabaseWriter {
///
/// - precondition: This method is not reentrant.
/// - parameters:
/// - kind: The transaction type (default nil).
///
/// If nil, the transaction kind is DEFERRED when the database
/// connection is read-only, and IMMEDIATE otherwise.
/// - kind: The transaction type (default nil). If nil, the transaction
/// type is the ``Configuration/defaultTransactionKind`` of the
/// the ``configuration``.
/// - updates: A function that updates the database.
/// - throws: The error thrown by `updates`, or by the wrapping transaction.
public func writeInTransaction(
@@ -787,7 +809,7 @@ extension DatabasePool: DatabaseWriter {
try writer.reentrantSync(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
writer.async(updates)
}
}
@@ -845,10 +867,11 @@ extension DatabasePool {
path: path,
configuration: DatabasePool.readerConfiguration(writer.configuration),
defaultLabel: "GRDB.DatabasePool",
purpose: "snapshot.\(databaseSnapshotCountMutex.increment())")
purpose: "snapshot.\($databaseSnapshotCount.increment())")
}
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
/// 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, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public enum DatabasePublishers { }
#endif
+22 -12
View File
@@ -169,9 +169,7 @@ extension DatabaseQueue {
// Release memory asynchronously
writer.async { db in
db.releaseMemory()
DispatchQueue.main.async {
application.endBackgroundTask(task)
}
application.endBackgroundTask(task)
}
}
}
@@ -235,7 +233,7 @@ extension DatabaseQueue: DatabaseReader {
}
}
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
writer.async { db in
defer {
// Ignore error because we can not notify it.
@@ -260,7 +258,7 @@ extension DatabaseQueue: DatabaseReader {
try writer.sync(value)
}
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
writer.async { value(.success($0)) }
}
@@ -268,7 +266,20 @@ extension DatabaseQueue: DatabaseReader {
try writer.reentrantSync(value)
}
public func spawnConcurrentRead(_ value: (Result<Database, Error>) -> Void) {
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) {
// Check that we're on the writer queue...
writer.execute { db in
// ... and that no transaction is opened.
@@ -341,10 +352,9 @@ extension DatabaseQueue: DatabaseWriter {
/// ```
///
/// - parameters:
/// - kind: The transaction type (default nil).
///
/// If nil, the transaction kind is DEFERRED when the database
/// connection is read-only, and IMMEDIATE otherwise.
/// - kind: The transaction type (default nil). If nil, the transaction
/// type is the ``Configuration/defaultTransactionKind`` of the
/// the ``configuration``.
/// - updates: A function that updates the database.
/// - throws: The error thrown by `updates`, or by the wrapping transaction.
public func inTransaction(
@@ -369,7 +379,7 @@ extension DatabaseQueue: DatabaseWriter {
try writer.sync(updates)
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
writer.async { updates(.success($0)) }
}
@@ -415,7 +425,7 @@ extension DatabaseQueue: DatabaseWriter {
try writer.reentrantSync(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
writer.async(updates)
}
}
+22 -20
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 @Sendable (Result<Database, Error>) -> Void)
func asyncRead(_ value: @escaping (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 @Sendable (Result<Database, Error>) -> Void)
func asyncUnsafeRead(_ value: @escaping (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, *)
public func read<T>(_ value: @escaping @Sendable (Database) throws -> T) async throws -> T {
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func read<T>(_ value: @Sendable @escaping (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, *)
public func unsafeRead<T>(_ value: @escaping @Sendable (Database) throws -> T) async throws -> T {
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func unsafeRead<T>(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T {
try await withUnsafeThrowingContinuation { continuation in
asyncUnsafeRead { result in
do {
@@ -549,15 +549,17 @@ extension DatabaseReader {
///
/// - parameter scheduler: A Combine Scheduler.
/// - parameter value: A closure which accesses the database.
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func readPublisher<Output>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
value: @escaping @Sendable (Database) throws -> Output)
value: @escaping (Database) throws -> Output)
-> DatabasePublishers.Read<Output>
{
OnDemandFuture { fulfill in
self.asyncRead { dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db) } })
Deferred {
Future { fulfill in
self.asyncRead { dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db) } })
}
}
}
.receiveValues(on: scheduler)
@@ -565,7 +567,7 @@ extension DatabaseReader {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
extension DatabasePublishers {
/// A publisher that reads from the database.
///
@@ -584,7 +586,7 @@ extension DatabasePublishers {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
extension Publisher where Failure == Error {
fileprivate func eraseToReadPublisher() -> DatabasePublishers.Read<Output> {
.init(upstream: eraseToAnyPublisher())
@@ -618,16 +620,16 @@ extension DatabaseReader {
}
return AnyDatabaseCancellable(cancel: { /* nothing to cancel */ })
} else {
let cancellable = AnyDatabaseCancellable()
var isCancelled = false
asyncRead { dbResult in
if cancellable.isCancelled { return }
guard !isCancelled else { return }
let result = dbResult.flatMap { db in
Result { try observation.fetchInitialValue(db) }
}
scheduler.schedule {
if cancellable.isCancelled { return }
guard !isCancelled else { return }
do {
try onChange(result.get())
} catch {
@@ -635,7 +637,7 @@ extension DatabaseReader {
}
}
}
return cancellable
return AnyDatabaseCancellable(cancel: { isCancelled = true })
}
}
}
@@ -676,7 +678,7 @@ extension AnyDatabaseReader: DatabaseReader {
try base.read(value)
}
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
base.asyncRead(value)
}
@@ -685,7 +687,7 @@ extension AnyDatabaseReader: DatabaseReader {
try base.unsafeRead(value)
}
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
base.asyncUnsafeRead(value)
}
@@ -756,7 +758,7 @@ extension DatabaseSnapshotReader {
}
// There is no such thing as an unsafe access to a snapshot.
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
asyncRead(value)
}
}
+8 -8
View File
@@ -89,16 +89,16 @@ extension DatabaseRegionObservation {
onChange: @escaping (Database) -> Void)
-> AnyDatabaseCancellable
{
let stateMutex = Mutex(ObservationState.pending)
@LockedBox var state = 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)
stateMutex.withLock { state in
$state.update {
let observer = DatabaseRegionObserver(region: region, onChange: {
if case .cancelled = stateMutex.value {
if case .cancelled = state {
return
}
onChange($0)
@@ -111,7 +111,7 @@ extension DatabaseRegionObservation {
// the observer.
db.add(transactionObserver: observer, extent: .observerLifetime)
state = .started(observer)
$0 = .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.
stateMutex.value = .cancelled
state = .cancelled
}
}
}
#if canImport(Combine)
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
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, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
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, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
extension DatabasePublishers {
/// A publisher that tracks transactions that modify a database region.
///
+6 -2
View File
@@ -126,6 +126,10 @@ 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
@@ -150,7 +154,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
try reader.sync(block)
}
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
reader.async { value(.success($0)) }
}
@@ -158,7 +162,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
try reader.sync(value)
}
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
reader.async { value(.success($0)) }
}
+19 -20
View File
@@ -1,13 +1,5 @@
#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
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
/// A database connection that allows concurrent accesses to an unchanging
/// database content, as it existed at the moment the snapshot was created.
///
@@ -130,7 +122,6 @@ 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
@@ -139,7 +130,7 @@ public final class DatabaseSnapshotPool {
}
var holderConfig = Configuration()
holderConfig.allowsUnsafeTransactions = true
snapshotHolder = try DatabaseQueue(path: path, configuration: holderConfig)
snapshotHolder = try DatabaseQueue(path: db.path, configuration: holderConfig)
try snapshotHolder.inDatabase { db in
try db.beginTransaction(.deferred)
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
@@ -159,18 +150,20 @@ public final class DatabaseSnapshotPool {
}
self.configuration = configuration
self.path = path
self.path = db.path
self.walSnapshot = walSnapshot
var readerCount = 0
readerPool = Pool(
maximumCount: configuration.maximumReaderCount,
qos: configuration.readQoS,
makeElement: { [configuration] index in
makeElement: {
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
return try SerializedDatabase(
path: path,
path: db.path,
configuration: configuration,
defaultLabel: "GRDB.DatabaseSnapshotPool",
purpose: "snapshot.\(index)")
purpose: "snapshot.\(readerCount)")
})
}
@@ -218,15 +211,17 @@ public final class DatabaseSnapshotPool {
self.path = path
self.walSnapshot = walSnapshot
var readerCount = 0
readerPool = Pool(
maximumCount: configuration.maximumReaderCount,
qos: configuration.readQoS,
makeElement: { [configuration] index in
makeElement: {
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
return try SerializedDatabase(
path: path,
configuration: configuration,
defaultLabel: "GRDB.DatabaseSnapshotPool",
purpose: "snapshot.\(index)")
purpose: "snapshot.\(readerCount)")
})
}
@@ -239,6 +234,10 @@ 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
@@ -293,7 +292,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
}
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
@@ -318,7 +317,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
return try reader.reentrantSync { db in
let result = try value(db)
if snapshotIsLost(db) {
throw DatabaseError.snapshotIsLost()
throw DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.")
}
return result
}
-9
View File
@@ -1,12 +1,3 @@
// 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.
+39 -13
View File
@@ -129,20 +129,45 @@ extension DatabaseValueConvertible {
// MARK: - Conversions
extension DatabaseValueConvertible {
@inlinable
public static func _decode(
databaseValue: DatabaseValue,
context: @autoclosure () -> _RowDecodingContext
) throws -> Self {
if let value = fromDatabaseValue(databaseValue) {
static func decode(
fromDatabaseValue dbValue: DatabaseValue,
context: @autoclosure () -> RowDecodingContext)
throws -> Self
{
if let value = fromDatabaseValue(dbValue) {
return value
} else {
throw RowDecodingError.valueMismatch(
Self.self,
context: context(),
databaseValue: databaseValue)
throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue)
}
}
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
@@ -190,9 +215,10 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
}
public func _element(sqliteStatement: SQLiteStatement) throws -> Value {
try Value._decode(
databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: columnIndex),
context: _RowDecodingContext(statement: _statement, index: Int(columnIndex)))
try Value.decode(
fromStatement: sqliteStatement,
atUncheckedIndex: columnIndex,
context: RowDecodingContext(statement: _statement, index: Int(columnIndex)))
}
}
+122 -31
View File
@@ -38,7 +38,9 @@ import Dispatch
///
/// ### Reading from the Latest Committed Database State
///
/// - ``concurrentRead(_:)``
/// - ``spawnConcurrentRead(_:)``
/// - ``DatabaseFuture``
///
/// ### Unsafe Methods
///
@@ -179,7 +181,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 @Sendable (Result<Database, Error>) -> Void)
func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void)
/// Schedules database operations for execution, and returns immediately.
///
@@ -211,7 +213,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 @Sendable (Database) -> Void)
func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -249,6 +251,49 @@ 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.
///
@@ -295,7 +340,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 @Sendable (Result<Database, Error>) -> Void)
func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void)
}
extension DatabaseWriter {
@@ -381,8 +426,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 @Sendable (Database) throws -> T,
completion: @escaping @Sendable (Database, Result<T, Error>) -> Void)
_ updates: @escaping (Database) throws -> T,
completion: @escaping (Database, Result<T, Error>) -> Void)
{
asyncWriteWithoutTransaction { db in
do {
@@ -496,7 +541,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, *)
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *)
public func vacuum(into filePath: String) throws {
try writeWithoutTransaction {
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
@@ -562,8 +607,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, *)
public func write<T>(_ updates: @escaping @Sendable (Database) throws -> T) async throws -> T {
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func write<T>(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T {
try await withUnsafeThrowingContinuation { continuation in
asyncWrite(updates, completion: { _, result in
continuation.resume(with: result)
@@ -600,8 +645,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, *)
public func writeWithoutTransaction<T>(_ updates: @escaping @Sendable (Database) throws -> T) async throws -> T {
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func writeWithoutTransaction<T>(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T {
try await withUnsafeThrowingContinuation { continuation in
asyncWriteWithoutTransaction { db in
do {
@@ -652,9 +697,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, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func barrierWriteWithoutTransaction<T>(
_ updates: @escaping @Sendable (Database) throws -> T)
_ updates: @Sendable @escaping (Database) throws -> T)
async throws -> T
{
try await withUnsafeThrowingContinuation { continuation in
@@ -667,7 +712,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, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func erase() async throws {
try await writeWithoutTransaction { try $0.erase() }
}
@@ -678,7 +723,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, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func vacuum() async throws {
try await writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
}
@@ -695,7 +740,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, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func vacuum(into filePath: String) async throws {
try await writeWithoutTransaction {
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
@@ -710,7 +755,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, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func vacuum(into filePath: String) async throws {
try await writeWithoutTransaction {
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
@@ -755,10 +800,10 @@ extension DatabaseWriter {
///
/// - parameter scheduler: A Combine Scheduler.
/// - parameter updates: A closure which accesses the database.
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func writePublisher<Output>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
updates: @escaping @Sendable (Database) throws -> Output)
updates: @escaping (Database) throws -> Output)
-> DatabasePublishers.Write<Output>
{
OnDemandFuture { fulfill in
@@ -772,7 +817,6 @@ 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
@@ -821,13 +865,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, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func writePublisher<S, T, Output>(
receiveOn scheduler: S = DispatchQueue.main,
updates: @escaping @Sendable (Database) throws -> T,
thenRead value: @escaping @Sendable (Database, T) throws -> Output)
updates: @escaping (Database) throws -> T,
thenRead value: @escaping (Database, T) throws -> Output)
-> DatabasePublishers.Write<Output>
where S: Scheduler, T: Sendable
where S: Scheduler
{
OnDemandFuture { fulfill in
self.asyncWriteWithoutTransaction { db in
@@ -841,7 +885,7 @@ extension DatabaseWriter {
fulfill(.failure(error))
return
}
self.spawnConcurrentRead { [updatesValue] dbResult in
self.spawnConcurrentRead { dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db, updatesValue!) } })
}
}
@@ -853,7 +897,7 @@ extension DatabaseWriter {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
extension DatabasePublishers {
/// A publisher that writes into the database.
///
@@ -872,7 +916,7 @@ extension DatabasePublishers {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
extension Publisher where Failure == Error {
fileprivate func eraseToWritePublisher() -> DatabasePublishers.Write<Output> {
.init(upstream: self.eraseToAnyPublisher())
@@ -880,6 +924,49 @@ 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
@@ -916,7 +1003,7 @@ extension AnyDatabaseWriter: DatabaseReader {
try base.read(value)
}
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
base.asyncRead(value)
}
@@ -925,7 +1012,7 @@ extension AnyDatabaseWriter: DatabaseReader {
try base.unsafeRead(value)
}
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
base.asyncUnsafeRead(value)
}
@@ -957,11 +1044,11 @@ extension AnyDatabaseWriter: DatabaseWriter {
try base.barrierWriteWithoutTransaction(updates)
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
base.asyncBarrierWriteWithoutTransaction(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
base.asyncWriteWithoutTransaction(updates)
}
@@ -969,7 +1056,11 @@ extension AnyDatabaseWriter: DatabaseWriter {
try base.unsafeReentrantWrite(updates)
}
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
base.concurrentRead(value)
}
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
base.spawnConcurrentRead(value)
}
}
-8
View File
@@ -1,8 +0,0 @@
//#warning("TODO: document")
//struct DetachedRow {
//
//}
//
//extension DetachedRow: Row {
//
//}
+973 -127
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: some RowProtocol) {
/// init(row: Row) {
/// player = row["player"]
/// team = row["team"]
/// }
@@ -318,7 +318,7 @@ extension Statement: _RowLayout {
/// - ``RenameColumnAdapter``
/// - ``ScopeAdapter``
/// - ``SuffixRowAdapter``
public protocol RowAdapter: Sendable {
public protocol RowAdapter {
/// 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: @Sendable (String) -> String
let transform: (String) -> String
/// Creates a `RenameColumnAdapter` adapter that renames columns according to the
/// provided transform function.
public init(_ transform: @escaping @Sendable (String) -> String) {
public init(_ transform: @escaping (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 base._fastDecode(Value.self, atUncheckedIndex: mappedIndex)
return try Value.fastDecode(fromRow: base, atUncheckedIndex: mappedIndex)
}
func withUnsafeData<T>(atUncheckedIndex index: Int, _ body: (Data?) throws -> T) throws -> T {
+33 -23
View File
@@ -1,14 +1,6 @@
// 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
public enum _RowKey: Hashable, Sendable {
@usableFromInline
enum RowKey: Hashable, Sendable {
/// A column name
case columnName(String)
@@ -37,7 +29,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?
@@ -45,7 +37,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
@@ -54,7 +46,7 @@ enum RowDecodingError: Error {
}
}
case keyNotFound(_RowKey, Context)
case keyNotFound(RowKey, Context)
case valueMismatch(Any.Type, Context)
var context: Context {
@@ -67,10 +59,9 @@ 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
{
@@ -88,7 +79,7 @@ enum RowDecodingError: Error {
_ type: Any.Type,
sqliteStatement: SQLiteStatement,
index: CInt,
context: _RowDecodingContext)
context: RowDecodingContext)
-> Self
{
valueMismatch(
@@ -107,14 +98,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: """
@@ -123,20 +114,39 @@ enum RowDecodingError: Error {
}
}
public struct _RowDecodingContext {
@usableFromInline
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?
}
extension _RowDecodingContext {
@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
}
}
/// 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: Sendable {
public struct SQL {
/// `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 {
nonisolated(unsafe) private static let watchDogKey = DispatchSpecificKey<SchedulingWatchdog>()
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 @Sendable (Database) -> Void) {
func async(_ block: @escaping (Database) -> Void) {
queue.async {
block(self.db)
self.preconditionNoUnsafeTransactionLeft(self.db)
+1 -10
View File
@@ -1,12 +1,3 @@
// 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.
@@ -146,7 +137,7 @@ public final class Statement {
database.sqliteConnection, statementStart, -1, prepFlags,
&sqliteStatement, statementEnd)
#else
if #available(macOS 10.14, *) { // SQLite 3.20+
if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { // SQLite 3.20+
code = sqlite3_prepare_v3(
database.sqliteConnection, statementStart, -1, prepFlags,
&sqliteStatement, statementEnd)
-9
View File
@@ -1,12 +1,3 @@
// 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
+58 -26
View File
@@ -1,12 +1,3 @@
// 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.
///
@@ -32,7 +23,7 @@ import SQLite3
/// var name: String
/// var score: Int
///
/// init(row: some RowProtocol) {
/// init(row: Row) {
/// // Optimized
/// name = row["name"]
/// score = row["score"]
@@ -136,21 +127,62 @@ extension StatementColumnConvertible {
// MARK: - Conversions
extension StatementColumnConvertible {
@inlinable
public static func _fastDecode(
sqliteStatement: SQLiteStatement,
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
@usableFromInline
/* private */ static func _valueMismatch(
fromStatement sqliteStatement: SQLiteStatement,
atUncheckedIndex index: CInt,
context: @autoclosure () -> _RowDecodingContext
) throws -> Self {
guard let value = fromStatement(sqliteStatement, atUncheckedIndex: index) else {
throw RowDecodingError.valueMismatch(
Self.self,
sqliteStatement: sqliteStatement,
index: index,
context: context())
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)))
}
return value
// 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)
}
}
@@ -202,10 +234,10 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
@inlinable
public func _element(sqliteStatement: SQLiteStatement) throws -> Value {
try Value._fastDecode(
sqliteStatement: sqliteStatement,
try Value.fastDecode(
fromStatement: sqliteStatement,
atUncheckedIndex: columnIndex,
context: _RowDecodingContext(statement: _statement, index: Int(columnIndex)))
context: RowDecodingContext(statement: _statement, index: Int(columnIndex)))
}
}
-152
View File
@@ -1,152 +0,0 @@
#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()]
}
}
+24 -9
View File
@@ -1,12 +1,3 @@
// 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.
@@ -69,3 +60,27 @@ 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,12 +1,3 @@
// 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,12 +1,3 @@
// 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,13 +1,4 @@
#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,12 +1,3 @@
// 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,12 +1,3 @@
// 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,12 +1,3 @@
// 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: Sendable {
public protocol TransactionClock {
/// 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 @Sendable (Database) throws -> Date) -> Self {
public static func custom(_ now: @escaping (Database) throws -> Date) -> Self {
CustomTransactionClock(now)
}
}
@@ -53,9 +53,9 @@ public struct DefaultTransactionClock: TransactionClock {
/// A custom transaction clock.
public struct CustomTransactionClock: TransactionClock {
let _now: @Sendable (Database) throws -> Date
let _now: (Database) throws -> Date
public init(_ now: @escaping @Sendable (Database) throws -> Date) {
public init(_ now: @escaping (Database) throws -> Date) {
self._now = now
}
-9
View File
@@ -1,12 +1,3 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
extension Database {
// MARK: - Database Observation
+2 -10
View File
@@ -1,13 +1,5 @@
#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
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
/// An instance of WALSnapshot records the state of a WAL mode database for some
/// specific point in history.
///
+26 -57
View File
@@ -1,30 +1,12 @@
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
/// A long-live read-only WAL transaction.
///
/// `WALSnapshotTransaction` **takes ownership** of its reader
/// `SerializedDatabase` (TODO: make it a move-only type eventually).
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?>
class WALSnapshotTransaction {
private let reader: SerializedDatabase
private let release: (_ isInsideTransaction: Bool) -> Void
/// The state of the database at the beginning of the transaction.
let walSnapshot: WALSnapshot
@@ -55,11 +37,10 @@ final class WALSnapshotTransaction: @unchecked Sendable {
/// is no longer used.
init(
onReader reader: SerializedDatabase,
release: @escaping @Sendable (_ isInsideTransaction: Bool) -> Void)
release: @escaping (_ 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
@@ -70,56 +51,44 @@ final class WALSnapshotTransaction: @unchecked Sendable {
try db.clearSchemaCacheIfNeeded()
return try WALSnapshot(db)
}
self.databaseAccessMutex = Mutex(databaseAccess)
self.reader = reader
self.release = release
} catch {
// self is not initialized, so deinit will not run.
databaseAccess.commitAndRelease()
Self.commitAndRelease(reader: reader, release: release)
throw error
}
}
deinit {
close()
Self.commitAndRelease(reader: reader, release: release)
}
/// Executes database operations in the snapshot transaction, and
/// returns their result after they have finished executing.
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)
}
func read<T>(_ value: (Database) throws -> T) rethrows -> T {
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
try reader.sync(value)
}
/// Schedules database operations for execution, and
/// returns immediately.
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))
}
}
func asyncRead(_ value: @escaping (Database) -> Void) {
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
reader.async(value)
}
func close() {
databaseAccessMutex.withLock { databaseAccess in
databaseAccess?.commitAndRelease()
databaseAccess = nil
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
}
release(isInsideTransaction)
}
}
#endif
+27 -2
View File
@@ -277,7 +277,31 @@ let newPlayerCount = try dbPool.write { db in
}
```
🔀 The solution is ``DatabasePool/asyncConcurrentRead(_:)``. It must be called from within a write access, outside of any transaction:
➡️ 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(_:)``:
```swift
try dbPool.writeWithoutTransaction { db in
@@ -300,10 +324,11 @@ try dbPool.writeWithoutTransaction { db in
}
```
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.
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.
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.
+2 -1
View File
@@ -152,11 +152,12 @@ 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)
```
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.
Both the `defaultTransactionKind` and `busyMode` are important for preventing `SQLITE_BUSY`. The `immediate` transaction kind prevents write transactions from overlapping, and the busy timeout has write transactions wait, instead of throwing `SQLITE_BUSY`, whenever another process is writing.
With such a setup, you will still get `SQLITE_BUSY` errors if the database remains locked by another process for longer than the specified timeout. You can catch those errors:
@@ -90,6 +90,7 @@ 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:bufferingPolicy:)``
- ``values(in:scheduling:bufferingPolicy:)``
- ``DatabaseCancellable``
- ``ValueObservationScheduler``
+1
View File
@@ -147,4 +147,5 @@ The `->` and `->>` SQL operators are available on the ``SQLJSONExpressible`` pro
### Validate JSON values at the SQL level
- ``Database/jsonErrorPosition(_:)``
- ``Database/jsonIsValid(_:)``
+17 -2
View File
@@ -214,8 +214,6 @@ 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
@@ -224,3 +222,20 @@ 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,12 +1,3 @@
// 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
+1 -10
View File
@@ -1,12 +1,3 @@
// 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.
@@ -52,7 +43,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, *) {
if #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) {
encoder.outputFormatting = .withoutEscapingSlashes
}
encoder.nonConformingFloatEncodingStrategy = .convertToString(
@@ -1,12 +1,3 @@
// 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,12 +1,3 @@
// 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,12 +1,3 @@
// 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
@@ -0,0 +1,8 @@
// 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, *) // SQLite 3.27+
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.27+
case remove
#endif
}
+2 -11
View File
@@ -1,13 +1,4 @@
#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.
@@ -69,7 +60,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, *) // SQLite 3.27+
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.27+
case remove
#endif
}
@@ -130,7 +121,7 @@ public struct FTS5 {
return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer)
#else
// GRDB is linked against the system SQLite.
if #available(macOS 10.14, *) { // SQLite 3.20+
if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { // SQLite 3.20+
return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer)
} else {
return api_v1(db)
-9
View File
@@ -1,13 +1,4 @@
#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,13 +1,4 @@
#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,13 +1,4 @@
#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, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
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, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
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, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
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() }
+15
View File
@@ -521,6 +521,21 @@ extension Database {
.function("JSON_ARRAY_LENGTH", [value.sqlExpression, path.sqlExpression])
}
/// The `JSON_ERROR_POSITION` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_ERROR_POSITION(info)
/// Database.jsonErrorPosition(Column("info"))
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jerr>
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func jsonErrorPosition(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_ERROR_POSITION", [value.sqlExpression])
}
/// The `JSON_EXTRACT` SQL function.
///
/// For example:
+5 -5
View File
@@ -40,7 +40,7 @@ import Foundation
/// - ``completedMigrations(_:)``
/// - ``hasBeenSuperseded(_:)``
/// - ``hasCompletedMigrations(_:)``
public struct DatabaseMigrator: Sendable {
public struct DatabaseMigrator {
/// 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: Sendable {
public mutating func registerMigration(
_ identifier: String,
foreignKeyChecks: ForeignKeyChecks = .deferred,
migrate: @escaping @Sendable (Database) throws -> Void)
migrate: @escaping (Database) throws -> Void)
{
let migrationChecks: Migration.ForeignKeyChecks
switch foreignKeyChecks {
@@ -264,7 +264,7 @@ public struct DatabaseMigrator: Sendable {
/// from succeeding.
public func asyncMigrate(
_ writer: some DatabaseWriter,
completion: @escaping @Sendable (Result<Database, Error>) -> Void)
completion: @escaping (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, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
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, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
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: Sendable {
struct Migration {
enum ForeignKeyChecks {
case deferred
case immediate
@@ -8,7 +8,7 @@ struct Migration: Sendable {
let identifier: String
var foreignKeyChecks: ForeignKeyChecks
let migrate: @Sendable (Database) throws -> Void
let migrate: (Database) throws -> Void
func run(_ db: Database) throws {
if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false {
@@ -835,7 +835,7 @@ extension AssociationAggregate {
}
}
// MARK: - Functions
// MARK: - IFNULL(...)
extension AssociationAggregate {
/// The `IFNULL` SQL function.
@@ -854,6 +854,8 @@ extension AssociationAggregate {
}
}
// MARK: - ABS(...)
/// The `ABS` SQL function.
public func abs<RowDecoder>(_ aggregate: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
@@ -861,18 +863,7 @@ public func abs<RowDecoder>(_ aggregate: AssociationAggregate<RowDecoder>)
aggregate.map(abs)
}
/// The `CAST` SQL function.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_expr.html#castexpr>
public func cast<RowDecoder>(
_ aggregate: AssociationAggregate<RowDecoder>,
as storageClass: Database.StorageClass)
-> AssociationAggregate<RowDecoder>
{
aggregate
.map { cast($0, as: storageClass) }
.with { $0.key = aggregate.key } // Preserve key
}
// MARK: - LENGTH(...)
/// The `LENGTH` SQL function.
public func length<RowDecoder>(_ aggregate: AssociationAggregate<RowDecoder>)
@@ -583,7 +583,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
extension TableRequest
where Self: FilteredRequest,
Self: TypedRequest,
@@ -23,7 +23,7 @@
/// see SQLRelation.filterPromise.
struct DatabasePromise<T> {
/// Returns the resolved value.
let resolve: @Sendable (Database) throws -> T
let resolve: (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 @Sendable (Database) throws -> T) {
init(_ resolve: @escaping (Database) throws -> T) {
self.resolve = resolve
}
/// Returns a promise whose value is transformed by the given closure.
func map<U>(_ transform: @escaping @Sendable (T) throws -> U) -> DatabasePromise<U> {
func map<U>(_ transform: @escaping (T) throws -> U) -> DatabasePromise<U> {
DatabasePromise<U> { db in
try transform(resolve(db))
}
+4 -25
View File
@@ -34,7 +34,7 @@
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_expr.html>
public struct SQLExpression: Sendable {
public struct SQLExpression {
private var impl: Impl
/// The preferred interpretation of the expression in JSON
@@ -90,11 +90,6 @@ public struct SQLExpression: Sendable {
/// A literal SQL expression
case literal(SQL)
/// The `CAST(expr AS storage-class)` expression.
///
/// See <https://www.sqlite.org/lang_expr.html#castexpr>.
indirect case cast(SQLExpression, Database.StorageClass)
/// The `BETWEEN` and `NOT BETWEEN` operators.
///
/// <expression> BETWEEN <lowerBound> AND <upperBound>
@@ -229,9 +224,6 @@ public struct SQLExpression: Sendable {
case let .literal(sqlLiteral):
return .literal(sqlLiteral.qualified(with: alias))
case let .cast(expression, storageClass):
return .cast(expression.qualified(with: alias), storageClass)
case let .between(
expression: expression,
lowerBound: lowerBound,
@@ -1100,13 +1092,6 @@ extension SQLExpression {
self.init(impl: .isEmpty(expression, isNegated: isNegated))
}
/// The `CAST(expr AS storage-class)` expression.
///
/// See <https://www.sqlite.org/lang_expr.html#castexpr>.
static func cast(_ expression: SQLExpression, as storageClass: Database.StorageClass) -> Self {
self.init(impl: .cast(expression, storageClass))
}
// MARK: Deferred
// TODO: replace with something that can work for WITHOUT ROWID table with a multi-columns primary key.
@@ -1284,9 +1269,6 @@ extension SQLExpression {
}
return resultSQL
case let .cast(expression, storageClass):
return try "CAST(\(expression.sql(context, wrappedInParenthesis: false)) AS \(storageClass.rawValue))"
case let .between(expression: expression, lowerBound: lowerBound, upperBound: upperBound, isNegated: isNegated):
var resultSQL = try """
\(expression.sql(context, wrappedInParenthesis: true)) \
@@ -1840,9 +1822,6 @@ extension SQLExpression {
let .associativeBinary(_, expressions):
return expressions.allSatisfy(\.isConstantInRequest)
case let .cast(expression, _):
return expression.isConstantInRequest
case let .between(expression: expression, lowerBound: lowerBound, upperBound: upperBound, isNegated: _):
return expression.isConstantInRequest
&& lowerBound.isConstantInRequest
@@ -1989,7 +1968,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, *) SQLite 3.30+
var filter: SQLExpression? = nil // @available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) SQLite 3.30+
/// A boolean value indicating if a function is known to return a
/// JSON value.
@@ -2328,13 +2307,13 @@ extension SQLSpecificExpressible {
}
#elseif !GRDBCIPHER
/// An ordering term for ascending order (nulls last).
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // 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, *) // SQLite 3.30+
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
public var descNullsFirst: SQLOrdering {
.descNullsFirst(sqlExpression)
}
+5 -19
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, *) // SQLite 3.30+
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
public func average(
_ value: some SQLSpecificExpressible,
filter: some SQLSpecificExpressible)
@@ -57,20 +57,6 @@ public func average(_ value: some SQLSpecificExpressible) -> SQLExpression {
}
#endif
/// The `CAST` SQL function.
///
/// For example:
///
/// ```swift
/// // CAST(value AS REAL)
/// cast(Column("value"), as: .real)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_expr.html#castexpr>
public func cast(_ expression: some SQLSpecificExpressible, as storageClass: Database.StorageClass) -> SQLExpression {
.cast(expression.sqlExpression, as: storageClass)
}
/// The `COUNT` SQL function.
///
/// For example:
@@ -145,7 +131,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, *) // SQLite 3.30+
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
public func max(
_ value: some SQLSpecificExpressible,
filter: some SQLSpecificExpressible)
@@ -190,7 +176,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, *) // SQLite 3.30+
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
public func min(
_ value: some SQLSpecificExpressible,
filter: some SQLSpecificExpressible)
@@ -248,7 +234,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, *) // SQLite 3.30+
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
public func sum(
_ value: some SQLSpecificExpressible,
filter: some SQLSpecificExpressible)
@@ -312,7 +298,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, *) // SQLite 3.30+
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // 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: Sendable {
public struct SQLOrdering {
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: Sendable {
struct SQLRelation {
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 @Sendable (Database) -> [SQLSelection] = { _ in [.allColumns] })
selection: @escaping (Database) -> [SQLSelection] = { _ in [.allColumns] })
-> Self
{
SQLRelation(
@@ -197,7 +197,7 @@ extension SQLRelation {
}
extension SQLRelation: Refinable {
func selectWhenConnected(_ selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self {
func selectWhenConnected(_ selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
with {
$0.selectionPromise = DatabasePromise(selection)
}
@@ -228,7 +228,7 @@ extension SQLRelation: Refinable {
}
}
func annotatedWhenConnected(with selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self {
func annotatedWhenConnected(with selection: @escaping (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 @Sendable (Database) throws -> SQLExpression) -> Self {
func filterWhenConnected(_ predicate: @escaping (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 @Sendable (Database) throws -> [SQLOrdering]) -> Self {
func orderWhenConnected(_ orderings: @escaping (Database) throws -> [SQLOrdering]) -> Self {
with {
$0.ordering = SQLRelation.Ordering(orderings: orderings)
}
@@ -313,13 +313,13 @@ extension SQLRelation: Refinable {
}
}
func groupWhenConnected(_ expressions: @escaping @Sendable (Database) throws -> [SQLExpression]) -> Self {
func groupWhenConnected(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self {
with {
$0.groupPromise = DatabasePromise(expressions)
}
}
func havingWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self {
func havingWhenConnected(_ predicate: @escaping (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: Sendable {
struct SQLSource {
var tableName: String
var alias: TableAlias?
@@ -691,7 +691,7 @@ struct SQLSource: Sendable {
extension SQLRelation {
/// SQLRelation.Ordering provides the order clause to SQLRelation.
struct Ordering: Sendable {
struct Ordering {
private enum Element {
case terms(DatabasePromise<[SQLOrdering]>)
case ordering(SQLRelation.Ordering)
@@ -740,7 +740,7 @@ extension SQLRelation {
isReversed: false)
}
init(orderings: @escaping @Sendable (Database) throws -> [SQLOrdering]) {
init(orderings: @escaping (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: Sendable {
public struct SQLSelection {
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: Sendable {
public struct SQLSubquery {
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, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
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, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
extension Table
where RowDecoder: Identifiable,
RowDecoder.ID: DatabaseValueConvertible
@@ -1688,7 +1688,7 @@ extension Table {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
extension Table
where RowDecoder: Identifiable,
RowDecoder.ID: DatabaseValueConvertible
@@ -213,9 +213,7 @@ 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: @unchecked Sendable {
// This Sendable conformance is transient. TableAlias IS NOT really Sendable.
// TODO: GRDB7 Make TableAlias really Sendable
public class TableAlias {
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, *) // SQLite 3.25+
@available(iOS 13, tvOS 13, watchOS 6, *) // 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, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
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: Sendable {
public enum DatabaseDataEncodingStrategy {
/// Encodes `Data` columns as SQL blob.
case deferredToData
@@ -474,7 +474,7 @@ public enum DatabaseDataEncodingStrategy: Sendable {
case text
/// Encodes `Data` column as the result of the user-provided function.
case custom(@Sendable (Data) -> (any DatabaseValueConvertible)?)
case custom((Data) -> (any DatabaseValueConvertible)?)
func encode(_ data: Data) -> DatabaseValue {
switch self {
@@ -508,7 +508,7 @@ public enum DatabaseDataEncodingStrategy: Sendable {
/// var creationDate: Date
/// }
/// ```
public enum DatabaseDateEncodingStrategy: Sendable {
public enum DatabaseDateEncodingStrategy {
/// 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: Sendable {
case formatted(DateFormatter)
/// Encodes the result of the user-provided function
case custom(@Sendable (Date) -> (any DatabaseValueConvertible)?)
case custom((Date) -> (any DatabaseValueConvertible)?)
private static let iso8601Formatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
@@ -585,7 +585,7 @@ public enum DatabaseDateEncodingStrategy: Sendable {
/// var uuid: UUID
/// }
/// ```
public enum DatabaseUUIDEncodingStrategy: Sendable {
public enum DatabaseUUIDEncodingStrategy {
/// The strategy that uses formatting from the UUID type.
///
/// It encodes UUIDs as 16-bytes data blobs.
@@ -626,7 +626,7 @@ public enum DatabaseUUIDEncodingStrategy: Sendable {
/// var playerID: String
/// }
/// ```
public enum DatabaseColumnEncodingStrategy: Sendable {
public enum DatabaseColumnEncodingStrategy {
/// A key encoding strategy that doesn’t change key names during encoding.
case useDefaultKeys
@@ -634,7 +634,7 @@ public enum DatabaseColumnEncodingStrategy: Sendable {
case convertToSnakeCase
/// A key encoding strategy defined by the closure you supply.
case custom(@Sendable (any CodingKey) -> String)
case custom((any CodingKey) -> String)
func column(forKey key: some CodingKey) -> String {
switch self {
+169 -84
View File
@@ -1,17 +1,8 @@
// 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: some RowProtocol) throws {
public init(row: Row) throws {
self = try FetchableRecordDecoder().decode(Self.self, from: row)
}
}
@@ -78,26 +69,17 @@ 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<RowType: RowProtocol, T: FetchableRecord & Decodable>(_ type: T.Type, from row: RowType) throws -> T {
let decoder = _RowDecoder<RowType, T>(row: row, codingPath: [], columnDecodingStrategy: T.databaseColumnDecodingStrategy)
public func decode<T: FetchableRecord & Decodable>(_ type: T.Type, from row: Row) throws -> T {
let decoder = _RowDecoder<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<RowType: RowProtocol, R: FetchableRecord>: Decoder {
var row: RowType
private struct _RowDecoder<R: FetchableRecord>: Decoder {
var row: Row
var codingPath: [CodingKey]
var columnDecodingStrategy: DatabaseColumnDecodingStrategy
var userInfo: [CodingUserInfoKey: Any] { R.databaseDecodingUserInfo }
@@ -127,17 +109,17 @@ private struct _RowDecoder<RowType: RowProtocol, 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<RowType, R>(row: row, columnIndex: 0, codingPath: codingPath)
return ColumnDecoder<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: row._makeRowDecodingContext(forKey: nil))
throw RowDecodingError.columnNotFound(key.stringValue, context: RowDecodingContext(row: row))
}
// TODO: test
// See DatabaseValueConversionErrorTests.testDecodableFetchableRecord2
return ColumnDecoder<RowType, R>(row: row, columnIndex: index, codingPath: codingPath)
return ColumnDecoder<R>(row: row, columnIndex: index, codingPath: codingPath)
}
class KeyedContainer<Key: CodingKey>: KeyedDecodingContainerProtocol {
@@ -257,12 +239,12 @@ private struct _RowDecoder<RowType: RowProtocol, 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: decoder.row._makeRowDecodingContext(forKey: nil),
decodingContext: RowDecodingContext(row: decoder.row),
debugDescription: "key not found: \(errorDescription)"))
}
@@ -279,18 +261,18 @@ private struct _RowDecoder<RowType: RowProtocol, R: FetchableRecord>: Decoder {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
if type == Data.self {
return try row._decodeIfPresent(
with: R.databaseDataDecodingStrategy,
return try R.databaseDataDecodingStrategy.decodeIfPresent(
fromRow: row,
atUncheckedIndex: index) as! T?
} else if type == Date.self {
return try row._decodeIfPresent(
with: R.databaseDateDecodingStrategy,
return try R.databaseDateDecodingStrategy.decodeIfPresent(
fromRow: row,
atUncheckedIndex: index) as! T?
} else if let type = T.self as? any (DatabaseValueConvertible & StatementColumnConvertible).Type {
return try row._fastDecodeIfPresent(type, atUncheckedIndex: index) as! T?
return try type.fastDecodeIfPresent(fromRow: row, atUncheckedIndex: index) as! T?
} else if let type = T.self as? any DatabaseValueConvertible.Type {
return try row._decodeIfPresent(type, atUncheckedIndex: index) as! T?
} else if row._hasNull(atUncheckedIndex: index) {
return try type.decodeIfPresent(fromRow: row, atUncheckedIndex: index) as! T?
} else if row.impl.hasNull(atUncheckedIndex: index) {
return nil
} else {
return try decode(type, fromRow: row, columnAtIndex: index, key: key)
@@ -328,13 +310,13 @@ private struct _RowDecoder<RowType: RowProtocol, R: FetchableRecord>: Decoder {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
if type == Data.self {
return try row._decode(with: R.databaseDataDecodingStrategy, atUncheckedIndex: index) as! T
return try R.databaseDataDecodingStrategy.decode(fromRow: row, atUncheckedIndex: index) as! T
} else if type == Date.self {
return try row._decode(with: R.databaseDateDecodingStrategy, atUncheckedIndex: index) as! T
return try R.databaseDateDecodingStrategy.decode(fromRow: row, atUncheckedIndex: index) as! T
} else if let type = T.self as? any (DatabaseValueConvertible & StatementColumnConvertible).Type {
return try row._fastDecode(type, atUncheckedIndex: index) as! T
return try type.fastDecode(fromRow: row, atUncheckedIndex: index) as! T
} else if let type = T.self as? any DatabaseValueConvertible.Type {
return try row._decode(type, atUncheckedIndex: index) as! T
return try type.decode(fromRow: row, atUncheckedIndex: index) as! T
} else {
return try decode(type, fromRow: row, columnAtIndex: index, key: key)
}
@@ -413,10 +395,9 @@ private struct _RowDecoder<RowType: RowProtocol, R: FetchableRecord>: Decoder {
// Helper methods
#warning("TODO: make NestedRowType concrete once it is settled")
private func decode<NestedRowType: RowProtocol, T>(
private func decode<T>(
_ type: T.Type,
fromRow row: NestedRowType,
fromRow row: Row,
codingPath: [CodingKey])
throws -> T
where T: Decodable
@@ -425,14 +406,14 @@ private struct _RowDecoder<RowType: RowProtocol, R: FetchableRecord>: Decoder {
// Prefer FetchableRecord decoding over Decodable.
return try type.init(row: row) as! T
} else {
let decoder = _RowDecoder<NestedRowType, NestedDecodingContext<R>>(row: row, codingPath: codingPath, columnDecodingStrategy: .useDefaultKeys)
let decoder = _RowDecoder(row: row, codingPath: codingPath, columnDecodingStrategy: .useDefaultKeys)
return try T(from: decoder)
}
}
private func decode<T>(
_ type: T.Type,
fromRow row: RowType,
fromRow row: Row,
columnAtIndex index: Int,
key: Key)
throws -> T
@@ -443,7 +424,7 @@ private struct _RowDecoder<RowType: RowProtocol, 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<RowType, R>(
let columnDecoder = ColumnDecoder<R>(
row: row,
columnIndex: index,
codingPath: codingPath + [key])
@@ -507,7 +488,7 @@ extension PrefetchedRowsDecoder: UnkeyedDecodingContainer {
columnDecodingStrategy = .useDefaultKeys
}
let decoder = _RowDecoder<Row, R>(
let decoder = _RowDecoder<R>(
row: rows[currentIndex],
codingPath: codingPath,
columnDecodingStrategy: columnDecodingStrategy)
@@ -533,8 +514,8 @@ extension PrefetchedRowsDecoder: UnkeyedDecodingContainer {
// MARK: - ColumnDecoder
/// The decoder that decodes from a database column
private struct ColumnDecoder<RowType: RowProtocol, R: FetchableRecord>: Decoder {
var row: RowType
private struct ColumnDecoder<R: FetchableRecord>: Decoder {
var row: Row
var columnIndex: Int
var codingPath: [CodingKey]
var userInfo: [CodingUserInfoKey: Any] { R.databaseDecodingUserInfo }
@@ -575,13 +556,13 @@ extension ColumnDecoder: SingleValueDecodingContainer {
func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
// TODO: not tested
if type == Data.self {
return try row._decode(with: R.databaseDataDecodingStrategy, atUncheckedIndex: columnIndex) as! T
return try R.databaseDataDecodingStrategy.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T
} else if type == Date.self {
return try row._decode(with: R.databaseDateDecodingStrategy, atUncheckedIndex: columnIndex) as! T
return try R.databaseDateDecodingStrategy.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T
} else if let type = T.self as? any (DatabaseValueConvertible & StatementColumnConvertible).Type {
return try row._fastDecode(type, atUncheckedIndex: columnIndex) as! T
return try type.fastDecode(fromRow: row, atUncheckedIndex: columnIndex) as! T
} else if let type = T.self as? any DatabaseValueConvertible.Type {
return try row._decode(type, atUncheckedIndex: columnIndex) as! T
return try type.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T
} else {
return try T(from: self)
}
@@ -594,12 +575,40 @@ private let iso8601Formatter: ISO8601DateFormatter = {
return formatter
}()
extension DatabaseDataDecodingStrategy: _RowDecodingStrategy {
public func _decode(
sqliteStatement: SQLiteStatement,
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 {
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,
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:
@@ -616,22 +625,46 @@ extension DatabaseDataDecodingStrategy: _RowDecodingStrategy {
}
}
public func _decode(
databaseValue: DatabaseValue,
context: @autoclosure () -> _RowDecodingContext
) throws -> Data {
if let data = decode(databaseValue) {
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) {
return data
} else {
throw RowDecodingError.valueMismatch(
Data.self,
context: context(),
databaseValue: databaseValue)
throw RowDecodingError.valueMismatch(Data.self, context: context(), databaseValue: dbValue)
}
}
/// Returns nil if decoding fails
private func decode(_ dbValue: DatabaseValue) -> Data? {
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? {
switch self {
case .deferredToData:
return Data.fromDatabaseValue(dbValue)
@@ -641,12 +674,40 @@ extension DatabaseDataDecodingStrategy: _RowDecodingStrategy {
}
}
extension DatabaseDateDecodingStrategy: _RowDecodingStrategy {
public func _decode(
sqliteStatement: SQLiteStatement,
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 {
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,
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:
@@ -696,22 +757,46 @@ extension DatabaseDateDecodingStrategy: _RowDecodingStrategy {
}
}
public func _decode(
databaseValue: DatabaseValue,
context: @autoclosure () -> _RowDecodingContext
) throws -> Date {
if let date = decode(databaseValue) {
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) {
return date
} else {
throw RowDecodingError.valueMismatch(
Date.self,
context: context(),
databaseValue: databaseValue)
throw RowDecodingError.valueMismatch(Date.self, context: context(), databaseValue: dbValue)
}
}
/// Returns nil if decoding fails
private func decode(_ dbValue: DatabaseValue) -> Date? {
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? {
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, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
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, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
extension FetchableRecord where Self: TableRecord & Hashable & Identifiable, ID: DatabaseValueConvertible {
/// Returns a set of records identified by their primary keys.
///
+7 -14
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: some RowProtocol) throws
init(row: Row) throws
// MARK: - Customizing the Format of Database Columns
@@ -260,13 +260,6 @@ 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
@@ -887,7 +880,7 @@ extension RecordCursor: Sendable { }
/// var myData: Data
/// }
/// ```
public enum DatabaseDataDecodingStrategy: Sendable {
public enum DatabaseDataDecodingStrategy {
/// Decodes `Data` columns from SQL blobs and UTF8 text.
case deferredToData
@@ -896,7 +889,7 @@ public enum DatabaseDataDecodingStrategy: Sendable {
/// 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(@Sendable (DatabaseValue) -> Data?)
case custom((DatabaseValue) -> Data?)
}
// MARK: - DatabaseDateDecodingStrategy
@@ -913,7 +906,7 @@ public enum DatabaseDataDecodingStrategy: Sendable {
/// var name: String
/// var registrationDate: Date // decoded from epoch timestamp
/// }
public enum DatabaseDateDecodingStrategy: Sendable {
public enum DatabaseDateDecodingStrategy {
/// The strategy that uses formatting from the Date structure.
///
/// It decodes numeric values as a number of seconds since Epoch
@@ -954,7 +947,7 @@ public enum DatabaseDateDecodingStrategy: Sendable {
/// 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(@Sendable (DatabaseValue) -> Date?)
case custom((DatabaseValue) -> Date?)
}
// MARK: - DatabaseColumnDecodingStrategy
@@ -971,7 +964,7 @@ public enum DatabaseDateDecodingStrategy: Sendable {
/// // Decoded from the player_id column
/// var playerID: Int
/// }
public enum DatabaseColumnDecodingStrategy: Sendable {
public enum DatabaseColumnDecodingStrategy {
/// A key decoding strategy that doesn’t change key names during decoding.
case useDefaultKeys
@@ -979,7 +972,7 @@ public enum DatabaseColumnDecodingStrategy: Sendable {
case convertFromSnakeCase
/// A key decoding strategy defined by the closure you supply.
case custom(@Sendable (String) -> CodingKey)
case custom((String) -> CodingKey)
func key<K: CodingKey>(forColumn column: String) -> K? {
switch self {
@@ -91,6 +91,7 @@ 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.
///
@@ -107,22 +108,22 @@ extension MutablePersistableRecord {
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The inserted record.
/// - returns: The inserted record, if any. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - 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.
///
@@ -160,10 +161,11 @@ extension MutablePersistableRecord {
/// var partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING *
/// 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
/// 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
/// }
/// }
/// ```
///
@@ -172,24 +174,19 @@ extension MutablePersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`.
/// - returns: A record of type `returnedType`, if any. The result can be
/// nil when the conflict policy is `IGNORE`.
/// - 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?
{
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)
try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
try T.fetchOne($0)
}
}
@@ -269,6 +266,7 @@ 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.
///
@@ -285,23 +283,23 @@ extension MutablePersistableRecord {
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The inserted record.
/// - returns: The inserted record, if any. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - 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.
///
@@ -339,10 +337,11 @@ extension MutablePersistableRecord {
/// var partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING *
/// 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
/// 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
/// }
/// }
/// ```
///
@@ -351,25 +350,20 @@ extension MutablePersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`.
/// - returns: A record of type `returnedType`, if any. The result can be
/// nil when the conflict policy is `IGNORE`.
/// - 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?
{
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)
try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
try T.fetchOne($0)
}
}
+20 -28
View File
@@ -87,6 +87,7 @@ 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.
///
@@ -106,22 +107,22 @@ extension MutablePersistableRecord {
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The saved record.
/// - returns: The saved record. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - 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.
///
@@ -134,31 +135,26 @@ extension MutablePersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - 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: {
if let result = try T.fetchOne($0) {
return result
}
throw record.recordNotFound(db)
try T.fetchOne($0)
})
return success!.saved
}
@@ -215,6 +211,7 @@ 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.
///
@@ -234,23 +231,23 @@ extension MutablePersistableRecord {
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The saved record.
/// - returns: The saved record. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - 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.
///
@@ -263,32 +260,27 @@ extension MutablePersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - 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: {
if let result = try T.fetchOne($0) {
return result
}
throw record.recordNotFound(db)
try T.fetchOne($0)
})
return success!.saved
}
@@ -218,6 +218,7 @@ 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.
///
@@ -225,23 +226,23 @@ extension MutablePersistableRecord {
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The updated record.
/// - returns: The updated record. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - 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.
///
@@ -250,28 +251,25 @@ extension MutablePersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - 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) {
if let result = try T.fetchOne($0) {
return result
}
throw recordNotFound(db)
try T.fetchOne($0)
}
}
// 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
@@ -282,13 +280,12 @@ 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.
/// - 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.
/// - 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,
@@ -300,6 +297,7 @@ 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
@@ -312,13 +310,12 @@ 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.
/// no change, or in case of a failed update due to the `IGNORE`
/// conflict policy.
/// - 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,
@@ -327,16 +324,10 @@ extension MutablePersistableRecord {
modify: (inout Self) throws -> Void)
throws -> T?
{
let record = self
return try updateChangesAndFetch(
try updateChangesAndFetch(
db, onConflict: conflictResolution,
selection: T.databaseSelection,
fetch: {
if let result = try T.fetchOne($0) {
return result
}
throw record.recordNotFound(db)
},
fetch: { try T.fetchOne($0) },
modify: modify)
}
@@ -491,6 +482,7 @@ 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
@@ -503,8 +495,7 @@ 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, or nil if the record
/// has no change.
/// - returns: The result of the `fetch` function.
/// - 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
@@ -515,7 +506,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?
{
@@ -528,6 +519,7 @@ 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.
///
@@ -535,19 +527,18 @@ extension MutablePersistableRecord {
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The updated record.
/// - returns: The updated record. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - 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)
@@ -561,29 +552,26 @@ extension MutablePersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - 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) {
if let result = try T.fetchOne($0) {
return result
}
throw recordNotFound(db)
try T.fetchOne($0)
}
}
// 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
@@ -594,13 +582,12 @@ 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.
/// - 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.
/// - 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(
@@ -613,6 +600,7 @@ 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
@@ -625,13 +613,12 @@ 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.
/// no change, or in case of a failed update due to the `IGNORE`
/// conflict policy.
/// - 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>(
@@ -641,16 +628,10 @@ extension MutablePersistableRecord {
modify: (inout Self) throws -> Void)
throws -> T?
{
let record = self
return try updateChangesAndFetch(
try updateChangesAndFetch(
db, onConflict: conflictResolution,
selection: T.databaseSelection,
fetch: {
if let result = try T.fetchOne($0) {
return result
}
throw record.recordNotFound(db)
},
fetch: { try T.fetchOne($0) },
modify: modify)
}
@@ -808,6 +789,7 @@ 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
@@ -820,8 +802,7 @@ 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, or nil if the record
/// has no change.
/// - returns: The result of the `fetch` function.
/// - 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
@@ -833,7 +814,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?
{
@@ -858,7 +839,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)
@@ -880,7 +861,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)
+20 -24
View File
@@ -56,6 +56,7 @@ 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.
///
@@ -93,10 +94,11 @@ extension PersistableRecord {
/// let partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING *
/// 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
/// 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
/// }
/// }
/// ```
///
@@ -105,23 +107,19 @@ extension PersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`.
/// - returns: A record of type `returnedType`, if any. The result can be
/// nil when the conflict policy is `IGNORE`.
/// - 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) {
if let result = try T.fetchOne($0) {
return result
}
throw recordNotFound(db)
try T.fetchOne($0)
}
}
@@ -201,6 +199,7 @@ 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.
///
@@ -238,10 +237,11 @@ extension PersistableRecord {
/// let partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING *
/// 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
/// 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
/// }
/// }
/// ```
///
@@ -250,24 +250,20 @@ extension PersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`.
/// - returns: A record of type `returnedType`, if any. The result can be
/// nil when the conflict policy is `IGNORE`.
/// - 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) {
if let result = try T.fetchOne($0) {
return result
}
throw recordNotFound(db)
try T.fetchOne($0)
}
}
+12 -18
View File
@@ -39,6 +39,7 @@ 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.
///
@@ -51,30 +52,26 @@ extension PersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - 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: {
if let result = try T.fetchOne($0) {
return result
}
throw recordNotFound(db)
try T.fetchOne($0)
})
return success!.saved
}
@@ -131,6 +128,7 @@ 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.
///
@@ -143,31 +141,27 @@ extension PersistableRecord {
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - 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: {
if let result = try T.fetchOne($0) {
return result
}
throw recordNotFound(db)
try T.fetchOne($0)
})
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: some RowProtocol) throws {
if row._isFetched {
public required init(row: Row) throws {
if row.isFetched {
// Take care of the hasDatabaseChanges flag.
//
// Row may be a reused row which will turn invalid as soon as the
+3 -37
View File
@@ -29,7 +29,6 @@ import Foundation
/// - ``exists(_:id:)``
/// - ``exists(_:key:)-60hf2``
/// - ``exists(_:key:)-6ha6``
/// - ``recordNotFound(_:)``
///
/// ### Throwing Record Not Found Errors
///
@@ -319,7 +318,7 @@ extension TableRecord {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
/// Returns whether a record exists for this primary key.
///
@@ -455,7 +454,7 @@ extension TableRecord {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
/// Deletes records identified by their primary keys, and returns the number
/// of deleted records.
@@ -698,15 +697,6 @@ 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).
@@ -750,31 +740,7 @@ extension TableRecord {
}
}
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, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
/// Returns an error for a record that does not exist in the database.
///
+72
View File
@@ -0,0 +1,72 @@
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
@@ -1,45 +0,0 @@
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 { }
+5 -9
View File
@@ -14,12 +14,9 @@ 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.
///
/// OnDemandFuture also adds Sendable requirements that avoid
/// compiler warnings.
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
struct OnDemandFuture<Output, Failure: Error>: Publisher {
typealias Promise = @Sendable (Result<Output, Failure>) -> Void
typealias Promise = (Result<Output, Failure>) -> Void
typealias Output = Output
typealias Failure = Failure
fileprivate let attemptToFulfill: (@escaping Promise) -> Void
@@ -36,10 +33,9 @@ struct OnDemandFuture<Output, Failure: Error>: Publisher {
}
}
@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
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
private class OnDemandFutureSubscription<Downstream: Subscriber>: Subscription {
typealias Promise = (Result<Downstream.Input, Downstream.Failure>) -> Void
private enum State {
case waitingForDemand(downstream: Downstream, attemptToFulfill: (@escaping Promise) -> Void)
+19 -33
View File
@@ -35,9 +35,8 @@ import Dispatch
/// got 2
/// got 1
/// got 3
final class Pool<T: Sendable>: Sendable {
private class Item: @unchecked Sendable {
// @unchecked because `isAvailable` is protected by `content`.
final class Pool<T> {
private class Item {
let element: T
var isAvailable: Bool
@@ -47,19 +46,8 @@ final class Pool<T: Sendable>: Sendable {
}
}
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 makeElement: () throws -> T
@ReadWriteBox private var items: [Item] = []
private let itemsSemaphore: DispatchSemaphore // limits the number of elements
private let itemsGroup: DispatchGroup // knows when no element is used
private let barrierQueue: DispatchQueue
@@ -71,12 +59,11 @@ final class Pool<T: Sendable>: Sendable {
/// - 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. Its argument is the index of the created elements
/// (1, then 2, etc).
/// on demand.
init(
maximumCount: Int,
qos: DispatchQoS = .unspecified,
makeElement: @escaping @Sendable (_ index: Int) throws -> T)
makeElement: @escaping () throws -> T)
{
GRDBPrecondition(maximumCount > 0, "Pool size must be at least 1")
self.makeElement = makeElement
@@ -88,20 +75,19 @@ final class Pool<T: Sendable>: Sendable {
/// Returns a tuple (element, release)
/// Client must call release(), only once, after the element has been used.
func get() throws -> ElementAndRelease {
func get() throws -> (element: T, release: (PoolCompletion) -> Void) {
try barrierQueue.sync {
itemsSemaphore.wait()
itemsGroup.enter()
do {
let item = try content.update { content -> Item in
if let item = content.items.first(where: \.isAvailable) {
let item = try $items.update { items -> Item in
if let item = items.first(where: \.isAvailable) {
item.isAvailable = false
return item
} else {
content.createdCount += 1
let element = try makeElement(content.createdCount)
let element = try makeElement()
let item = Item(element: element, isAvailable: false)
content.items.append(item)
items.append(item)
return item
}
}
@@ -121,7 +107,7 @@ final class Pool<T: Sendable>: Sendable {
///
/// - important: The `execute` argument is executed in a serial dispatch
/// queue, so make sure you use the element asynchronously.
func asyncGet(_ execute: @escaping @Sendable (Result<ElementAndRelease, Error>) -> Void) {
func asyncGet(_ execute: @escaping (Result<(element: T, release: (PoolCompletion) -> Void), 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
@@ -142,7 +128,7 @@ final class Pool<T: Sendable>: Sendable {
}
private func release(_ item: Item, completion: PoolCompletion) {
content.update { content in
$items.update { items in
switch completion {
case .reuse:
// This is why Item is a class, not a struct: so that we can
@@ -150,8 +136,8 @@ final class Pool<T: Sendable>: Sendable {
item.isAvailable = true
case .discard:
// Discard should be rare: perform lookup.
if let index = content.items.firstIndex(where: { $0 === item }) {
content.items.remove(at: index)
if let index = items.firstIndex(where: { $0 === item }) {
items.remove(at: index)
}
}
}
@@ -162,8 +148,8 @@ final class Pool<T: Sendable>: Sendable {
/// 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 content.read { content in
for item in content.items {
try $items.read { items in
for item in items {
try body(item.element)
}
}
@@ -172,7 +158,7 @@ final class Pool<T: Sendable>: Sendable {
/// Removes all elements from the pool.
/// Currently used elements won't be reused.
func removeAll() {
content.update { $0.items.removeAll() }
items = []
}
/// Blocks until no element is used, and runs the `barrier` function before
@@ -186,7 +172,7 @@ final class Pool<T: Sendable>: Sendable {
/// Asynchronously runs the `barrier` function when no element is used, and
/// before any other element is dequeued.
func asyncBarrier(execute barrier: @escaping @Sendable () -> Void) {
func asyncBarrier(execute barrier: @escaping () -> Void) {
barrierQueue.async(flags: [.barrier]) {
self.itemsGroup.wait()
barrier()
+1 -2
View File
@@ -3,8 +3,7 @@ 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: Sendable>: @unchecked Sendable {
// @unchecked because `_wrappedValue` is protected by `queue`
final class ReadWriteBox<T> {
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, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
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, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
private class ReceiveValuesOnSubscription<Upstream, Context, Downstream>: Subscription, Subscriber
where
Upstream: Publisher,
@@ -211,7 +211,7 @@ where
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
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 {
nonisolated(unsafe) private static let mainKey: DispatchSpecificKey<()> = {
private static var 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: (@Sendable () -> Void)?, _ lhs: (@Sendable () -> Void)?) -> (@Sendable () -> Void)? {
func concat(_ rhs: (() -> Void)?, _ lhs: (() -> Void)?) -> (() -> Void)? {
switch (rhs, lhs) {
case let (rhs, nil):
return rhs
@@ -140,7 +140,7 @@ func concat(_ rhs: (@Sendable () -> Void)?, _ lhs: (@Sendable () -> Void)?) -> (
}
/// Concatenates two functions
func concat<T>(_ rhs: (@Sendable (T) -> Void)?, _ lhs: (@Sendable (T) -> Void)?) -> (@Sendable (T) -> Void)? {
func concat<T>(_ rhs: ((T) -> Void)?, _ lhs: ((T) -> Void)?) -> ((T) -> Void)? {
switch (rhs, lhs) {
case let (rhs, nil):
return rhs
+10 -21
View File
@@ -1,5 +1,3 @@
import Foundation
/// A protocol indicating that an activity or action supports cancellation.
///
/// ## Topics
@@ -17,40 +15,31 @@ public protocol DatabaseCancellable {
///
/// An `AnyDatabaseCancellable` instance automatically calls ``cancel()``
/// when deinitialized.
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: { })
}
public class AnyDatabaseCancellable: DatabaseCancellable {
private var _cancel: (() -> Void)?
/// Initializes the cancellable object with the given cancel-time closure.
public init(cancel: @escaping @Sendable () -> Void) {
public init(cancel: @escaping () -> 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 {
base.cancel()
cancellable?.cancel()
cancellable = nil // Release memory
}
}
deinit {
cancel()
_cancel?()
}
public func cancel() {
lock.lock()
let cancel = _cancel
// Don't prevent multiple concurrent calls to _cancel, because it is
// pointless. But release memory!
_cancel?()
_cancel = nil
lock.unlock()
cancel?()
}
}
Loaded 100 of 227 files, more files were not shown because too many files have changed in this diff. Show more