mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-06 05:28:44 +00:00
Compare commits
70
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9318693fe4 | ||
|
|
a1b76f9e06 | ||
|
|
2d19cab2b5 | ||
|
|
a551fbf443 | ||
|
|
c6e220a531 | ||
|
|
600d1b84b6 | ||
|
|
5629cfe6ff | ||
|
|
5d9b9edfe1 | ||
|
|
449c243a36 | ||
|
|
6ca4986bc2 | ||
|
|
063877d49c | ||
|
|
2f4d0c4588 | ||
|
|
0a544dc0d2 | ||
|
|
d64274474b | ||
|
|
e66dfacab8 | ||
|
|
0d4c6e592e | ||
|
|
5d7fdeae5a | ||
|
|
378c6785ea | ||
|
|
6d392f0a87 | ||
|
|
7c81c37e1f | ||
|
|
3f876978a1 | ||
|
|
a0ed1bfd33 | ||
|
|
be41d2dd03 | ||
|
|
e6c3a8d07a | ||
|
|
5e41ca7e4e | ||
|
|
0f942c014c | ||
|
|
40bebda712 | ||
|
|
37fd4c18b0 | ||
|
|
d5a41bd11b | ||
|
|
c22fc202a9 | ||
|
|
a0f14d816a | ||
|
|
ad33dfcfbf | ||
|
|
840fa3b5da | ||
|
|
397a008237 | ||
|
|
f7559d4c76 | ||
|
|
8cd71ac832 | ||
|
|
0ffd25bc74 | ||
|
|
ff7f9073fc | ||
|
|
93616775f6 | ||
|
|
81751625e0 | ||
|
|
9798f9f9fa | ||
|
|
db165581ea | ||
|
|
b4e851aa49 | ||
|
|
0169e340dc | ||
|
|
1d5d1aea68 | ||
|
|
0c333b6e22 | ||
|
|
6a24d835d3 | ||
|
|
3382280cc3 | ||
|
|
60fa8a630f | ||
|
|
9ba64c2426 | ||
|
|
29b5b99b89 | ||
|
|
725d38ea06 | ||
|
|
6509f7ed40 | ||
|
|
67bdc740bd | ||
|
|
1e2b454c4c | ||
|
|
a77f9d3f6a | ||
|
|
229bd98b9c | ||
|
|
692eac43a9 | ||
|
|
4f398a3457 | ||
|
|
44c13e5bff | ||
|
|
7b2393f2cd | ||
|
|
67dfdc1bbb | ||
|
|
cc8ed5ccb5 | ||
|
|
441823d5f4 | ||
|
|
1e5ee4b292 | ||
|
|
159a34bdf2 | ||
|
|
e936d6b42d | ||
|
|
cc567f2555 | ||
|
|
b3763ad08e | ||
|
|
c824b42757 |
No files matched your search
@@ -7,6 +7,8 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 6.x Releases
|
||||
|
||||
- `6.10.x` Releases - [6.10.0](#6100)
|
||||
- `6.9.x` Releases - [6.9.0](#690) - [6.9.1](#691) - [6.9.2](#692)
|
||||
- `6.8.x` Releases - [6.8.0](#680)
|
||||
- `6.7.x` Releases - [6.7.0](#670)
|
||||
- `6.6.x` Releases - [6.6.0](#660) - [6.6.1](#661)
|
||||
@@ -106,6 +108,38 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 6.10.0
|
||||
|
||||
Released March 20, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.9.2...v6.10.0)
|
||||
|
||||
- **New**: [#1350](https://github.com/groue/GRDB.swift/pull/1350) by [@groue](https://github.com/groue): DatabasePool won't close read-only connections if requested, and ValueObservation no longer opens a new database connection when it starts.
|
||||
|
||||
## 6.9.2
|
||||
|
||||
Released March 14, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.9.1...v6.9.2)
|
||||
|
||||
- **Fixed**: [#1349](https://github.com/groue/GRDB.swift/pull/1349) by [@JonLz](https://github.com/JonLz): Fix Migrations.md example so it compiles
|
||||
- **Fixed**: Avoid the risk for pathologically deep stack trace, or stack overflow, introduced by [#1348](https://github.com/groue/GRDB.swift/pull/1348).
|
||||
|
||||
## 6.9.1
|
||||
|
||||
Released March 12, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.9.0...v6.9.1)
|
||||
|
||||
- **Documentation Updates**: Moved more README chapters into DocC:
|
||||
- [`RowAdapter`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter)
|
||||
- [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/splittingrowadapters(columncounts:))
|
||||
|
||||
## 6.9.0
|
||||
|
||||
Released March 12, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.8.0...v6.9.0)
|
||||
|
||||
- **New**: [#1348](https://github.com/groue/GRDB.swift/pull/1348) by [@groue](https://github.com/groue): SQLite argument binding optimization
|
||||
- **New**: `FTS5.api(db)` returns a pointer to the `fts5_api` structure, useful for low-level [FTS5 customization](https://www.sqlite.org/fts5.html#extending_fts5).
|
||||
- **Documentation Updates**: Moved more README chapters into DocC, enhanced and extended DocC articles:
|
||||
- [Database Connections](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections)
|
||||
- [Prepared Statements](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statement)
|
||||
- [DatabaseValueConvertible](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasevalueconvertible)
|
||||
|
||||
## 6.8.0
|
||||
|
||||
Released February 24, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.7.0...v6.8.0)
|
||||
|
||||
@@ -130,7 +130,7 @@ let request = Book.including(optional: Book.author)
|
||||
let bookInfos = BookInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
Before we dive in, please remember that associations can not generate all possible SQL queries that involve several tables. You may also *prefer* writing SQL, and this is just OK, because your SQL skills are welcome: see the [Joined Queries Support](../README.md#joined-queries-support) chapter.
|
||||
Before we dive in, please remember that associations can not generate all possible SQL queries that involve several tables. You may also *prefer* writing SQL, and this is just OK, because your SQL skills are welcome. The [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/splittingrowadapters(columncounts:)) method can help you consume the rows fetched from joined queries, as in `SELECT book.*, author.* FROM ...`.
|
||||
|
||||
|
||||
## Required Protocols
|
||||
@@ -2996,7 +2996,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
[Isolation of Multiple Aggregates]: #isolation-of-multiple-aggregates
|
||||
[DerivableRequest Protocol]: #derivablerequest-protocol
|
||||
[Known Issues]: #known-issues
|
||||
[Row Adapters]: ../README.md#row-adapters
|
||||
[Row Adapters]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter
|
||||
[query interface requests]: ../README.md#requests
|
||||
[TableRecord]: ../README.md#tablerecord-protocol
|
||||
[Good Practices for Designing Record Types]: GoodPracticesForDesigningRecordTypes.md
|
||||
|
||||
@@ -230,6 +230,7 @@
|
||||
567C3E0E2520B6DE0011F6E9 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = YES;
|
||||
LastSwiftUpdateCheck = 1250;
|
||||
LastUpgradeCheck = 1200;
|
||||
TargetAttributes = {
|
||||
@@ -583,7 +584,7 @@
|
||||
repositoryURL = "https://github.com/groue/GRDBQuery";
|
||||
requirement = {
|
||||
kind = upToNextMajorVersion;
|
||||
minimumVersion = 0.1.0;
|
||||
minimumVersion = 0.6.0;
|
||||
};
|
||||
};
|
||||
/* End XCRemoteSwiftPackageReference section */
|
||||
|
||||
+2
-2
@@ -5,8 +5,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/groue/GRDBQuery",
|
||||
"state" : {
|
||||
"revision" : "df514f2bd74548f94e082f3233022190e594fce4",
|
||||
"version" : "0.5.1"
|
||||
"revision" : "aefc0d7e7a64e841da33e1c8be7429da1bd9b5d6",
|
||||
"version" : "0.6.0"
|
||||
}
|
||||
}
|
||||
],
|
||||
|
||||
@@ -230,6 +230,7 @@
|
||||
567C3E0E2520B6DE0011F6E9 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = YES;
|
||||
LastSwiftUpdateCheck = 1250;
|
||||
LastUpgradeCheck = 1200;
|
||||
TargetAttributes = {
|
||||
@@ -581,7 +582,7 @@
|
||||
repositoryURL = "https://github.com/groue/GRDBQuery";
|
||||
requirement = {
|
||||
kind = upToNextMajorVersion;
|
||||
minimumVersion = 0.1.0;
|
||||
minimumVersion = 0.6.0;
|
||||
};
|
||||
};
|
||||
/* End XCRemoteSwiftPackageReference section */
|
||||
|
||||
+2
-2
@@ -5,8 +5,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/groue/GRDBQuery",
|
||||
"state" : {
|
||||
"revision" : "df514f2bd74548f94e082f3233022190e594fce4",
|
||||
"version" : "0.5.1"
|
||||
"revision" : "aefc0d7e7a64e841da33e1c8be7429da1bd9b5d6",
|
||||
"version" : "0.6.0"
|
||||
}
|
||||
}
|
||||
],
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '6.8.0'
|
||||
s.version = '6.10.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -281,6 +281,7 @@
|
||||
56D110D828AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */; };
|
||||
56D110DD28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */; };
|
||||
56D110FA28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */; };
|
||||
56D3332029C38D6700430680 /* WALSnapshotTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */; };
|
||||
56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */; };
|
||||
56D496551D812F83008276D7 /* FoundationDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */; };
|
||||
56D496571D81303E008276D7 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; };
|
||||
@@ -373,6 +374,7 @@
|
||||
56E9FACB221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FACA221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift */; };
|
||||
56E9FADA221053DD00C703A8 /* SQL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAD7221053DC00C703A8 /* SQL.swift */; };
|
||||
56EA63C5209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */; };
|
||||
56F0383B28C21814000DEBFB /* Database+Cache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0383A28C21814000DEBFB /* Database+Cache.swift */; };
|
||||
56F34FBA24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */; };
|
||||
56F34FC224B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */; };
|
||||
56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
|
||||
@@ -753,6 +755,7 @@
|
||||
56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Insert.swift"; sourceTree = "<group>"; };
|
||||
56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Save.swift"; sourceTree = "<group>"; };
|
||||
56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+DAO.swift"; sourceTree = "<group>"; };
|
||||
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshotTransaction.swift; sourceTree = "<group>"; };
|
||||
56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = "<group>"; };
|
||||
56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = "<group>"; };
|
||||
56D91AA12205E03700770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = "<group>"; };
|
||||
@@ -775,6 +778,7 @@
|
||||
56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReadOnlyTests.swift; sourceTree = "<group>"; };
|
||||
56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataMemoryTests.swift; sourceTree = "<group>"; };
|
||||
56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizerTests.swift; sourceTree = "<group>"; };
|
||||
56F0383A28C21814000DEBFB /* Database+Cache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Cache.swift"; sourceTree = "<group>"; };
|
||||
56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = "<group>"; };
|
||||
56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLExpressionIsConstantTests.swift; sourceTree = "<group>"; };
|
||||
56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLIdentifyingColumnsTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1442,6 +1446,7 @@
|
||||
56A238701B9C75030082EB20 /* Configuration.swift */,
|
||||
56DAA2DA1DE9C827006E10C8 /* Cursor.swift */,
|
||||
56A238711B9C75030082EB20 /* Database.swift */,
|
||||
56F0383A28C21814000DEBFB /* Database+Cache.swift */,
|
||||
566B91221FA4CF810012D5B0 /* Database+Schema.swift */,
|
||||
566B91081FA4C3960012D5B0 /* Database+Statements.swift */,
|
||||
4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */,
|
||||
@@ -1466,6 +1471,7 @@
|
||||
566B9C1F25C6CC24004542CF /* RowDecodingError.swift */,
|
||||
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
|
||||
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
|
||||
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */,
|
||||
56E9FAD7221053DC00C703A8 /* SQL.swift */,
|
||||
569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */,
|
||||
56FBFED82210731A00945324 /* SQLRequest.swift */,
|
||||
@@ -2020,6 +2026,7 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */,
|
||||
56F0383B28C21814000DEBFB /* Database+Cache.swift in Sources */,
|
||||
56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
56158780288D875E00A67323 /* Optional.swift in Sources */,
|
||||
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */,
|
||||
@@ -2157,6 +2164,7 @@
|
||||
5653EC122098738B00F46237 /* SQLGenerationContext.swift in Sources */,
|
||||
560D92471C672C4B00F4F92B /* MutablePersistableRecord.swift in Sources */,
|
||||
5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
|
||||
56D3332029C38D6700430680 /* WALSnapshotTransaction.swift in Sources */,
|
||||
5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
|
||||
5657AAB91D107001006283EF /* NSData.swift in Sources */,
|
||||
560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */,
|
||||
|
||||
@@ -301,13 +301,15 @@ public struct Configuration {
|
||||
/// If nil, GRDB picks a default one.
|
||||
var readonlyBusyMode: Database.BusyMode? = nil
|
||||
|
||||
/// The maximum number of concurrent readers.
|
||||
/// The maximum number of concurrent reader connections.
|
||||
///
|
||||
/// This configuration applies to ``DatabasePool`` only. The default value
|
||||
/// is 5.
|
||||
/// This configuration has effect on ``DatabasePool`` and
|
||||
/// ``DatabaseSnapshotPool`` only. The default value is 5.
|
||||
///
|
||||
/// You can query this value at runtime in order to get the actual capacity
|
||||
/// for concurrent reads of any ``DatabaseReader``. For example:
|
||||
/// for concurrent reads of any ``DatabaseReader``. In this context,
|
||||
/// ``DatabaseQueue`` and ``DatabaseSnapshot`` have a capacity of 1,
|
||||
/// because they can't perform two concurrent reads. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
@@ -321,6 +323,7 @@ public struct Configuration {
|
||||
/// print(dbQueue.configuration.maximumReaderCount) // 1
|
||||
/// print(dbPool.configuration.maximumReaderCount) // 5
|
||||
/// print(dbSnapshot.configuration.maximumReaderCount) // 1
|
||||
/// ```
|
||||
public var maximumReaderCount: Int = 5
|
||||
|
||||
/// The quality of service of database accesses.
|
||||
@@ -372,7 +375,22 @@ public struct Configuration {
|
||||
/// The default is true.
|
||||
public var automaticMemoryManagement = true
|
||||
#endif
|
||||
|
||||
|
||||
/// A boolean value indicating whether read-only connections should be
|
||||
/// kept open.
|
||||
///
|
||||
/// This configuration flag applies to ``DatabasePool`` only. The
|
||||
/// default value is false.
|
||||
///
|
||||
/// When the flag is false, a `DatabasePool` closes read-only
|
||||
/// connections when requested to dispose non-essential memory with
|
||||
/// ``DatabasePool/releaseMemory()``. When true, those connections are
|
||||
/// kept open.
|
||||
///
|
||||
/// Consider setting this flag to true when profiling your application
|
||||
/// reveals that a lot of time is spent opening new SQLite connections.
|
||||
public var persistentReadOnlyConnections = false
|
||||
|
||||
// MARK: - Factory Configuration
|
||||
|
||||
/// Creates a factory configuration.
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
extension Database {
|
||||
func withCache<T>(atPath path: String, execute: () throws -> T) throws -> T {
|
||||
GRDBPrecondition(attachedCache == nil, "Database is already cached.")
|
||||
|
||||
return try throwingFirstError {
|
||||
attachedCache = AttachedCache(
|
||||
schema: .attached("cache"),
|
||||
statementCache: StatementCache(database: self))
|
||||
try self.execute(literal: "ATTACH DATABASE \(path) AS cache")
|
||||
return try execute()
|
||||
} finally: {
|
||||
attachedCache = nil
|
||||
try self.execute(sql: "DETACH DATABASE cache")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Statement {
|
||||
/// Returns a statement ready for iterating the results of this statement
|
||||
/// with a DatabaseCursor.
|
||||
///
|
||||
/// The result is not the same statement as the receiver if we cache the
|
||||
/// statement's results.
|
||||
func databaseCursorStatement(with arguments: StatementArguments?) throws -> Statement {
|
||||
// Should we cache statement results and return a new statement on the cached values?
|
||||
guard
|
||||
// Don't cache until we were instructed to.
|
||||
let attachedCache = database.attachedCache,
|
||||
|
||||
// Only cache read-only statements.
|
||||
isReadonly,
|
||||
|
||||
// Only cache statements that access user tables.
|
||||
databaseRegion
|
||||
.filteringTables({ !Database.isSQLiteInternalTable($0) && !Database.isGRDBInternalTable($0) })
|
||||
.isEmpty == false,
|
||||
|
||||
// Only cache statements that can build a name for the cache table.
|
||||
let cacheTableName,
|
||||
|
||||
// Only cache statements for which we can guarantee rowid ordering
|
||||
// without ambiguity.
|
||||
case let statementColumns = columnNames.map({ $0.lowercased() }),
|
||||
let rowid = ["rowid", "_rowid_", "oid"].first(where: { !statementColumns.contains($0) })
|
||||
else {
|
||||
// Don't cache: return self.
|
||||
// Reset before cursor iteration: the statement may be reused.
|
||||
try prepareExecution(withArguments: arguments)
|
||||
return self
|
||||
}
|
||||
|
||||
// Cache the results if not done yet
|
||||
let cacheTable = Database.TableIdentifier(schemaID: attachedCache.schema, name: cacheTableName)
|
||||
try database.execute(sql: """
|
||||
CREATE TABLE IF NOT EXISTS \(cacheTable.quotedDatabaseIdentifier) AS \(sql)
|
||||
""", arguments: arguments ?? self.arguments)
|
||||
|
||||
// Return a statement on the cached values, preserving the order of the
|
||||
// original rows.
|
||||
//
|
||||
// Quoting <https://sqlite.org/lang_createtable.html#create_table_as_select_statements>:
|
||||
//
|
||||
// > Tables created using CREATE TABLE AS are initially populated with
|
||||
// > the rows of data returned by the SELECT statement. Rows are
|
||||
// > assigned contiguously ascending rowid values, starting with 1, in
|
||||
// > the order that they are returned by the SELECT statement.
|
||||
let statement = try attachedCache.statementCache.statement("""
|
||||
SELECT * FROM \(cacheTable.quotedDatabaseIdentifier) ORDER BY \(rowid)
|
||||
""")
|
||||
// Reset before cursor iteration: the statement may be reused.
|
||||
try statement.reset()
|
||||
return statement
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,10 @@ extension Database {
|
||||
case let .attached(name): return "\(name).sqlite_master"
|
||||
}
|
||||
}
|
||||
|
||||
func table(_ name: String) -> TableIdentifier {
|
||||
TableIdentifier(schemaID: self, name: name)
|
||||
}
|
||||
}
|
||||
|
||||
/// The identifier of a database table or view.
|
||||
@@ -210,7 +214,7 @@ extension Database {
|
||||
}
|
||||
}
|
||||
|
||||
private func tableExists(_ table: TableIdentifier) throws -> Bool {
|
||||
func tableExists(_ table: TableIdentifier) throws -> Bool {
|
||||
try exists(type: .table, name: table.name, in: table.schemaID)
|
||||
}
|
||||
|
||||
|
||||
@@ -331,6 +331,20 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
class AttachedCache {
|
||||
var schema: SchemaIdentifier
|
||||
var statementCache: StatementCache
|
||||
|
||||
init(schema: Database.SchemaIdentifier, statementCache: StatementCache) {
|
||||
self.schema = schema
|
||||
self.statementCache = statementCache
|
||||
}
|
||||
}
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The attached database that caches the results of requests.
|
||||
var attachedCache: AttachedCache?
|
||||
|
||||
// MARK: - Private properties
|
||||
|
||||
/// Support for ``Configuration/busyMode``.
|
||||
|
||||
@@ -216,10 +216,12 @@ extension ResultCode: Sendable { }
|
||||
/// do {
|
||||
/// try player.insert(db)
|
||||
/// } catch let error as DatabaseError {
|
||||
/// switch error.resultCode {
|
||||
/// case ResultCode.SQLITE_CONSTRAINT_FOREIGNKEY:
|
||||
/// print(error) // prints debugging information
|
||||
///
|
||||
/// switch error {
|
||||
/// case DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY:
|
||||
/// // foreign key constraint error
|
||||
/// case ResultCode.SQLITE_CONSTRAINT:
|
||||
/// case DatabaseError.SQLITE_CONSTRAINT:
|
||||
/// // any other constraint error
|
||||
/// default:
|
||||
/// // any other database error
|
||||
|
||||
@@ -168,12 +168,15 @@ extension DatabasePool {
|
||||
|
||||
// MARK: - Memory management
|
||||
|
||||
/// Frees as much memory as possible, by disposing non-essential memory from
|
||||
/// the writer connection, and closing all reader connections.
|
||||
/// Frees as much memory as possible, by disposing non-essential memory.
|
||||
///
|
||||
/// This method is synchronous, and blocks the current thread until all
|
||||
/// database accesses are completed.
|
||||
///
|
||||
/// This method closes all read-only connections, unless the
|
||||
/// ``Configuration/persistentReadOnlyConnections`` configuration flag
|
||||
/// is set.
|
||||
///
|
||||
/// - warning: This method can prevent concurrent reads from executing,
|
||||
/// until it returns. Prefer ``releaseMemoryEventually()`` if you intend
|
||||
/// to keep on using the database while releasing memory.
|
||||
@@ -181,34 +184,50 @@ extension DatabasePool {
|
||||
// Release writer memory
|
||||
writer.sync { $0.releaseMemory() }
|
||||
|
||||
// Release readers memory by closing all connections.
|
||||
//
|
||||
// We must use a barrier in order to guarantee that memory has been
|
||||
// freed (reader connections closed) when the method exits, as
|
||||
// documented.
|
||||
//
|
||||
// Without the barrier, connections would only close _eventually_ (after
|
||||
// their eventual concurrent jobs have completed).
|
||||
readerPool?.barrier {
|
||||
readerPool?.removeAll()
|
||||
if configuration.persistentReadOnlyConnections {
|
||||
// Keep existing readers
|
||||
readerPool?.forEach { reader in
|
||||
reader.sync { $0.releaseMemory() }
|
||||
}
|
||||
} else {
|
||||
// Release readers memory by closing all connections.
|
||||
//
|
||||
// We must use a barrier in order to guarantee that memory has been
|
||||
// freed (reader connections closed) when the method exits, as
|
||||
// documented.
|
||||
//
|
||||
// Without the barrier, connections would only close _eventually_ (after
|
||||
// their eventual concurrent jobs have completed).
|
||||
readerPool?.barrier {
|
||||
readerPool?.removeAll()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Eventually frees as much memory as possible, by disposing non-essential
|
||||
/// memory from the writer connection, and closing all reader connections.
|
||||
/// Eventually frees as much memory as possible, by disposing
|
||||
/// non-essential memory.
|
||||
///
|
||||
/// This method eventually closes all read-only connections, unless the
|
||||
/// ``Configuration/persistentReadOnlyConnections`` configuration flag
|
||||
/// is set.
|
||||
///
|
||||
/// Unlike ``releaseMemory()``, this method does not prevent concurrent
|
||||
/// database accesses when it is executing. But it does not notify when
|
||||
/// non-essential memory has been freed.
|
||||
public func releaseMemoryEventually() {
|
||||
// Release readers memory by eventually closing all reader connections
|
||||
// (they will close after their current jobs have completed).
|
||||
readerPool?.removeAll()
|
||||
if configuration.persistentReadOnlyConnections {
|
||||
// Keep existing readers
|
||||
readerPool?.forEach { reader in
|
||||
reader.async { $0.releaseMemory() }
|
||||
}
|
||||
} else {
|
||||
// Release readers memory by eventually closing all reader connections
|
||||
// (they will close after their current jobs have completed).
|
||||
readerPool?.removeAll()
|
||||
}
|
||||
|
||||
// Release writer memory eventually.
|
||||
writer.async { db in
|
||||
db.releaseMemory()
|
||||
}
|
||||
writer.async { $0.releaseMemory() }
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
@@ -361,7 +380,7 @@ extension DatabasePool: DatabaseReader {
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")))
|
||||
value(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -405,7 +424,7 @@ extension DatabasePool: DatabaseReader {
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")))
|
||||
value(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -608,8 +627,12 @@ extension DatabasePool: DatabaseReader {
|
||||
/// After this method is called, read-only database access methods will use
|
||||
/// new SQLite connections.
|
||||
///
|
||||
/// Eventual concurrent read-only accesses are not invalidated: they will
|
||||
/// Eventual concurrent read-only accesses are not interrupted, and
|
||||
/// proceed until completion.
|
||||
///
|
||||
/// - This method closes all read-only connections, even if the
|
||||
/// ``Configuration/persistentReadOnlyConnections`` configuration flag
|
||||
/// is set.
|
||||
public func invalidateReadOnlyConnections() {
|
||||
readerPool?.removeAll()
|
||||
}
|
||||
@@ -640,6 +663,50 @@ extension DatabasePool: DatabaseReader {
|
||||
return readers.first { $0.onValidQueue }
|
||||
}
|
||||
|
||||
// MARK: - WAL Snapshot Transactions
|
||||
|
||||
// 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 {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
return try WALSnapshotTransaction(onReader: reader, release: { isInsideTransaction in
|
||||
// Discard the connection if the transaction could not be
|
||||
// properly ended. If we'd reuse it, the next read would
|
||||
// fail because we'd fail starting a read transaction.
|
||||
releaseReader(isInsideTransaction ? .discard : .reuse)
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns a long-lived WAL snapshot transaction on a reader connection.
|
||||
///
|
||||
/// - important: The `completion` argument is executed in a serial
|
||||
/// dispatch queue, so make sure you use the transaction asynchronously.
|
||||
func asyncWALSnapshotTransaction(_ completion: @escaping (Result<WALSnapshotTransaction, Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
completion(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
}
|
||||
|
||||
readerPool.asyncGet { result in
|
||||
completion(result.flatMap { reader, releaseReader in
|
||||
Result {
|
||||
try WALSnapshotTransaction(onReader: reader, release: { isInsideTransaction in
|
||||
// Discard the connection if the transaction could not be
|
||||
// properly ended. If we'd reuse it, the next read would
|
||||
// fail because we'd fail starting a read transaction.
|
||||
releaseReader(isInsideTransaction ? .discard : .reuse)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
|
||||
@@ -168,9 +168,14 @@ public struct DatabaseRegion {
|
||||
// TransactionObserver protocol. By removing internal SQLite tables from
|
||||
// the observed region, we optimize database observation.
|
||||
//
|
||||
// We also remove GRDB internal tables (cache tables).
|
||||
//
|
||||
// And by canonicalizing table names, we remove views, and help the
|
||||
// `isModified` methods.
|
||||
try ignoringInternalSQLiteTables().canonicalTables(db)
|
||||
let notInternalTables = filteringTables {
|
||||
!Database.isSQLiteInternalTable($0) && !Database.isGRDBInternalTable($0)
|
||||
}
|
||||
return try notInternalTables.canonicalTables(db)
|
||||
}
|
||||
|
||||
/// Returns a region only made of actual tables with their canonical names.
|
||||
@@ -190,11 +195,11 @@ public struct DatabaseRegion {
|
||||
return region
|
||||
}
|
||||
|
||||
/// Returns a region which doesn't contain any SQLite internal table.
|
||||
private func ignoringInternalSQLiteTables() -> DatabaseRegion {
|
||||
/// Returns a region which only contains the filtered tables
|
||||
func filteringTables(_ predicate: (String) -> Bool) -> DatabaseRegion {
|
||||
guard let tableRegions else { return .fullDatabase }
|
||||
let filteredRegions = tableRegions.filter {
|
||||
!Database.isSQLiteInternalTable($0.key.rawValue)
|
||||
predicate($0.key.rawValue)
|
||||
}
|
||||
return DatabaseRegion(tableRegions: filteredRegions)
|
||||
}
|
||||
|
||||
@@ -3,109 +3,6 @@ import Combine
|
||||
#endif
|
||||
import Foundation
|
||||
|
||||
/// `DatabaseRegionObservation` tracks transactions that modify a
|
||||
/// database region.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// Tracked changes are insertions, updates, and deletions that impact the
|
||||
/// tracked region, whether performed with raw SQL, or <doc:QueryInterface>.
|
||||
/// This includes indirect changes triggered by
|
||||
/// [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions)
|
||||
/// or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
|
||||
///
|
||||
/// Changes to internal system tables (such as `sqlite_master`) and changes to
|
||||
/// [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables are
|
||||
/// not notified.
|
||||
///
|
||||
/// `DatabaseRegionObservation` calls your application right after changes have
|
||||
/// been committed in the database, and before any other thread had any
|
||||
/// opportunity to perform further changes. *This is a pretty strong guarantee,
|
||||
/// that most applications do not really need.* Instead, most applications
|
||||
/// prefer to be notified with fresh values: make sure you check
|
||||
/// ``ValueObservation`` before using `DatabaseRegionObservation`.
|
||||
///
|
||||
/// ## DatabaseRegionObservation Usage
|
||||
///
|
||||
/// Create a `DatabaseRegionObservation` with one or several requests to track:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Tracks the full player table
|
||||
/// let observation = DatabaseRegionObservation(tracking: Player.all())
|
||||
/// ```
|
||||
///
|
||||
/// Then start the observation from a ``DatabaseQueue`` or ``DatabasePool``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let cancellable = try observation.start(in: dbQueue) { error in
|
||||
/// // Handle error
|
||||
/// } onChange: { (db: Database) in
|
||||
/// print("Players were changed")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Enjoy the changes notifications:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// try Player(name: "Arthur").insert(db)
|
||||
/// }
|
||||
/// // Prints "Players were changed"
|
||||
/// ```
|
||||
///
|
||||
/// You stop the observation by calling the ``DatabaseCancellable/cancel()``
|
||||
/// method on the object returned by the `start` method. Cancellation is
|
||||
/// automatic when the cancellable is deallocated:
|
||||
///
|
||||
/// ```swift
|
||||
/// cancellable.cancel()
|
||||
/// ```
|
||||
///
|
||||
/// `DatabaseRegionObservation` can also be turned into a Combine publisher, or
|
||||
/// an RxSwift observable (see the companion library
|
||||
/// [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB)):
|
||||
///
|
||||
/// ```swift
|
||||
/// let cancellable = observation.publisher(in: dbQueue).sink { completion in
|
||||
/// // Handle completion
|
||||
/// } receiveValue: { (db: Database) in
|
||||
/// print("Players were changed")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// You can feed `DatabaseRegionObservation` with any type that conforms to
|
||||
/// the ``DatabaseRegionConvertible`` protocol: ``FetchRequest``,
|
||||
/// ``DatabaseRegion``, ``Table``, etc. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Observe the score column of the 'player' table
|
||||
/// let observation = DatabaseRegionObservation(
|
||||
/// tracking: Player.select(Column("score")))
|
||||
///
|
||||
/// // Observe the 'score' column of the 'player' table
|
||||
/// let observation = DatabaseRegionObservation(
|
||||
/// tracking: SQLRequest("SELECT score FROM player"))
|
||||
///
|
||||
/// // Observe both the 'player' and 'team' tables
|
||||
/// let observation = DatabaseRegionObservation(
|
||||
/// tracking: Table("player"), Table("team"))
|
||||
///
|
||||
/// // Observe the full database
|
||||
/// let observation = DatabaseRegionObservation(
|
||||
/// tracking: .fullDatabase)
|
||||
/// ```
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating DatabaseRegionObservation
|
||||
///
|
||||
/// - ``init(tracking:)-5ldbe``
|
||||
/// - ``init(tracking:)-2nqjd``
|
||||
///
|
||||
/// ### Observing Database Transactions
|
||||
///
|
||||
/// - ``publisher(in:)``
|
||||
/// - ``start(in:onError:onChange:)``
|
||||
public struct DatabaseRegionObservation {
|
||||
/// A closure that is evaluated when the observation starts, and returns
|
||||
/// the observed database region.
|
||||
|
||||
@@ -294,7 +294,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")))
|
||||
value(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -188,6 +188,34 @@ extension DatabaseValue: StatementBinding {
|
||||
return data.bind(to: sqliteStatement, at: index)
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls the given closure after binding a statement argument.
|
||||
///
|
||||
/// The binding is valid only during the execution of this method.
|
||||
///
|
||||
/// - parameter sqliteStatement: An SQLite statement.
|
||||
/// - parameter index: 1-based index to statement arguments.
|
||||
/// - parameter body: The closure to execute when argument is bound.
|
||||
func withBinding<T>(to sqliteStatement: SQLiteStatement, at index: CInt, do body: () throws -> T) throws -> T {
|
||||
switch storage {
|
||||
case .null:
|
||||
let code = sqlite3_bind_null(sqliteStatement, index)
|
||||
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
|
||||
return try body()
|
||||
case .int64(let int64):
|
||||
let code = int64.bind(to: sqliteStatement, at: index)
|
||||
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
|
||||
return try body()
|
||||
case .double(let double):
|
||||
let code = double.bind(to: sqliteStatement, at: index)
|
||||
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
|
||||
return try body()
|
||||
case .string(let string):
|
||||
return try string.withBinding(to: sqliteStatement, at: index, do: body)
|
||||
case .blob(let data):
|
||||
return try data.withBinding(to: sqliteStatement, at: index, do: body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValue: Sendable { }
|
||||
@@ -314,6 +342,25 @@ extension DatabaseValue: CustomStringConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValue {
|
||||
/// A string that represented the value in a lossless and
|
||||
/// unambiguous way.
|
||||
var losslessDescription: String {
|
||||
switch storage {
|
||||
case .null:
|
||||
return "NULL"
|
||||
case let .string(string):
|
||||
return String(reflecting: string)
|
||||
case let .double(double):
|
||||
return double.description
|
||||
case let .int64(int64):
|
||||
return int64.description
|
||||
case let .blob(data):
|
||||
return "X'" + data.map { String(format: "%02X", $0) }.joined() + "'"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Compares DatabaseValue like SQLite.
|
||||
///
|
||||
/// See RxGRDB for tests.
|
||||
|
||||
@@ -1,49 +1,38 @@
|
||||
/// A type that can convert itself into and out of a database value.
|
||||
///
|
||||
/// `DatabaseValueConvertible` is adopted by `Bool`, `Int`, `String`,
|
||||
/// `Date`, etc.
|
||||
///
|
||||
/// To conform to `DatabaseValueConvertible`, provide custom implementations
|
||||
/// for ``fromDatabaseValue(_:)-21zzv`` and ``databaseValue-1ob9k``. These
|
||||
/// implementations are ready-made for `RawRepresentable` types whose
|
||||
/// `RawValue` is `StatementColumnConvertible`, and for `Codable` types.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a Value
|
||||
///
|
||||
/// - ``fromDatabaseValue(_:)-21zzv``
|
||||
/// - ``fromMissingColumn()-7iamp``
|
||||
///
|
||||
/// ### Accessing the DatabaseValue
|
||||
///
|
||||
/// - ``databaseValue-1ob9k``
|
||||
///
|
||||
/// ### Fetching Values from Raw SQL
|
||||
///
|
||||
/// - ``fetchCursor(_:sql:arguments:adapter:)-6elcz``
|
||||
/// - ``fetchAll(_:sql:arguments:adapter:)-1cqyb``
|
||||
/// - ``fetchSet(_:sql:arguments:adapter:)-5jene``
|
||||
/// - ``fetchOne(_:sql:arguments:adapter:)-qvqp``
|
||||
///
|
||||
/// ### Fetching Values from a Prepared Statement
|
||||
///
|
||||
/// - ``fetchCursor(_:arguments:adapter:)-4l6af``
|
||||
/// - ``fetchAll(_:arguments:adapter:)-3abuc``
|
||||
/// - ``fetchSet(_:arguments:adapter:)-6y54n``
|
||||
/// - ``fetchOne(_:arguments:adapter:)-3d7ax``
|
||||
///
|
||||
/// ### Fetching Values from a Request
|
||||
///
|
||||
/// - ``fetchCursor(_:_:)-8q4r6``
|
||||
/// - ``fetchAll(_:_:)-9hkqs``
|
||||
/// - ``fetchSet(_:_:)-1foke``
|
||||
/// - ``fetchOne(_:_:)-o6yj``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``DatabaseValueCursor``
|
||||
/// - ``StatementBinding``
|
||||
// Standard collections `Array`, `Set`, and `Dictionary` do not conform to
|
||||
// `DatabaseValueConvertible`, on purpose.
|
||||
//
|
||||
// Adding `DatabaseValueConvertible` conformance to those collection types
|
||||
// would litter JSON values in unexpected places, and foster misuse. For
|
||||
// example, it is better when the code below *does not compile*:
|
||||
//
|
||||
// ```swift
|
||||
// // MISUSE: if Array would conform to DatabaseValueConvertible, this
|
||||
// // code would compile, and run the incorrect SQLite query
|
||||
// // `SELECT ... WHERE id IN ('[1,2,3]')`, instead of the expected
|
||||
// // `SELECT ... WHERE id IN (1, 2, 3)`.
|
||||
// let ids = [1, 2, 3]
|
||||
// let players = try Player.fetchAll(db, sql: """
|
||||
// SELECT * FROM player WHERE id IN (?)
|
||||
// """, arguments: [ids])
|
||||
// ```
|
||||
//
|
||||
// Correct and fostered versions of the code above are:
|
||||
//
|
||||
// ```swift
|
||||
// // CORRECT (explicit SQLite arguments):
|
||||
// let ids = [1, 2, 3]
|
||||
// let questionMarks = databaseQuestionMarks(count: ids.count) // "?,?,?"
|
||||
// let players = try Player.fetchAll(db, sql: """
|
||||
// SELECT * FROM player WHERE id IN (\(questionMarks))
|
||||
// """, arguments: StatementArguments(ids))
|
||||
//
|
||||
// // CORRECT (SQL interpolation):
|
||||
// let ids = [1, 2, 3]
|
||||
// let request: SQLRequest<Player> = """
|
||||
// SELECT * FROM player WHERE id IN \(ids)
|
||||
// """
|
||||
// let players = try request.fetchAll(db)
|
||||
// ```
|
||||
public protocol DatabaseValueConvertible: SQLExpressible, StatementBinding {
|
||||
/// A database value.
|
||||
var databaseValue: DatabaseValue { get }
|
||||
@@ -158,6 +147,7 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
|
||||
private let columnIndex: CInt
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
|
||||
let statement = try statement.databaseCursorStatement(with: arguments)
|
||||
self._statement = statement
|
||||
if let adapter {
|
||||
// adapter may redefine the index of the leftmost column
|
||||
@@ -165,9 +155,6 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
|
||||
} else {
|
||||
columnIndex = 0
|
||||
}
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
try statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
|
||||
@@ -141,7 +141,9 @@ extension FetchRequest {
|
||||
/// Returns an adapted request.
|
||||
///
|
||||
/// The returned request performs an identical database query, but adapts
|
||||
/// the fetched rows. See ``RowAdapter``.
|
||||
/// the fetched rows. See ``RowAdapter``, and
|
||||
/// ``splittingRowAdapters(columnCounts:)`` for a sample code that uses
|
||||
/// `adapted(_:)`.
|
||||
///
|
||||
/// - parameter adapter: A closure that accepts a database connection and
|
||||
/// returns a row adapter.
|
||||
|
||||
+3
-7
@@ -1152,8 +1152,7 @@ extension Row {
|
||||
/// Nil is returned if the scope is not available, or contains only
|
||||
/// null values.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support>
|
||||
/// for more information.
|
||||
/// See ``splittingRowAdapters(columnCounts:)`` for a sample code.
|
||||
func decodeIfPresent<Record: FetchableRecord>(
|
||||
_ type: Record.Type = Record.self,
|
||||
forKey scope: String)
|
||||
@@ -1194,8 +1193,7 @@ extension Row {
|
||||
/// A fatal error is raised if the scope is not available, or contains only
|
||||
/// null values.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support>
|
||||
/// for more information.
|
||||
/// See ``splittingRowAdapters(columnCounts:)`` for a sample code.
|
||||
func decode<Record: FetchableRecord>(
|
||||
_ type: Record.Type = Record.self,
|
||||
forKey scope: String)
|
||||
@@ -1362,11 +1360,9 @@ public final class RowCursor: DatabaseCursor {
|
||||
@usableFromInline let _row: Row // Reused for performance
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
|
||||
let statement = try statement.databaseCursorStatement(with: arguments)
|
||||
self._statement = statement
|
||||
self._row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
try statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
|
||||
+294
-67
@@ -1,27 +1,137 @@
|
||||
import Foundation
|
||||
|
||||
/// Returns an array of row adapters that split a row according to the input
|
||||
/// number of columns.
|
||||
/// Returns an array of row adapters that split a row according to the
|
||||
/// provided numbers of columns.
|
||||
///
|
||||
/// For example:
|
||||
/// This method is useful for splitting a row into chunks.
|
||||
///
|
||||
/// For example, let's consider the following SQL query:
|
||||
///
|
||||
/// ```swift
|
||||
/// let sql = "SELECT 1, 2,3,4, 5,6, 7,8"
|
||||
/// // <.><. . .><. .><. .>
|
||||
/// let adapters = splittingRowAdapters([1, 3, 2])
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "a": adapters[0],
|
||||
/// "b": adapters[1],
|
||||
/// "c": adapters[2],
|
||||
/// "d": adapters[3]])
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// row.scopes["a"] // [1]
|
||||
/// row.scopes["b"] // [2, 3, 4]
|
||||
/// row.scopes["c"] // [5, 6]
|
||||
/// row.scopes["d"] // [7, 8]
|
||||
/// let sql = """
|
||||
/// SELECT player.*, team.*
|
||||
/// FROM player
|
||||
/// LEFT JOIN team ON team.id = player.teamId
|
||||
/// WHERE player.id = ?
|
||||
/// """
|
||||
/// ```
|
||||
///
|
||||
/// The resulting rows contains columns from both player and team tables:
|
||||
///
|
||||
/// ```swift
|
||||
/// // [id: 1, name: "Arthur", teamId: 42, id: 42, name: "Reds"]
|
||||
/// // <---------------------------------><-------------------->
|
||||
/// // player columns team columns
|
||||
/// let row = try Row.fetchOne(db, sql: sql, arguments: [1])
|
||||
/// ```
|
||||
///
|
||||
/// Because some columns have the same name (`id` and `name`), it is
|
||||
/// difficult to access the team columns.
|
||||
///
|
||||
/// `splittingRowAdapters` and ``ScopeAdapter`` make it possible to
|
||||
/// access player and team columns independently, with row ``Row/scopes``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let adapters = try splittingRowAdapters([
|
||||
/// db.columns(in: "player").count,
|
||||
/// db.columns(in: "team").count,
|
||||
/// ])
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "player": adapters[0],
|
||||
/// "team": adapters[1],
|
||||
/// ])
|
||||
/// if let row = try Row.fetchOne(db, sql: sql, arguments: [1], adapter: adapter) {
|
||||
/// // A Row that only contains player columns
|
||||
/// // [id: 1, name: "Arthur", teamId: 42]
|
||||
/// row.scopes["player"]
|
||||
///
|
||||
/// // A Row that only contains team columns
|
||||
/// // [id: 42, name: "Reds"]
|
||||
/// row.scopes["team"]
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Decoding ``FetchableRecord`` types is easy:
|
||||
///
|
||||
/// ```swift
|
||||
/// if let row = try Row.fetchOne(db, sql: sql, arguments: [1], adapter: adapter) {
|
||||
/// // Player(id: 1, name: "Arthur", teamId: 42)
|
||||
/// let player: Player = row["player"]
|
||||
///
|
||||
/// // Team(id: 42, name: "Reds")
|
||||
/// // nil if the LEFT JOIN has fetched NULL team columns
|
||||
/// if let team: Team? = row["team"]
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// You can package this technique in a dedicated type, as in the next
|
||||
/// example. It enhances the previous sample codes with:
|
||||
///
|
||||
/// - Support for record types that customize their fetched columns
|
||||
/// with ``TableRecord/databaseSelection-7iphs``.
|
||||
/// - ``SQLRequest`` and its support for [SQL Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md).
|
||||
/// - ``FetchRequest/adapted(_:)`` for building a request that embeds the
|
||||
/// row adapters.
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord, FetchableRecord { ... }
|
||||
/// struct Team: TableRecord, FetchableRecord { ... }
|
||||
///
|
||||
/// struct PlayerInfo {
|
||||
/// var player: Player
|
||||
/// var team: Team?
|
||||
/// }
|
||||
///
|
||||
/// extension PlayerInfo: FetchableRecord {
|
||||
/// init(row: Row) {
|
||||
/// player = row["player"]
|
||||
/// team = row["team"]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// extension PlayerInfo {
|
||||
/// /// The request for the player info, given a player id
|
||||
/// static func filter(playerId: Int64) -> some FetchRequest<PlayerInfo> {
|
||||
/// // Build SQL request with SQL interpolation
|
||||
/// let request: SQLRequest<PlayerInfo> = """
|
||||
/// SELECT
|
||||
/// \(columnsOf: Player.self), -- Instead of player.*
|
||||
/// \(columnsOf: Team.self), -- Instead of team.*
|
||||
/// FROM player
|
||||
/// LEFT JOIN team ON team.id = player.teamId
|
||||
/// WHERE player.id = \(playerId)
|
||||
/// """
|
||||
///
|
||||
/// // Returns an adapted request that defines the player and team
|
||||
/// // scopes in the fetched row
|
||||
/// return request.adapted { db in
|
||||
/// let adapters = try splittingRowAdapters(columnCounts: [
|
||||
/// Player.numberOfSelectedColumns(db),
|
||||
/// Team.numberOfSelectedColumns(db),
|
||||
/// ])
|
||||
/// return ScopeAdapter([
|
||||
/// "player": adapters[0],
|
||||
/// "team": adapters[1],
|
||||
/// ])
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Usage
|
||||
/// try dbQueue.read { db in
|
||||
/// if let playerInfo = try PlayerInfo.filter(playerId: 1).fetchOne(db) {
|
||||
/// print(playerInfo.player) // Player(id: 1, name: "Arthur", teamId: 42)
|
||||
/// print(playerInfo.team) // Team(id: 42, name: "Reds")
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter columnCounts: An array of row chunk lengths.
|
||||
/// - returns: An array of row adapters that split a row into as many chunks
|
||||
/// as the number of elements in `columnCounts`, plus one (the row adapter
|
||||
/// for all columns that remain on the right of the last chunk).
|
||||
public func splittingRowAdapters(columnCounts: [Int]) -> [any RowAdapter] {
|
||||
guard !columnCounts.isEmpty else {
|
||||
if columnCounts.isEmpty {
|
||||
// Identity adapter
|
||||
return [SuffixRowAdapter(fromIndex: 0)]
|
||||
}
|
||||
@@ -149,25 +259,57 @@ extension Statement: _RowLayout {
|
||||
|
||||
/// A type that helps two incompatible row interfaces working together.
|
||||
///
|
||||
/// You provide row adapters to methods that fetch. For example:
|
||||
/// Row adapters present database rows in the way expected by the
|
||||
/// row consumers.
|
||||
///
|
||||
/// For example, when a row consumer expects a column named "consumed", but
|
||||
/// the raw row has a column named "produced", the ``ColumnMapping`` row
|
||||
/// adapter comes in handy:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read {
|
||||
/// // An adapter that ignores the first two columns
|
||||
/// let adapter = SuffixRowAdapter(fromIndex: 2)
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
|
||||
/// // Feeds the "consumed" column from "produced":
|
||||
/// let adapter = ColumnMapping(["consumed": "produced"])
|
||||
/// let sql = "SELECT 'Hello' AS produced"
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
///
|
||||
/// // [baz:3]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// }
|
||||
/// // [consumed:"Hello"]
|
||||
/// print(row)
|
||||
///
|
||||
/// // "Hello"
|
||||
/// print(row["consumed"])
|
||||
/// ```
|
||||
///
|
||||
/// The raw fetched columns are not lost (see ``Row/unadapted``):
|
||||
///
|
||||
/// ```swift
|
||||
/// // ▿ [consumed:"Hello"]
|
||||
/// // unadapted: [produced:"Hello"]
|
||||
/// print(row.debugDescription)
|
||||
///
|
||||
/// // [produced:"Hello"]
|
||||
/// print(row.unadapted)
|
||||
/// ```
|
||||
///
|
||||
/// There are several situations where row adapters are useful. Among them:
|
||||
///
|
||||
/// - Adapters help disambiguate columns with identical names, which may
|
||||
/// happen when you select columns from several tables.
|
||||
/// See ``splittingRowAdapters(columnCounts:)`` for some sample code.
|
||||
///
|
||||
/// - Adapters help when SQLite outputs unexpected column names, which may
|
||||
/// happen with some subqueries. See ``RenameColumnAdapter`` for
|
||||
/// an example.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Splitting a Row
|
||||
/// ### Splitting a Row into Chunks
|
||||
///
|
||||
/// - ``splittingRowAdapters(columnCounts:)``
|
||||
///
|
||||
/// ### Adding Scopes to an Adapter
|
||||
///
|
||||
/// - ``addingScopes(_:)``
|
||||
///
|
||||
/// ### Built-in Adapters
|
||||
///
|
||||
/// - ``ColumnMapping``
|
||||
@@ -222,9 +364,22 @@ extension RowAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/// EmptyRowAdapter is a row adapter that hides all columns.
|
||||
/// `EmptyRowAdapter` is a row adapter that hides all columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let adapter = EmptyRowAdapter()
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c"
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
/// row.isEmpty // true
|
||||
/// ```
|
||||
///
|
||||
/// This limit adapter may turn out useful in some narrow use cases. You'll
|
||||
/// be happy to find it when you need it.
|
||||
public struct EmptyRowAdapter: RowAdapter {
|
||||
/// Creates an EmptyRowAdapter
|
||||
/// Creates an `EmptyRowAdapter`.
|
||||
public init() { }
|
||||
|
||||
public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter {
|
||||
@@ -232,19 +387,28 @@ public struct EmptyRowAdapter: RowAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/// ColumnMapping is a row adapter that maps column names.
|
||||
/// `ColumnMapping` is a row adapter that maps column names.
|
||||
///
|
||||
/// let adapter = ColumnMapping(["foo": "bar"])
|
||||
/// let sql = "SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz"
|
||||
/// Build a `ColumnMapping` with a dictionary whose keys
|
||||
/// are adapted column names, and values the column names in the base row:
|
||||
///
|
||||
/// // [foo:"bar"]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// ```swift
|
||||
/// // Feeds "newA" from "a", and "newB" from "b":
|
||||
/// let adapter = ColumnMapping(["newA": "a", "newB": "b"])
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c"
|
||||
///
|
||||
/// // [newA:0, newB:1]
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
/// ```
|
||||
///
|
||||
/// Note that columns that are not present in the dictionary are not present
|
||||
/// in the resulting adapted row.
|
||||
public struct ColumnMapping: RowAdapter {
|
||||
/// A dictionary from mapped column names to column names in a base row.
|
||||
let mapping: [String: String]
|
||||
|
||||
/// Creates a ColumnMapping with a dictionary from mapped column names to
|
||||
/// column names in a base row.
|
||||
/// Creates a `ColumnMapping` with a dictionary from mapped column names
|
||||
/// to column names in a base row.
|
||||
public init(_ mapping: [String: String]) {
|
||||
self.mapping = mapping
|
||||
}
|
||||
@@ -269,13 +433,17 @@ public struct ColumnMapping: RowAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/// SuffixRowAdapter is a row adapter that hides the first columns in a row.
|
||||
/// `SuffixRowAdapter` hides the leftmost columns in a row.
|
||||
///
|
||||
/// let adapter = SuffixRowAdapter(fromIndex: 2)
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
|
||||
/// For example:
|
||||
///
|
||||
/// // [baz:3]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// ```swift
|
||||
/// let adapter = SuffixRowAdapter(fromIndex: 2)
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d"
|
||||
///
|
||||
/// // [c:2, d: 3]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
/// ```
|
||||
public struct SuffixRowAdapter: RowAdapter {
|
||||
/// The suffix index
|
||||
let index: Int
|
||||
@@ -294,13 +462,17 @@ public struct SuffixRowAdapter: RowAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/// RangeRowAdapter is a row adapter that only exposes a range of columns.
|
||||
/// `RangeRowAdapter` is a row adapter that only exposes a range of columns.
|
||||
///
|
||||
/// let adapter = RangeRowAdapter(1..<3)
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz, 4 as qux"
|
||||
/// For example:
|
||||
///
|
||||
/// // [bar:2 baz:3]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// ```swift
|
||||
/// let adapter = RangeRowAdapter(1..<3)
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d"
|
||||
///
|
||||
/// // [b:1 c:2]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// ```
|
||||
public struct RangeRowAdapter: RowAdapter {
|
||||
/// The range
|
||||
let range: CountableRange<Int>
|
||||
@@ -322,28 +494,65 @@ public struct RangeRowAdapter: RowAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/// `ScopeAdapter` is a row adapter that lets you define scopes on rows.
|
||||
/// `ScopeAdapter` is a row adapter that defines row scopes.
|
||||
///
|
||||
/// // Two adapters
|
||||
/// let fooAdapter = ColumnMapping(["value": "foo"])
|
||||
/// let barAdapter = ColumnMapping(["value": "bar"])
|
||||
/// `ScopeAdapter` does not change the columns and values of the fetched
|
||||
/// row. Instead, it defines *scopes* based on other adapter, which you
|
||||
/// access through the ``Row/scopes`` property of the fetched rows.
|
||||
///
|
||||
/// // Define scopes
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "foo": fooAdapter,
|
||||
/// "bar": barAdapter])
|
||||
/// For example:
|
||||
///
|
||||
/// // Fetch
|
||||
/// let sql = "SELECT 'foo' AS foo, 'bar' AS bar"
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
/// ```swift
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "left": RangeRowAdapter(0..<2),
|
||||
/// "right": RangeRowAdapter(2..<4)])
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d"
|
||||
///
|
||||
/// // Scoped rows:
|
||||
/// if let fooRow = row.scopes["foo"] {
|
||||
/// fooRow["value"] // "foo"
|
||||
/// }
|
||||
/// if let barRow = row.scopes["bar"] {
|
||||
/// barRow["value"] // "bar"
|
||||
/// }
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
///
|
||||
/// row // [a:0 b:1 c:2 d:3]
|
||||
/// row.scopes["left"] // [a:0 b:1]
|
||||
/// row.scopes["right"] // [c:2 d:3]
|
||||
/// row.scopes["missing"] // nil
|
||||
/// ```
|
||||
///
|
||||
/// Scopes can be nested:
|
||||
///
|
||||
/// ```swift
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "left": ScopeAdapter([
|
||||
/// "left": RangeRowAdapter(0..<1),
|
||||
/// "right": RangeRowAdapter(1..<2)]),
|
||||
/// "right": ScopeAdapter([
|
||||
/// "left": RangeRowAdapter(2..<3),
|
||||
/// "right": RangeRowAdapter(3..<4)])
|
||||
/// ])
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d"
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
///
|
||||
/// let leftRow = row.scopes["left"]!
|
||||
/// leftRow.scopes["left"] // [a:0]
|
||||
/// leftRow.scopes["right"] // [b:1]
|
||||
///
|
||||
/// let rightRow = row.scopes["right"]!
|
||||
/// rightRow.scopes["left"] // [c:2]
|
||||
/// rightRow.scopes["right"] // [d:3]
|
||||
/// ```
|
||||
///
|
||||
/// Any adapter can be extended with scopes, with
|
||||
/// ``RowAdapter/addingScopes(_:)``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let baseAdapter = RangeRowAdapter(0..<2)
|
||||
/// let adapter = baseAdapter.addingScopes([
|
||||
/// "remainder": SuffixRowAdapter(fromIndex: 2)
|
||||
/// ])
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d"
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
///
|
||||
/// row // [a:0 b:1]
|
||||
/// row.scopes["remainder"] // [c:2 d:3]
|
||||
/// ```
|
||||
public struct ScopeAdapter: RowAdapter {
|
||||
|
||||
/// The base adapter
|
||||
@@ -423,11 +632,29 @@ struct ChainedAdapter: RowAdapter {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let adapter = RenameColumnAdapter { $0 + "rrr" }
|
||||
/// let sql = "SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz"
|
||||
/// ```swift
|
||||
/// let adapter = RenameColumnAdapter { column in column + "rrr" }
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c"
|
||||
///
|
||||
/// // [foorrr:"foo", barrrr:"bar", bazrrr:"baz"]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// // [arrr:0, brrr:1, crrr:2]
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
/// ```
|
||||
///
|
||||
/// This adapter is useful when subqueries contain duplicated column names:
|
||||
///
|
||||
/// ```swift
|
||||
/// let sql = "SELECT * FROM (SELECT 1 AS id, 2 AS id)"
|
||||
///
|
||||
/// // Prints ["id", "id:1"]
|
||||
/// // Note the "id:1" column, generated by SQLite.
|
||||
/// let row = try Row.fetchOne(db, sql: sql)!
|
||||
/// print(Array(row.columnNames))
|
||||
///
|
||||
/// // Drop the `:...` suffix, and prints ["id", "id"]
|
||||
/// let adapter = RenameColumnAdapter { String($0.prefix(while: { $0 != ":" })) }
|
||||
/// let adaptedRow = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
/// print(Array(adaptedRow.columnNames))
|
||||
/// ```
|
||||
public struct RenameColumnAdapter: RowAdapter {
|
||||
let transform: (String) -> String
|
||||
|
||||
|
||||
@@ -14,6 +14,9 @@ final class SerializedDatabase {
|
||||
/// The dispatch queue
|
||||
private let queue: DispatchQueue
|
||||
|
||||
/// If true, overrides `configuration.allowsUnsafeTransactions`.
|
||||
private var allowsUnsafeTransactions = false
|
||||
|
||||
init(
|
||||
path: String,
|
||||
configuration: Configuration = Configuration(),
|
||||
@@ -76,10 +79,25 @@ final class SerializedDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a block the serialized dispatch queue, and
|
||||
/// returns its result.
|
||||
/// Executes database operations, returns their result after they have
|
||||
/// finished executing, and allows or forbids long-lived transactions.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
/// This method is not reentrant.
|
||||
///
|
||||
/// - parameter allowingLongLivedTransaction: When true, the
|
||||
/// ``Configuration/allowsUnsafeTransactions`` configuration flag is
|
||||
/// ignored until this method is called again with false.
|
||||
func sync<T>(allowingLongLivedTransaction: Bool, _ body: (Database) throws -> T) rethrows -> T {
|
||||
try sync { db in
|
||||
self.allowsUnsafeTransactions = allowingLongLivedTransaction
|
||||
return try body(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes database operations, and returns their result after they
|
||||
/// have finished executing.
|
||||
///
|
||||
/// This method is not reentrant.
|
||||
func sync<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
// Three different cases:
|
||||
//
|
||||
@@ -122,8 +140,23 @@ final class SerializedDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a block the serialized dispatch queue, and
|
||||
/// returns its result.
|
||||
/// Executes database operations, returns their result after they have
|
||||
/// finished executing, and allows or forbids long-lived transactions.
|
||||
///
|
||||
/// This method is reentrant.
|
||||
///
|
||||
/// - parameter allowingLongLivedTransaction: When true, the
|
||||
/// ``Configuration/allowsUnsafeTransactions`` configuration flag is
|
||||
/// ignored until this method is called again with false.
|
||||
func reentrantSync<T>(allowingLongLivedTransaction: Bool, _ body: (Database) throws -> T) rethrows -> T {
|
||||
try reentrantSync { db in
|
||||
self.allowsUnsafeTransactions = allowingLongLivedTransaction
|
||||
return try body(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes database operations, and returns their result after they
|
||||
/// have finished executing.
|
||||
///
|
||||
/// This method is reentrant.
|
||||
func reentrantSync<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
@@ -189,7 +222,7 @@ final class SerializedDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Asynchronously executes a block in the serialized dispatch queue.
|
||||
/// Schedules database operations for execution, and returns immediately.
|
||||
func async(_ block: @escaping (Database) -> Void) {
|
||||
queue.async {
|
||||
block(self.db)
|
||||
@@ -242,7 +275,7 @@ final class SerializedDatabase {
|
||||
line: UInt = #line)
|
||||
{
|
||||
GRDBPrecondition(
|
||||
configuration.allowsUnsafeTransactions || !db.isInsideTransaction,
|
||||
allowsUnsafeTransactions || configuration.allowsUnsafeTransactions || !db.isInsideTransaction,
|
||||
message(),
|
||||
file: file,
|
||||
line: line)
|
||||
|
||||
+333
-110
@@ -1,3 +1,4 @@
|
||||
import CryptoKit
|
||||
import Foundation
|
||||
|
||||
/// A raw SQLite statement, suitable for the SQLite C API.
|
||||
@@ -25,59 +26,6 @@ extension String {
|
||||
}
|
||||
}
|
||||
|
||||
/// A prepared statement.
|
||||
///
|
||||
/// You create prepared statements from a ``Database`` instance. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// DELETE FROM player WHERE id = ?
|
||||
/// """)
|
||||
/// try statement.execute(arguments: [1])!
|
||||
/// try statement.execute(arguments: [12])!
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// To fetch rows and values from a prepared statement, use a fetching method of
|
||||
///``Row``, ``DatabaseValueConvertible``, or ``FetchableRecord``:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// SELECT name FROM player WHERE id = ?
|
||||
/// """)
|
||||
/// let name1 = try String.fetchOne(statement, arguments: [1])!
|
||||
/// let name2 = try String.fetchOne(statement, arguments: [12])!
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/stmt.html>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Executing a Prepared Statement
|
||||
///
|
||||
/// - ``execute(arguments:)``
|
||||
///
|
||||
/// ### Arguments
|
||||
///
|
||||
/// - ``arguments``
|
||||
/// - ``setArguments(_:)``
|
||||
/// - ``setUncheckedArguments(_:)``
|
||||
/// - ``validateArguments(_:)``
|
||||
/// - ``StatementArguments``
|
||||
///
|
||||
/// ### Statement Informations
|
||||
///
|
||||
/// - ``columnCount``
|
||||
/// - ``columnNames``
|
||||
/// - ``databaseRegion``
|
||||
/// - ``index(ofColumn:)``
|
||||
/// - ``isReadonly``
|
||||
/// - ``sql``
|
||||
/// - ``sqliteStatement``
|
||||
/// - ``SQLiteStatement``
|
||||
public final class Statement {
|
||||
enum TransactionEffect {
|
||||
case beginTransaction
|
||||
@@ -109,6 +57,20 @@ public final class Statement {
|
||||
// refined in `SQLQueryGenerator.makeStatement(_:)` when we have enough
|
||||
// information about the statement.
|
||||
/// The database region that the statement looks into.
|
||||
///
|
||||
/// The returned region describes the tables and columns read by
|
||||
/// the statement. It does not describe the columns that the statement
|
||||
/// writes into. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Reads score, writes bonus
|
||||
/// let statement = db.makeStatement(sql: """
|
||||
/// UPDATE player SET bonus = 0 WHERE score = 0
|
||||
/// """)
|
||||
///
|
||||
/// // Prints "player(score)"
|
||||
/// print(statement.databaseRegion)
|
||||
/// ```
|
||||
public internal(set) var databaseRegion = DatabaseRegion()
|
||||
|
||||
/// If true, the database schema cache gets invalidated after this statement
|
||||
@@ -134,6 +96,23 @@ public final class Statement {
|
||||
authorizerEventKinds.contains(where: \.isDelete)
|
||||
}
|
||||
|
||||
/// A string that represented the statement in a lossless and
|
||||
/// unambiguous way.
|
||||
lazy var losslessDescription: String = {
|
||||
"\(sql); -- \(arguments.losslessDescription)"
|
||||
}()
|
||||
|
||||
/// A table name for caching the results of this statement
|
||||
lazy var cacheTableName: String? = {
|
||||
guard #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *),
|
||||
let losslessDescription = losslessDescription.data(using: .utf8)
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
let digest = Insecure.SHA1.hash(data: losslessDescription)
|
||||
return "grdb_cache_" + digest.map { String(format: "%02X", $0) }.joined()
|
||||
}()
|
||||
|
||||
@usableFromInline
|
||||
unowned let database: Database
|
||||
|
||||
@@ -209,25 +188,100 @@ public final class Statement {
|
||||
|
||||
// MARK: Arguments
|
||||
|
||||
private var argumentsNeedValidation = true
|
||||
/// Whether arguments are valid and bound inside the SQLite statement.
|
||||
///
|
||||
/// If true, arguments are considered valid, and they are bound in
|
||||
/// the SQLite statement:
|
||||
///
|
||||
/// - **Valid**: Arguments match the statement expectations, or the user has
|
||||
/// called ``setUncheckedArguments(_:)``.
|
||||
/// - **Bound**: The SQLite bindings are set. String and blob arguments
|
||||
/// are bound with SQLITE_TRANSIENT (copied and managed by SQLite).
|
||||
///
|
||||
/// When false, arguments have not been validated yet, or they are
|
||||
/// not bound.
|
||||
///
|
||||
/// - Not validated yet: this is the initial default (non-validated
|
||||
/// empty arguments)
|
||||
///
|
||||
/// ```swift
|
||||
/// // Default arguments are empty, argumentsAreValidAndBound is
|
||||
/// // false. The statement needs one argument.
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// INSERT INTO t VALUES (?)
|
||||
/// """)
|
||||
///
|
||||
/// // Because argumentsAreValidAndBound is false, we validate the
|
||||
/// // empty arguments, and throw SQLITE_MISUSE: wrong number
|
||||
/// // of statement arguments.
|
||||
/// try statement.execute()
|
||||
/// ```
|
||||
///
|
||||
/// - Not bound: this is the case after we have performed an optimized
|
||||
/// execution with temporary bindings that avoid copying strings
|
||||
/// and blobs:
|
||||
///
|
||||
/// ```swift
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// INSERT INTO t VALUES (?)
|
||||
/// """)
|
||||
/// // Arguments are set, and execution is performed with
|
||||
/// // temporary bindings.
|
||||
/// try statement.execute(arguments: ["Hello"])
|
||||
/// // <- Here statement.arguments is ["Hello"]
|
||||
/// // <- Here statement.argumentsAreValidAndBound is false
|
||||
/// ```
|
||||
///
|
||||
/// See `withArguments(_:do:)`.
|
||||
private var argumentsAreValidAndBound = false
|
||||
|
||||
/// The statement arguments. They may be bound, or not, in the SQLite
|
||||
/// statement. See `argumentsAreValidAndBound`.
|
||||
private var _arguments = StatementArguments()
|
||||
|
||||
lazy var sqliteArgumentCount: Int = {
|
||||
Int(sqlite3_bind_parameter_count(self.sqliteStatement))
|
||||
}()
|
||||
|
||||
// Returns ["id", nil", "name"] for "INSERT INTO table VALUES (:id, ?, :name)"
|
||||
// Returns ["id", nil, "name"] for "INSERT INTO table VALUES (:id, ?, :name)"
|
||||
fileprivate lazy var sqliteArgumentNames: [String?] = {
|
||||
(0..<CInt(self.sqliteArgumentCount)).map {
|
||||
guard let cString = sqlite3_bind_parameter_name(self.sqliteStatement, $0 + 1) else {
|
||||
(1..<CInt(sqliteArgumentCount + 1)).map {
|
||||
guard let cString = sqlite3_bind_parameter_name(sqliteStatement, $0) else {
|
||||
return nil
|
||||
}
|
||||
return String(String(cString: cString).dropFirst()) // Drop initial ":", "@", "$"
|
||||
return String(cString: cString + 1) // Drop initial ":", "@", "$"
|
||||
}
|
||||
}()
|
||||
|
||||
/// The statement arguments.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // This statement expects two arguments
|
||||
/// let statement = try db.makeUpdateArgument(sql: """
|
||||
/// INSERT INTO player (id, name) VALUES (?, ?)
|
||||
/// """)
|
||||
///
|
||||
/// // Set arguments
|
||||
/// statement.arguments = [1, "Arthur"]
|
||||
///
|
||||
/// // Prints [1, "Arthur"]
|
||||
/// print(statement.arguments)
|
||||
/// ```
|
||||
///
|
||||
/// If is a programmer error to set arguments that do not provide all
|
||||
/// values expected by the statement:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Fatal error
|
||||
/// statement.arguments = [1]
|
||||
/// statement.arguments = [1, "Arthur", Date()]
|
||||
/// ```
|
||||
///
|
||||
/// Prefer ``setArguments(_:)`` when you are not sure that
|
||||
/// arguments match, because it throws an error instead of raising a
|
||||
/// fatal error.
|
||||
public var arguments: StatementArguments {
|
||||
get { _arguments }
|
||||
set {
|
||||
@@ -237,12 +291,13 @@ public final class Statement {
|
||||
}
|
||||
}
|
||||
|
||||
/// Throws a ``DatabaseError`` of code `SQLITE_ERROR` if arguments don't
|
||||
/// fill all statement arguments.
|
||||
/// Throws a ``DatabaseError`` of code `SQLITE_ERROR` if the provided
|
||||
/// arguments do not provide all values expected by the statement.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // This statement expects two arguments
|
||||
/// let statement = try db.makeUpdateArgument(sql: """
|
||||
/// INSERT INTO player (id, name) VALUES (?, ?)
|
||||
/// """)
|
||||
@@ -251,7 +306,8 @@ public final class Statement {
|
||||
/// statement.validateArguments([1, "Arthur"])
|
||||
///
|
||||
/// // Throws
|
||||
/// statement.validateArguments([1])
|
||||
/// try statement.setArguments([1])
|
||||
/// try statement.setArguments([1, "Arthur", Date()])
|
||||
/// ```
|
||||
///
|
||||
/// See also ``setArguments(_:)``.
|
||||
@@ -264,12 +320,13 @@ public final class Statement {
|
||||
|
||||
/// Set arguments without any validation. Trades safety for performance.
|
||||
///
|
||||
/// Only call this method if you are sure input arguments match all expected
|
||||
/// arguments of the statement.
|
||||
/// Only call this method if you are sure input arguments provide all
|
||||
/// values expected by the statement.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // This statement expects two arguments
|
||||
/// let statement = try db.makeUpdateArgument(sql: """
|
||||
/// INSERT INTO player (id, name) VALUES (?, ?)
|
||||
/// """)
|
||||
@@ -278,18 +335,19 @@ public final class Statement {
|
||||
/// statement.setUncheckedArguments([1, "Arthur"])
|
||||
///
|
||||
/// // OK
|
||||
/// let arguments: StatementArguments = ... // some untrusted arguments
|
||||
/// let arguments = ... // some untrusted arguments
|
||||
/// try statement.validateArguments(arguments)
|
||||
/// statement.setUncheckedArguments(arguments)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// statement.setUncheckedArguments([1])
|
||||
/// statement.setUncheckedArguments([1, "Arthur", Date()])
|
||||
/// ```
|
||||
public func setUncheckedArguments(_ arguments: StatementArguments) {
|
||||
_arguments = arguments
|
||||
argumentsNeedValidation = false
|
||||
|
||||
// Reset and bind arguments
|
||||
try! reset()
|
||||
_arguments = arguments
|
||||
argumentsAreValidAndBound = true
|
||||
clearBindings()
|
||||
|
||||
var valuesIterator = arguments.values.makeIterator()
|
||||
@@ -302,14 +360,16 @@ public final class Statement {
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the statement arguments.
|
||||
/// Validates and sets the statement arguments.
|
||||
///
|
||||
/// This method throws a ``DatabaseError`` of code `SQLITE_ERROR` if
|
||||
/// arguments don't fill all statement arguments.
|
||||
/// This method throws a ``DatabaseError`` of code `SQLITE_MISUSE` if
|
||||
/// the provided arguments do not provide all values expected by
|
||||
/// the statement.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // This statement expects two arguments
|
||||
/// let statement = try db.makeUpdateArgument(sql: """
|
||||
/// INSERT INTO player (id, name) VALUES (?, ?)
|
||||
/// """)
|
||||
@@ -319,6 +379,7 @@ public final class Statement {
|
||||
///
|
||||
/// // Throws
|
||||
/// try statement.setArguments([1])
|
||||
/// try statement.setArguments([1, "Arthur", Date()])
|
||||
/// ```
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` if `arguments` don't fit the expected ones.
|
||||
@@ -327,16 +388,43 @@ public final class Statement {
|
||||
var consumedArguments = arguments
|
||||
let bindings = try consumedArguments.extractBindings(forStatement: self, allowingRemainingValues: false)
|
||||
|
||||
// Apply
|
||||
_arguments = arguments
|
||||
argumentsNeedValidation = false
|
||||
// Reset and bind arguments
|
||||
try reset()
|
||||
_arguments = arguments
|
||||
argumentsAreValidAndBound = true
|
||||
clearBindings()
|
||||
|
||||
for (index, dbValue) in zip(CInt(1)..., bindings) {
|
||||
bind(dbValue, at: index)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets, sets arguments, and calls the given closure after performing
|
||||
/// temporary bindings that avoid copying strings and blobs.
|
||||
///
|
||||
/// The bindings are valid only during the execution of this method.
|
||||
/// After it returns, the SQLite statement bindings are cleared (but the
|
||||
/// statement arguments are set).
|
||||
func withArguments<T>(_ arguments: StatementArguments, do body: () throws -> T) throws -> T {
|
||||
// Validate
|
||||
var consumedArguments = arguments
|
||||
let bindings = try consumedArguments.extractBindings(forStatement: self, allowingRemainingValues: false)
|
||||
|
||||
// Reset and bind arguments (temporarily)
|
||||
try reset()
|
||||
_arguments = arguments
|
||||
argumentsAreValidAndBound = false
|
||||
clearBindings()
|
||||
|
||||
defer {
|
||||
// Don't leave the SQLite statement in an invalid state
|
||||
// (temporary bindings that point to undefined memory).
|
||||
clearBindings()
|
||||
}
|
||||
|
||||
return try withBindings(bindings, to: sqliteStatement, do: body)
|
||||
}
|
||||
|
||||
// 1-based index
|
||||
func bind(_ value: some StatementBinding, at index: CInt) {
|
||||
let code = value.bind(to: sqliteStatement, at: index)
|
||||
@@ -369,14 +457,44 @@ public final class Statement {
|
||||
}
|
||||
}
|
||||
|
||||
func reset(withArguments arguments: StatementArguments?) throws {
|
||||
// Force arguments validity: it is a programmer error to provide
|
||||
// arguments that do not match the statement.
|
||||
if let arguments {
|
||||
try setArguments(arguments)
|
||||
} else if argumentsNeedValidation {
|
||||
/// Convenience method that resets, sets arguments if needed, and checks
|
||||
/// arguments validity.
|
||||
///
|
||||
/// - parameter newArguments: if not nil, this method sets arguments.
|
||||
func prepareExecution(withArguments newArguments: StatementArguments? = nil) throws {
|
||||
if let newArguments {
|
||||
try setArguments(newArguments) // calls reset()
|
||||
return
|
||||
}
|
||||
|
||||
if argumentsAreValidAndBound {
|
||||
try reset()
|
||||
try validateArguments(self.arguments)
|
||||
} else {
|
||||
// Arguments needs to be validated, or bound.
|
||||
if arguments.isEmpty {
|
||||
// Only reset and perform validation.
|
||||
try reset()
|
||||
try validateArguments(arguments)
|
||||
} else {
|
||||
// The `setArguments` method binds and validates, and that's
|
||||
// exactly what we want to do.
|
||||
//
|
||||
// To get there, perform statement.execute() after
|
||||
// statement.execute(arguments:):
|
||||
//
|
||||
// // Step 1
|
||||
// // Optimized execution with temporary bindings in order
|
||||
// // to avoid copying strings and blobs: after execution,
|
||||
// // arguments are set, but bindings have been cleared,
|
||||
// // and argumentsAreValidAndBound is false.
|
||||
// try statement.execute(arguments: StatementArguments(person)!)
|
||||
//
|
||||
// // Step 2 (we are here). Stop using temporary
|
||||
// // bindings because user explicitly opt ins for
|
||||
// // permanent ones.
|
||||
// try statement.execute()
|
||||
try setArguments(arguments) // calls reset()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -385,35 +503,83 @@ public final class Statement {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// try dbQueue.write { db in
|
||||
/// // Statement without argument
|
||||
/// let createTableStatement = try db.makeStatement(sql: """
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// CREATE TABLE player (
|
||||
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
/// name TEXT NOT NULL
|
||||
/// )
|
||||
/// """)
|
||||
/// try createTableStatement.execute()
|
||||
/// try statement.execute()
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// // Statement with argument
|
||||
/// let insertStatement = try db.makeStatement(sql: """
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?)
|
||||
/// """)
|
||||
///
|
||||
/// // Set argument and execute
|
||||
/// try insertStatement.setArguments(["Arthur"])
|
||||
/// try insertStatement.execute()
|
||||
/// try statement.setArguments(["Arthur"])
|
||||
/// try statement.execute()
|
||||
///
|
||||
/// // Set argument and execute in one shot
|
||||
/// try insertStatement.execute(arguments: ["Barbara"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When arguments are set at the moment of execution, with an non-nil
|
||||
/// `arguments` parameter, it is assumed that the statement won't be
|
||||
/// reused with the same arguments. When the number of arguments is
|
||||
/// small, execution is performed with temporary SQLite bindings that
|
||||
/// avoid copying strings and blobs arguments.
|
||||
///
|
||||
/// For more information, see [`SQLITE_STATIC` and `SQLITE_TRANSIENT`](https://www.sqlite.org/c3ref/c_static.html).
|
||||
/// Compare:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Uses SQLITE_STATIC if there are few arguments,
|
||||
/// // SQLITE_TRANSIENT otherwise.
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// // Always uses SQLITE_TRANSIENT
|
||||
/// try statement.setArguments(["Arthur"])
|
||||
/// try statement.execute()
|
||||
/// ```
|
||||
///
|
||||
/// Both techniques have the same results, but when you care about
|
||||
/// performances, monitor your application in order to make the
|
||||
/// best choice.
|
||||
///
|
||||
/// - parameter arguments: Optional statement arguments.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func execute(arguments: StatementArguments? = nil) throws {
|
||||
try reset(withArguments: arguments)
|
||||
if let arguments {
|
||||
// Assume that the statement won't be reused with the same arguments.
|
||||
//
|
||||
// Avoid a stack overflow, and don't perform an unbounded nesting
|
||||
// of `withBinding(to:at:do:)` methods: only use temporary bindings
|
||||
// for less than 20 arguments. This number 20 is completely
|
||||
// arbitrary!
|
||||
// See <https://forums.swift.org/t/avoiding-stack-overflow-when-nesting-string-withcstring-how-to-handle-an-arbitrary-number-of-temp-values-in-general/63663>
|
||||
if sqliteArgumentCount <= 20 {
|
||||
// Perform an optimized execution with temporary bindings
|
||||
// in order to avoid copying strings and blobs.
|
||||
try withArguments(arguments) {
|
||||
try executeAllSteps()
|
||||
}
|
||||
} else {
|
||||
try setArguments(arguments)
|
||||
try executeAllSteps()
|
||||
}
|
||||
} else {
|
||||
try prepareExecution()
|
||||
try executeAllSteps()
|
||||
}
|
||||
}
|
||||
|
||||
private func executeAllSteps() throws {
|
||||
try database.statementWillExecute(self)
|
||||
|
||||
// Iterate all rows, since they may execute side effects.
|
||||
@@ -631,10 +797,7 @@ final class StatementCursor: DatabaseCursor {
|
||||
|
||||
// Use Statement.makeCursor() instead
|
||||
init(statement: Statement, arguments: StatementArguments? = nil) throws {
|
||||
self._statement = statement
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
try statement.reset(withArguments: arguments)
|
||||
_statement = try statement.databaseCursorStatement(with: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -679,11 +842,50 @@ public protocol StatementBinding {
|
||||
/// Binds a statement argument.
|
||||
///
|
||||
/// - parameter sqliteStatement: An SQLite statement.
|
||||
/// - parameter index: 1-based index to statement arguments
|
||||
/// - parameter index: 1-based index to statement arguments.
|
||||
/// - returns: the code returned by the `sqlite3_bind_xxx` function.
|
||||
func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt
|
||||
}
|
||||
|
||||
/// Helper function for `withBinding(to:at:do:)` methods.
|
||||
func checkBindingSuccess(code: CInt, sqliteStatement: SQLiteStatement) throws {
|
||||
if code == SQLITE_OK { return }
|
||||
let message = String(cString: sqlite3_errmsg(sqlite3_db_handle(sqliteStatement)))
|
||||
let sql = String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
|
||||
throw DatabaseError(resultCode: code, message: message, sql: sql)
|
||||
}
|
||||
|
||||
/// Calls the given closure after performing temporary bindings that avoid
|
||||
/// copying strings and blobs.
|
||||
///
|
||||
/// The bindings are valid only during the execution of this method.
|
||||
///
|
||||
/// - parameter bindings: The bindings
|
||||
/// - parameter sqliteStatement: The SQLite statement
|
||||
/// - parameter index: The index of the first binding.
|
||||
/// - parameter body: The closure to execute when arguments are bound.
|
||||
@usableFromInline
|
||||
func withBindings<C, T>(
|
||||
_ bindings: C,
|
||||
to sqliteStatement: SQLiteStatement,
|
||||
from index: CInt = 1,
|
||||
do body: () throws -> T)
|
||||
throws -> T
|
||||
where C: Collection, C.Element == DatabaseValue
|
||||
{
|
||||
guard let binding = bindings.first else {
|
||||
return try body()
|
||||
}
|
||||
|
||||
return try binding.withBinding(to: sqliteStatement, at: index) {
|
||||
try withBindings(
|
||||
bindings.dropFirst(),
|
||||
to: sqliteStatement,
|
||||
from: index + 1,
|
||||
do: body)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - StatementArguments
|
||||
|
||||
/// An instance of `StatementArguments` provides the values for argument
|
||||
@@ -699,9 +901,9 @@ public protocol StatementBinding {
|
||||
/// - `@AAAA` (e.g. `@name`): named argument
|
||||
/// - `$AAAA` (e.g. `$name`): named argument
|
||||
///
|
||||
/// GRDB does not allow to distinguish between the `:AAAA`, `@AAAA`, and `$AAAA`
|
||||
/// syntaxes. You are encouraged to write named arguments with a
|
||||
/// colon prefix: `:name`.
|
||||
/// All forms are supported, but GRDB does not allow to distinguish between
|
||||
/// the `:AAAA`, `@AAAA`, and `$AAAA` syntaxes. You are encouraged to write
|
||||
/// named arguments with a colon prefix: `:name`.
|
||||
///
|
||||
/// ## Positional Arguments
|
||||
///
|
||||
@@ -1120,36 +1322,42 @@ public struct StatementArguments: Hashable {
|
||||
allowingRemainingValues: Bool)
|
||||
throws -> [DatabaseValue]
|
||||
{
|
||||
let initialValuesCount = values.count
|
||||
var iterator = values.makeIterator()
|
||||
var consumedValuesCount = 0
|
||||
let bindings = try statement.sqliteArgumentNames.map { argumentName -> DatabaseValue in
|
||||
if let argumentName {
|
||||
if let dbValue = namedValues[argumentName] {
|
||||
return dbValue
|
||||
} else if values.isEmpty {
|
||||
} else if let value = iterator.next() {
|
||||
consumedValuesCount += 1
|
||||
return value
|
||||
} else {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: "missing statement argument: \(argumentName)",
|
||||
sql: statement.sql)
|
||||
} else {
|
||||
return values.removeFirst()
|
||||
}
|
||||
} else if let value = iterator.next() {
|
||||
consumedValuesCount += 1
|
||||
return value
|
||||
} else {
|
||||
if values.isEmpty {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: "wrong number of statement arguments: \(initialValuesCount)",
|
||||
sql: statement.sql)
|
||||
} else {
|
||||
return values.removeFirst()
|
||||
}
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: "wrong number of statement arguments: \(values.count)",
|
||||
sql: statement.sql)
|
||||
}
|
||||
}
|
||||
if !allowingRemainingValues && !values.isEmpty {
|
||||
if !allowingRemainingValues && iterator.next() != nil {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: "wrong number of statement arguments: \(initialValuesCount)",
|
||||
message: "wrong number of statement arguments: \(values.count)",
|
||||
sql: statement.sql)
|
||||
}
|
||||
if consumedValuesCount == values.count {
|
||||
values.removeAll()
|
||||
} else {
|
||||
values = Array(values[consumedValuesCount...])
|
||||
}
|
||||
return bindings
|
||||
}
|
||||
}
|
||||
@@ -1196,4 +1404,19 @@ extension StatementArguments: CustomStringConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
extension StatementArguments {
|
||||
/// A string that represented the value in a lossless and
|
||||
/// unambiguous way.
|
||||
var losslessDescription: String {
|
||||
var chunks: [String] = []
|
||||
for value in values {
|
||||
chunks.append(value.losslessDescription)
|
||||
}
|
||||
for (key, value) in namedValues.sorted(by: { $0.key < $1.key }) {
|
||||
chunks.append("\(key): \(value.losslessDescription)")
|
||||
}
|
||||
return chunks.joined(separator: ",")
|
||||
}
|
||||
}
|
||||
|
||||
extension StatementArguments: Sendable { }
|
||||
@@ -12,7 +12,7 @@
|
||||
/// // Optimized
|
||||
/// let scores = Int.fetchAll(db, sql: "SELECT score FROM player")
|
||||
///
|
||||
/// let rows = Row.fetchCursor(db, sql: "SELECT * FROM player")
|
||||
/// let rows = try Row.fetchCursor(db, sql: "SELECT * FROM player")
|
||||
/// while let row = try rows.next() {
|
||||
/// // Optimized
|
||||
/// let int: Int = row[0]
|
||||
@@ -214,6 +214,7 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
@usableFromInline let columnIndex: CInt
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
|
||||
let statement = try statement.databaseCursorStatement(with: arguments)
|
||||
self._statement = statement
|
||||
if let adapter {
|
||||
// adapter may redefine the index of the leftmost column
|
||||
@@ -221,9 +222,6 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
} else {
|
||||
columnIndex = 0
|
||||
}
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
try statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
|
||||
@@ -42,6 +42,23 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
sqlite3_bind_blob(sqliteStatement, index, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls the given closure after binding a statement argument.
|
||||
///
|
||||
/// The binding is valid only during the execution of this method.
|
||||
///
|
||||
/// - parameter sqliteStatement: An SQLite statement.
|
||||
/// - parameter index: 1-based index to statement arguments.
|
||||
/// - parameter body: The closure to execute when argument is bound.
|
||||
func withBinding<T>(to sqliteStatement: SQLiteStatement, at index: CInt, do body: () throws -> T) throws -> T {
|
||||
try withUnsafeBytes {
|
||||
let code = sqlite3_bind_blob(
|
||||
sqliteStatement, index,
|
||||
$0.baseAddress, CInt($0.count), nil /* SQLITE_STATIC */)
|
||||
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
|
||||
return try body()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Conversions
|
||||
|
||||
@@ -610,6 +610,21 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_text(sqliteStatement, index, self, -1, SQLITE_TRANSIENT)
|
||||
}
|
||||
|
||||
/// Calls the given closure after binding a statement argument.
|
||||
///
|
||||
/// The binding is valid only during the execution of this method.
|
||||
///
|
||||
/// - parameter sqliteStatement: An SQLite statement.
|
||||
/// - parameter index: 1-based index to statement arguments.
|
||||
/// - parameter body: The closure to execute when argument is bound.
|
||||
func withBinding<T>(to sqliteStatement: SQLiteStatement, at index: CInt, do body: () throws -> T) throws -> T {
|
||||
try withCString {
|
||||
let code = sqlite3_bind_text(sqliteStatement, index, $0, -1, nil /* SQLITE_STATIC */)
|
||||
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
|
||||
return try body()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -739,311 +739,6 @@ class DatabaseObservationBroker {
|
||||
|
||||
// MARK: - TransactionObserver
|
||||
|
||||
/// A type that tracks database changes and transactions performed in
|
||||
/// a database.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// `TransactionObserver` is the low-level protocol that supports all
|
||||
/// <doc:DatabaseObservation> features.
|
||||
///
|
||||
/// A transaction observer is notified of individual changes (inserts, updates
|
||||
/// and deletes), before they are committed to disk, as well as transaction
|
||||
/// commits and rollbacks.
|
||||
///
|
||||
/// ## Activate a Transaction Observer
|
||||
///
|
||||
/// An observer starts receiving change notifications after it has been added to
|
||||
/// a database connection with the
|
||||
/// ``DatabaseWriter/add(transactionObserver:extent:)`` `DatabaseWriter` method,
|
||||
/// or the ``Database/add(transactionObserver:extent:)`` `Database` method:
|
||||
///
|
||||
/// ```swift
|
||||
/// let observer = MyObserver()
|
||||
/// dbQueue.add(transactionObserver: observer)
|
||||
/// ```
|
||||
///
|
||||
/// By default, database holds weak references to its transaction observers:
|
||||
/// they are not retained, and stop getting notifications after they are
|
||||
/// deallocated. See <doc:TransactionObserver#Observation-Extent> for
|
||||
/// more options.
|
||||
///
|
||||
/// ## Database Changes And Transactions
|
||||
///
|
||||
/// Database changes are notified to the ``databaseDidChange(with:)`` callback.
|
||||
/// This includes indirect changes triggered by `ON DELETE` and `ON UPDATE`
|
||||
/// actions associated to
|
||||
/// [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions), and
|
||||
/// [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
|
||||
///
|
||||
/// Transaction completions are notified to the ``databaseWillCommit()-7mksu``,
|
||||
/// ``databaseDidCommit(_:)`` and ``databaseDidRollback(_:)`` callbacks.
|
||||
///
|
||||
/// Read-only transactions, changes and transactions performed by external
|
||||
/// database connections, changes to internal system tables (such as
|
||||
/// `sqlite_master`), changes to
|
||||
/// [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables, and the
|
||||
/// deletion of duplicate rows triggered by
|
||||
/// [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses
|
||||
/// (this last exception might change in a future release of SQLite) are
|
||||
/// not notified.
|
||||
///
|
||||
/// Notified changes are not actually written to disk until the transaction
|
||||
/// commits, and the `databaseDidCommit` callback is called. On the other
|
||||
/// side, `databaseDidRollback` confirms their invalidation:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// try db.execute(sql: "INSERT ...") // 1. didChange
|
||||
/// try db.execute(sql: "UPDATE ...") // 2. didChange
|
||||
/// } // 3. willCommit, 4. didCommit
|
||||
///
|
||||
/// try dbQueue.inTransaction { db in
|
||||
/// try db.execute(sql: "INSERT ...") // 1. didChange
|
||||
/// try db.execute(sql: "UPDATE ...") // 2. didChange
|
||||
/// return .rollback // 3. didRollback
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// try db.execute(sql: "INSERT ...") // 1. didChange
|
||||
/// throw SomeError()
|
||||
/// } // 2. didRollback
|
||||
/// ```
|
||||
///
|
||||
/// Database statements that are executed outside of any explicit transaction
|
||||
/// do not drop off the radar:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.writeWithoutTransaction { db in
|
||||
/// try db.execute(sql: "INSERT ...") // 1. didChange, 2. willCommit, 3. didCommit
|
||||
/// try db.execute(sql: "UPDATE ...") // 4. didChange, 5. willCommit, 6. didCommit
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Changes that are on hold because of a
|
||||
/// [savepoint](https://www.sqlite.org/lang_savepoint.html) are only notified
|
||||
/// after the savepoint has been released. This makes sure that notified events
|
||||
/// are only those that have an opportunity to be committed:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.inTransaction { db in
|
||||
/// try db.execute(sql: "INSERT ...") // 1. didChange
|
||||
///
|
||||
/// try db.execute(sql: "SAVEPOINT foo")
|
||||
/// try db.execute(sql: "UPDATE ...") // delayed
|
||||
/// try db.execute(sql: "UPDATE ...") // delayed
|
||||
/// try db.execute(sql: "RELEASE SAVEPOINT foo") // 2. didChange, 3. didChange
|
||||
///
|
||||
/// try db.execute(sql: "SAVEPOINT bar")
|
||||
/// try db.execute(sql: "UPDATE ...") // not notified
|
||||
/// try db.execute(sql: "ROLLBACK TO SAVEPOINT bar")
|
||||
/// try db.execute(sql: "RELEASE SAVEPOINT bar")
|
||||
///
|
||||
/// return .commit // 4. willCommit, 5. didCommit
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Eventual errors thrown from `databaseWillCommit` are exposed to the
|
||||
/// application code:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// try dbQueue.inTransaction { db in
|
||||
/// ...
|
||||
/// return .commit // 1. willCommit (throws), 2. didRollback
|
||||
/// }
|
||||
/// } catch {
|
||||
/// // 3. The error thrown by the transaction observer.
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - Note: All callbacks are called in the writer dispatch queue, and
|
||||
/// serialized with all database updates.
|
||||
///
|
||||
/// - Note: The `databaseDidChange` and `databaseWillCommit` callbacks must not
|
||||
/// touch the SQLite database. This limitation does not apply to
|
||||
/// `databaseDidCommit` and `databaseDidRollback` which can use their
|
||||
/// database argument.
|
||||
///
|
||||
/// ## Filtering Database Events
|
||||
///
|
||||
/// **Transaction observers can choose the database changes they are
|
||||
/// interested in.**
|
||||
///
|
||||
/// The filtering happens in the ``observes(eventsOfKind:)`` method, which tells
|
||||
/// whether the observer wants notifications of specific kinds of changes,
|
||||
/// or not.
|
||||
///
|
||||
/// The ``DatabaseEventKind`` argument of `observes(eventsOfKind:)` can
|
||||
/// distinguish insertions from deletions and updates, and is also able to
|
||||
/// tell the columns that are about to be changed.
|
||||
///
|
||||
/// For example, an observer can focus on the changes that happen on the
|
||||
/// "player" database table only:
|
||||
///
|
||||
/// ```swift
|
||||
/// class PlayerObserver: TransactionObserver {
|
||||
/// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
/// // Only observe changes to the "player" table.
|
||||
/// eventKind.tableName == "player"
|
||||
/// }
|
||||
///
|
||||
/// func databaseDidChange(with event: DatabaseEvent) {
|
||||
/// // This method is only called for changes that happen to
|
||||
/// // the "player" table.
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When the `observes(eventsOfKind:)` method returns false for all event kinds,
|
||||
/// the observer is still notified of transactions.
|
||||
///
|
||||
/// ## Observation Extent
|
||||
///
|
||||
/// **You can specify how long an observer is notified of database changes
|
||||
/// and transactions.**
|
||||
///
|
||||
/// The `remove(transactionObserver:)` method explicitly stops notifications,
|
||||
/// at any time:
|
||||
///
|
||||
/// ```swift
|
||||
/// // From a database queue or pool:
|
||||
/// dbQueue.remove(transactionObserver: observer)
|
||||
///
|
||||
/// // From a database connection:
|
||||
/// dbQueue.inDatabase { db in
|
||||
/// db.remove(transactionObserver: observer)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Alternatively, use the `extent` parameter of the
|
||||
/// `add(transactionObserver:extent:)` method:
|
||||
///
|
||||
/// ```swift
|
||||
/// let observer = MyObserver()
|
||||
///
|
||||
/// // On a database queue or pool:
|
||||
/// dbQueue.add(transactionObserver: observer) // default extent
|
||||
/// dbQueue.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
/// dbQueue.add(transactionObserver: observer, extent: .nextTransaction)
|
||||
/// dbQueue.add(transactionObserver: observer, extent: .databaseLifetime)
|
||||
///
|
||||
/// // On a database connection:
|
||||
/// dbQueue.inDatabase { db in
|
||||
/// db.add(transactionObserver: ...)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - The default extent is `.observerLifetime`: the database holds a weak
|
||||
/// reference to the observer, and the observation automatically ends when the
|
||||
/// observer is deallocated. Meanwhile, the observer is notified of all changes
|
||||
/// and transactions.
|
||||
///
|
||||
/// - `.nextTransaction` activates the observer until the current or next
|
||||
/// transaction completes. The database keeps a strong reference to the observer
|
||||
/// until its `databaseDidCommit` or `databaseDidRollback` callback is called.
|
||||
/// Hereafter the observer won't get any further notification.
|
||||
///
|
||||
/// - `.databaseLifetime` has the database retain and notify the observer until
|
||||
/// the database connection is closed.
|
||||
///
|
||||
/// Finally, an observer can avoid processing database changes until the end
|
||||
/// of the current transaction. After
|
||||
/// ``stopObservingDatabaseChangesUntilNextTransaction()``, the
|
||||
/// `databaseDidChange` callback will not be called until the current
|
||||
/// transaction completes:
|
||||
///
|
||||
/// ```swift
|
||||
/// class PlayerObserver: TransactionObserver {
|
||||
/// var playerTableWasModified = false
|
||||
///
|
||||
/// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
/// eventKind.tableName == "player"
|
||||
/// }
|
||||
///
|
||||
/// func databaseDidChange(with event: DatabaseEvent) {
|
||||
/// playerTableWasModified = true
|
||||
///
|
||||
/// // It is pointless to keep on tracking further changes:
|
||||
/// stopObservingDatabaseChangesUntilNextTransaction()
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ### Support for SQLite Pre-Update Hooks
|
||||
///
|
||||
/// When SQLite is built with the `SQLITE_ENABLE_PREUPDATE_HOOK` option,
|
||||
/// `TransactionObserver` gets an extra callback which lets you observe
|
||||
/// individual column values in the rows modified by a transaction:
|
||||
///
|
||||
/// ```swift
|
||||
/// protocol TransactionObserver: AnyObject {
|
||||
/// #if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
/// /// Notifies before a database change (insert, update, or delete)
|
||||
/// /// with change information (initial / final values for the row's
|
||||
/// /// columns).
|
||||
/// ///
|
||||
/// /// The event is only valid for the duration of this method call. If you
|
||||
/// /// need to keep it longer, store a copy: event.copy().
|
||||
/// func databaseWillChange(with event: DatabasePreUpdateEvent)
|
||||
/// #endif
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This extra API can be activated in two ways:
|
||||
///
|
||||
/// 1. Use the GRDB.swift CocoaPod with a custom compilation option, as below.
|
||||
/// It uses the system SQLite, which is compiled with
|
||||
/// `SQLITE_ENABLE_PREUPDATE_HOOK` support, but only on iOS 11.0+ (we don't
|
||||
/// know the minimum version of macOS, tvOS, watchOS):
|
||||
///
|
||||
/// ```ruby
|
||||
/// pod 'GRDB.swift'
|
||||
/// platform :ios, '11.0' # or above
|
||||
///
|
||||
/// post_install do |installer|
|
||||
/// installer.pods_project.targets.select { |target| target.name == "GRDB.swift" }.each do |target|
|
||||
/// target.build_configurations.each do |config|
|
||||
/// # Enable extra GRDB APIs
|
||||
/// config.build_settings['OTHER_SWIFT_FLAGS'] = "$(inherited) -D SQLITE_ENABLE_PREUPDATE_HOOK"
|
||||
/// # Enable extra SQLite APIs
|
||||
/// config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = "$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1"
|
||||
/// end
|
||||
/// end
|
||||
/// end
|
||||
/// ```
|
||||
///
|
||||
/// **Warning**: make sure you use the right platform version! You will get
|
||||
/// runtime errors on devices with a lower version.
|
||||
///
|
||||
/// **Note**: the `GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1` option in
|
||||
/// `GCC_PREPROCESSOR_DEFINITIONS` defines some C function prototypes that
|
||||
/// are lacking from the system `<sqlite3.h>` header. When Xcode eventually
|
||||
/// ships with an SDK that includes a complete header, you may get a
|
||||
/// compiler error about duplicate function definitions. When this happens,
|
||||
/// just remove this `GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1` option.
|
||||
///
|
||||
/// 2. Use a [custom SQLite build](http://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md)
|
||||
/// and activate the `SQLITE_ENABLE_PREUPDATE_HOOK` compilation option.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Filtering Database Changes
|
||||
///
|
||||
/// - ``observes(eventsOfKind:)``
|
||||
/// - ``DatabaseEventKind``
|
||||
///
|
||||
/// ### Handling Database Changes
|
||||
///
|
||||
/// - ``databaseDidChange(with:)``
|
||||
/// - ``stopObservingDatabaseChangesUntilNextTransaction()``
|
||||
/// - ``DatabaseEvent``
|
||||
///
|
||||
/// ### Handling Transactions
|
||||
///
|
||||
/// - ``databaseWillCommit()-7mksu``
|
||||
/// - ``databaseDidCommit(_:)``
|
||||
/// - ``databaseDidRollback(_:)``
|
||||
public protocol TransactionObserver: AnyObject {
|
||||
|
||||
/// Returns whether specific kinds of database changes should be notified
|
||||
@@ -1066,7 +761,7 @@ public protocol TransactionObserver: AnyObject {
|
||||
/// When this method returns true for deletion events, the observer
|
||||
/// prevents the
|
||||
/// [truncate optimization](https://www.sqlite.org/lang_delete.html#the_truncate_optimization)
|
||||
/// from being applied.
|
||||
/// from being applied on the observed tables.
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
|
||||
|
||||
/// Called when the database is changed by an insert, update, or
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
// 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).
|
||||
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
|
||||
|
||||
/// Creates a long-live WAL transaction on a read-only connection.
|
||||
///
|
||||
/// The `release` closure is always called. It is called when the
|
||||
/// `WALSnapshotTransaction` is deallocated, or if the initializer
|
||||
/// throws.
|
||||
///
|
||||
/// In normal operations, the argument to `release` is always false,
|
||||
/// meaning that the connection is no longer in a transaction. If true,
|
||||
/// the connection has been left inside a transaction, due to
|
||||
/// some error.
|
||||
///
|
||||
/// Usage:
|
||||
///
|
||||
/// ```swift
|
||||
/// let transaction = WALSnapshotTransaction(
|
||||
/// reader: reader,
|
||||
/// release: { isInsideTransaction in
|
||||
/// ...
|
||||
/// })
|
||||
/// ```
|
||||
///
|
||||
/// - parameter reader: A read-only database connection.
|
||||
/// - parameter release: A closure to call when the read-only connection
|
||||
/// is no longer used.
|
||||
init(
|
||||
onReader reader: SerializedDatabase,
|
||||
release: @escaping (_ isInsideTransaction: Bool) -> Void)
|
||||
throws
|
||||
{
|
||||
assert(reader.configuration.readonly)
|
||||
|
||||
do {
|
||||
// Open a long-lived transaction, and enter snapshot isolation
|
||||
self.walSnapshot = try reader.sync(allowingLongLivedTransaction: true) { db in
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
|
||||
return try WALSnapshot(db)
|
||||
}
|
||||
self.reader = reader
|
||||
self.release = release
|
||||
} catch {
|
||||
// self is not initialized, so deinit will not run.
|
||||
Self.commitAndRelease(reader: reader, release: release)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
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) 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 (Database) -> Void) {
|
||||
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
|
||||
reader.async(value)
|
||||
}
|
||||
|
||||
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
|
||||
@@ -22,6 +22,73 @@ The differences are:
|
||||
|
||||
**If you are not sure, choose `DatabaseQueue`.** You will always be able to switch to `DatabasePool` later.
|
||||
|
||||
## Opening a Connection
|
||||
|
||||
You need a path to a database file in order to open a database connection.
|
||||
|
||||
**When the SQLite file is ready-made, and you do not intend to modify its content**, then add the database file as a [resource of your Xcode project or Swift package](https://developer.apple.com/documentation/xcode), and open a read-only database connection:
|
||||
|
||||
```swift
|
||||
// HOW TO open a read-only connection to a database resource
|
||||
|
||||
// Get the path to the database resource.
|
||||
// Replace `Bundle.main` with `Bundle.module` when you write a Swift Package.
|
||||
if let dbPath = Bundle.main.path(forResource: "db", ofType: "sqlite")
|
||||
|
||||
if let dbPath {
|
||||
// If the resource exists, open a read-only connection.
|
||||
// Writes are disallowed because resources can not be modified.
|
||||
var config = Configuration()
|
||||
config.readonly = true
|
||||
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
|
||||
} else {
|
||||
// The database resource can not be found.
|
||||
// Fix your setup, or report the problem to the user.
|
||||
}
|
||||
```
|
||||
|
||||
**If the application creates or writes in the database**, then first choose a proper location for the database file. Document-based applications will let the user pick a location. Apps that use the database as a global storage will prefer the Application Support directory.
|
||||
|
||||
> Tip: Regardless of the database location, it is recommended that you wrap the database file inside a dedicated directory. This directory will bundle the main database file and its related [SQLite temporary files](https://www.sqlite.org/tempfiles.html) together.
|
||||
>
|
||||
> The dedicated directory helps moving or deleting the whole database when needed: just move or delete the directory.
|
||||
>
|
||||
> On iOS, the directory can be encrypted with [data protection](https://developer.apple.com/documentation/uikit/protecting_the_user_s_privacy/encrypting_your_app_s_files), in order to help securing all database files in one shot. When a database is protected, an application that runs in the background on a locked device won't be able to read or write from it. Instead, it will catch ``DatabaseError`` with code [`SQLITE_IOERR`](https://www.sqlite.org/rescode.html#ioerr) (10) "disk I/O error", or [`SQLITE_AUTH`](https://www.sqlite.org/rescode.html#auth) (23) "not authorized".
|
||||
|
||||
The sample code below creates or opens a database file inside its dedicated directory. On the first run, a new empty database file is created. On subsequent runs, the directory and database file already exist, so it just opens a connection:
|
||||
|
||||
```swift
|
||||
// HOW TO create an empty database, or open an existing database file
|
||||
|
||||
// Create the "Application Support/MyDatabase" directory if needed
|
||||
let fileManager = FileManager.default
|
||||
let appSupportURL = try fileManager.url(
|
||||
for: .applicationSupportDirectory, in: .userDomainMask,
|
||||
appropriateFor: nil, create: true)
|
||||
let directoryURL = appSupportURL.appendingPathComponent("MyDatabase", isDirectory: true)
|
||||
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
|
||||
|
||||
// Open or create the database
|
||||
let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
|
||||
let dbQueue = try DatabaseQueue(path: databaseURL.path)
|
||||
```
|
||||
|
||||
## Closing Connections
|
||||
|
||||
Database connections are automatically closed when ``DatabaseQueue`` or ``DatabasePool`` instances are deinitialized.
|
||||
|
||||
If the correct execution of your program depends on precise database closing, perform an explicit call to ``DatabaseReader/close()``. This method may fail and create zombie connections, so please check its detailed documentation.
|
||||
|
||||
|
||||
## Next Steps
|
||||
|
||||
Once connected to the database, your next steps are probably:
|
||||
|
||||
- Define the structure of newly created databases: see <doc:Migrations>.
|
||||
- If you intend to write SQL, see <doc:SQLSupport>. Otherwise, see <doc:QueryInterface>.
|
||||
|
||||
Even if you plan to keep your project mundane and simple, take the time to read the <doc:Concurrency> guide eventually.
|
||||
|
||||
## Topics
|
||||
|
||||
### Configuring database connections
|
||||
|
||||
@@ -140,29 +140,13 @@ try db.create(table: "membership") { t in
|
||||
}
|
||||
t.column("role", .text).notNull()
|
||||
}
|
||||
|
||||
// REQUIRES EXTRA CONFIGURATION
|
||||
try db.create(table: "player") { t in
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
|
||||
try db.create(table: "team") { t in
|
||||
t.column("id", .text).notNull().unique()
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
|
||||
try db.create(table: "membership") { t in
|
||||
t.column("playerId", .integer).notNull()
|
||||
t.column("teamId", .text).notNull()
|
||||
t.column("role", .text).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
Primary keys support record fetching methods such as ``FetchableRecord/fetchOne(_:id:)``, and persistence methods such as ``MutablePersistableRecord/update(_:onConflict:)`` or ``MutablePersistableRecord/delete(_:)``.
|
||||
|
||||
See <doc:SingleRowTables> when you need to define a table that contains a single row.
|
||||
|
||||
☝️ **If the database table does not define any explicit primary key**, the record type for this table needs explicit support for the [hidden `rowid` column](https://www.sqlite.org/rowidtable.html):
|
||||
☝️ **If the database table does not define any explicit primary key**, identifying specific rows in this table needs explicit support for the [hidden `rowid` column](https://www.sqlite.org/rowidtable.html) in the matching record types:
|
||||
|
||||
```swift
|
||||
// A table without any explicit primary key
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Sharing a Database
|
||||
|
||||
How to share an SQLite Database between several processes.
|
||||
How to share an SQLite database between multiple processes • Recommendations for App Group containers, App Extensions, App Sandbox, and file coordination.
|
||||
|
||||
## Overview
|
||||
|
||||
|
||||
@@ -92,6 +92,7 @@ do {
|
||||
- ``label``
|
||||
- ``maximumReaderCount``
|
||||
- ``observesSuspensionNotifications``
|
||||
- ``persistentReadOnlyConnections``
|
||||
- ``prepareDatabase(_:)``
|
||||
- ``publicStatementArguments``
|
||||
- ``transactionClock``
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
# ``GRDB/DatabaseRegionObservation``
|
||||
|
||||
`DatabaseRegionObservation` tracks changes in a database region, and notifies impactful transactions.
|
||||
|
||||
## Overview
|
||||
|
||||
`DatabaseRegionObservation` tracks insertions, updates, and deletions that impact the tracked region, whether performed with raw SQL, or <doc:QueryInterface>. This includes indirect changes triggered by [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
|
||||
|
||||
The only changes that are not notified are:
|
||||
|
||||
- Changes performed by external database connections.
|
||||
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
|
||||
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
|
||||
`DatabaseRegionObservation` calls your application right after changes have been committed in the database, and before any other thread had any opportunity to perform further changes. *This is a pretty strong guarantee, that most applications do not really need.* Instead, most applications prefer to be notified with fresh values: make sure you check ``ValueObservation`` before using `DatabaseRegionObservation`.
|
||||
|
||||
## DatabaseRegionObservation Usage
|
||||
|
||||
Create a `DatabaseRegionObservation` with one or several requests to track:
|
||||
|
||||
```swift
|
||||
// Tracks the full player table
|
||||
let observation = DatabaseRegionObservation(tracking: Player.all())
|
||||
```
|
||||
|
||||
Then start the observation from a ``DatabaseQueue`` or ``DatabasePool``:
|
||||
|
||||
```swift
|
||||
let cancellable = try observation.start(in: dbQueue) { error in
|
||||
// Handle error
|
||||
} onChange: { (db: Database) in
|
||||
print("Players were changed")
|
||||
}
|
||||
```
|
||||
|
||||
Enjoy the changes notifications:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
try Player(name: "Arthur").insert(db)
|
||||
}
|
||||
// Prints "Players were changed"
|
||||
```
|
||||
|
||||
You stop the observation by calling the ``DatabaseCancellable/cancel()`` method on the object returned by the `start` method. Cancellation is automatic when the cancellable is deallocated:
|
||||
|
||||
```swift
|
||||
cancellable.cancel()
|
||||
```
|
||||
|
||||
`DatabaseRegionObservation` can also be turned into a Combine publisher, or an RxSwift observable (see the companion library [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB)):
|
||||
|
||||
```swift
|
||||
let cancellable = observation.publisher(in: dbQueue).sink { completion in
|
||||
// Handle completion
|
||||
} receiveValue: { (db: Database) in
|
||||
print("Players were changed")
|
||||
}
|
||||
```
|
||||
|
||||
You can feed `DatabaseRegionObservation` with any type that conforms to the ``DatabaseRegionConvertible`` protocol: ``FetchRequest``, ``DatabaseRegion``, ``Table``, etc. For example:
|
||||
|
||||
```swift
|
||||
// Observe the score column of the 'player' table
|
||||
let observation = DatabaseRegionObservation(
|
||||
tracking: Player.select(Column("score")))
|
||||
|
||||
// Observe the 'score' column of the 'player' table
|
||||
let observation = DatabaseRegionObservation(
|
||||
tracking: SQLRequest("SELECT score FROM player"))
|
||||
|
||||
// Observe both the 'player' and 'team' tables
|
||||
let observation = DatabaseRegionObservation(
|
||||
tracking: Table("player"), Table("team"))
|
||||
|
||||
// Observe the full database
|
||||
let observation = DatabaseRegionObservation(
|
||||
tracking: .fullDatabase)
|
||||
```
|
||||
|
||||
## Topics
|
||||
|
||||
### Creating DatabaseRegionObservation
|
||||
|
||||
- ``init(tracking:)-5ldbe``
|
||||
- ``init(tracking:)-2nqjd``
|
||||
|
||||
### Observing Database Transactions
|
||||
|
||||
- ``publisher(in:)``
|
||||
- ``start(in:onError:onChange:)``
|
||||
@@ -0,0 +1,171 @@
|
||||
# ``GRDB/DatabaseValueConvertible``
|
||||
|
||||
A type that can convert itself into and out of a database value.
|
||||
|
||||
## Overview
|
||||
|
||||
A `DatabaseValueConvertible` type supports conversion to and from database values (null, integers, doubles, strings, and blobs). `DatabaseValueConvertible` is adopted by `Bool`, `Int`, `String`, `Date`, etc.
|
||||
|
||||
> Note: Types that converts to and from multiple columns in a database row must not conform to the `DatabaseValueConvertible` protocol. Those types are called **record types**, and should conform to record protocols instead. See <doc:QueryInterface>.
|
||||
|
||||
> Note: Standard collections `Array`, `Set`, and `Dictionary` do not conform to `DatabaseValueConvertible`. To store arrays, sets, or dictionaries in individual database values, wrap them as properties of `Codable` record types. They will automatically be stored as JSON objects and arrays. See <doc:QueryInterface>.
|
||||
|
||||
## Conforming to the DatabaseValueConvertible Protocol
|
||||
|
||||
To conform to `DatabaseValueConvertible`, implement the two requirements ``fromDatabaseValue(_:)-21zzv`` and ``databaseValue-1ob9k``. Do not customize the ``fromMissingColumn()-7iamp`` requirement. If your type `MyValue` conforms, then the conformance of the optional type `MyValue?` is automatic.
|
||||
|
||||
The implementation of `fromDatabaseValue` must return nil if the type can not be decoded from the raw database value. This nil value will have GRDB throw a decoding error accordingly.
|
||||
|
||||
For example:
|
||||
|
||||
```swift
|
||||
struct EvenInteger {
|
||||
let value: Int // Guaranteed even
|
||||
|
||||
init?(_ value: Int) {
|
||||
guard value.isMultiple(of: 2) else {
|
||||
return nil // Not an even number
|
||||
}
|
||||
self.value = value
|
||||
}
|
||||
}
|
||||
|
||||
extension EvenInteger: DatabaseValueConvertible {
|
||||
var databaseValue: DatabaseValue {
|
||||
value.databaseValue
|
||||
}
|
||||
|
||||
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
guard let value = Int.fromDatabaseValue(dbValue) else {
|
||||
return nil // Not an integer
|
||||
}
|
||||
return EvenInteger(value) // Nil if not even
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Built-in RawRepresentable support
|
||||
|
||||
`DatabaseValueConvertible` implementation is ready-made for `RawRepresentable` types whose raw value is itself `DatabaseValueConvertible`, such as enums:
|
||||
|
||||
```swift
|
||||
enum Grape: String {
|
||||
case chardonnay, merlot, riesling
|
||||
}
|
||||
|
||||
// Encodes and decodes `Grape` as a string in the database:
|
||||
extension Grape: DatabaseValueConvertible { }
|
||||
```
|
||||
|
||||
### Built-in Codable support
|
||||
|
||||
`DatabaseValueConvertible` is also ready-made for `Codable` types, which are automatically coded and decoded from JSON arrays and objects:
|
||||
|
||||
```swift
|
||||
struct Color: Codable {
|
||||
var red: Double
|
||||
var green: Double
|
||||
var blue: Double
|
||||
}
|
||||
|
||||
// Encodes and decodes `Color` as a JSON object in the database:
|
||||
extension Color: DatabaseValueConvertible { }
|
||||
```
|
||||
|
||||
By default, such codable value types are encoded and decoded with the standard [JSONEncoder](https://developer.apple.com/documentation/foundation/jsonencoder) and [JSONDecoder](https://developer.apple.com/documentation/foundation/jsondecoder). `Data` values are handled with the `.base64` strategy, `Date` with the `.millisecondsSince1970` strategy, and non conforming floats with the `.throw` strategy.
|
||||
|
||||
To customize the JSON format, provide an explicit implementation for the `DatabaseValueConvertible` requirements.
|
||||
|
||||
### Adding support for the Tagged library
|
||||
|
||||
[Tagged](https://github.com/pointfreeco/swift-tagged) is a popular library that makes it possible to enhance the type-safety of our programs with dedicated wrappers around basic types. For example:
|
||||
|
||||
```swift
|
||||
import Tagged
|
||||
|
||||
struct Player: Identifiable {
|
||||
// Thanks to Tagged, Player.ID can not be mismatched with Team.ID or
|
||||
// Award.ID, even though they all wrap strings.
|
||||
typealias ID = Tagged<Player, String>
|
||||
var id: ID
|
||||
var name: String
|
||||
var score: Int
|
||||
}
|
||||
```
|
||||
|
||||
Applications that use both Tagged and GRDB will want to add those lines somewhere:
|
||||
|
||||
```swift
|
||||
import GRDB
|
||||
import Tagged
|
||||
|
||||
// Add database support to Tagged values
|
||||
extension Tagged: SQLExpressible where RawValue: SQLExpressible { }
|
||||
extension Tagged: StatementBinding where RawValue: StatementBinding { }
|
||||
extension Tagged: StatementColumnConvertible where RawValue: StatementColumnConvertible { }
|
||||
extension Tagged: DatabaseValueConvertible where RawValue: DatabaseValueConvertible { }
|
||||
```
|
||||
|
||||
This makes it possible to use `Tagged` values in all the expected places:
|
||||
|
||||
```swift
|
||||
let id: Player.ID = ...
|
||||
let player = try Player.find(db, id: id)
|
||||
```
|
||||
|
||||
## Optimized Values
|
||||
|
||||
For extra performance, custom value types can conform to both `DatabaseValueConvertible` and ``StatementColumnConvertible``. This extra protocol grants raw access to the [low-level C SQLite interface](https://www.sqlite.org/c3ref/column_blob.html) when decoding values.
|
||||
|
||||
For example:
|
||||
|
||||
```swift
|
||||
extension EvenInteger: StatementColumnConvertible {
|
||||
init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
guard let value = Int(exactly: int64) else {
|
||||
return nil // Does not fit Int (probably a 32-bit architecture)
|
||||
}
|
||||
self.init(value) // Nil if not even
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This extra conformance is not required: only aim at the low-level C interface if you have identified a performance issue after profiling your application!
|
||||
|
||||
## Topics
|
||||
|
||||
### Creating a Value
|
||||
|
||||
- ``fromDatabaseValue(_:)-21zzv``
|
||||
- ``fromMissingColumn()-7iamp``
|
||||
|
||||
### Accessing the DatabaseValue
|
||||
|
||||
- ``databaseValue-1ob9k``
|
||||
|
||||
### Fetching Values from Raw SQL
|
||||
|
||||
- ``fetchCursor(_:sql:arguments:adapter:)-6elcz``
|
||||
- ``fetchAll(_:sql:arguments:adapter:)-1cqyb``
|
||||
- ``fetchSet(_:sql:arguments:adapter:)-5jene``
|
||||
- ``fetchOne(_:sql:arguments:adapter:)-qvqp``
|
||||
|
||||
### Fetching Values from a Prepared Statement
|
||||
|
||||
- ``fetchCursor(_:arguments:adapter:)-4l6af``
|
||||
- ``fetchAll(_:arguments:adapter:)-3abuc``
|
||||
- ``fetchSet(_:arguments:adapter:)-6y54n``
|
||||
- ``fetchOne(_:arguments:adapter:)-3d7ax``
|
||||
|
||||
### Fetching Values from a Request
|
||||
|
||||
- ``fetchCursor(_:_:)-8q4r6``
|
||||
- ``fetchAll(_:_:)-9hkqs``
|
||||
- ``fetchSet(_:_:)-1foke``
|
||||
- ``fetchOne(_:_:)-o6yj``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``DatabaseValueCursor``
|
||||
- ``StatementBinding``
|
||||
@@ -0,0 +1,205 @@
|
||||
# ``GRDB/Statement``
|
||||
|
||||
A prepared statement.
|
||||
|
||||
## Overview
|
||||
|
||||
Prepared statements let you execute an SQL query several times, with different arguments if needed.
|
||||
|
||||
Reusing prepared statements is a performance optimization technique because SQLite parses and analyses the SQL query only once, when the prepared statement is created.
|
||||
|
||||
## Building Prepared Statements
|
||||
|
||||
Build a prepared statement with the ``Database/makeStatement(sql:)`` method:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
let insertStatement = try db.makeStatement(sql: """
|
||||
INSERT INTO player (name, score) VALUES (:name, :score)
|
||||
""")
|
||||
|
||||
let selectStatement = try db.makeStatement(sql: """
|
||||
SELECT * FROM player WHERE name = ?
|
||||
""")
|
||||
}
|
||||
```
|
||||
|
||||
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. Set the values for those arguments with arrays or dictionaries of database values, or ``StatementArguments`` instances:
|
||||
|
||||
```swift
|
||||
insertStatement.arguments = ["name": "Arthur", "score": 1000]
|
||||
selectStatement.arguments = ["Arthur"]
|
||||
```
|
||||
|
||||
Alternatively, the ``Database/makeStatement(literal:)`` method creates prepared statements with support for [SQL Interpolation]:
|
||||
|
||||
```swift
|
||||
let insertStatement = try db.makeStatement(literal: "INSERT ...")
|
||||
let selectStatement = try db.makeStatement(literal: "SELECT ...")
|
||||
// ~~~~~~~
|
||||
```
|
||||
|
||||
The `makeStatement` methods throw an error of code `SQLITE_MISUSE` (21) if the SQL query contains multiple statements joined with a semicolon. See <doc:GRDB/Statement#Parsing-Multiple-Prepared-Statements-from-a-Single-SQL-String> below.
|
||||
|
||||
## Executing Prepared Statements and Fetching Values
|
||||
|
||||
Prepared statements can be executed:
|
||||
|
||||
```swift
|
||||
try insertStatement.execute()
|
||||
```
|
||||
|
||||
To fetch rows and values from a prepared statement, use a fetching method of ``Row``, ``DatabaseValueConvertible``, or ``FetchableRecord``:
|
||||
|
||||
```swift
|
||||
let players = try Player.fetchCursor(selectStatement) // A Cursor of Player
|
||||
let players = try Player.fetchAll(selectStatement) // [Player]
|
||||
let players = try Player.fetchSet(selectStatement) // Set<Player>
|
||||
let player = try Player.fetchOne(selectStatement) // Player?
|
||||
// ~~~~~~ or Row, Int, String, Date, etc.
|
||||
```
|
||||
|
||||
Arguments can be set at the moment of the statement execution:
|
||||
|
||||
```swift
|
||||
try insertStatement.execute(arguments: ["name": "Arthur", "score": 1000])
|
||||
let player = try Player.fetchOne(selectStatement, arguments: ["Arthur"])
|
||||
```
|
||||
|
||||
> Note: A prepared statement that has failed with an error can not be recovered. Create a new instance, or use a cached statement as described below.
|
||||
|
||||
> Tip: When you look after the best performance, take care about a difference between setting the arguments before execution, and setting the arguments at the moment of execution:
|
||||
>
|
||||
> ```swift
|
||||
> // First option
|
||||
> try statement.setArguments(...)
|
||||
> try statement.execute()
|
||||
>
|
||||
> // Second option
|
||||
> try statement.execute(arguments: ...)
|
||||
> ```
|
||||
>
|
||||
> Both perform exactly the same action, and most applications should not care about the difference. Yet:
|
||||
>
|
||||
> - ``setArguments(_:)`` performs a copy of string and blob arguments. It uses the low-level [`SQLITE_TRANSIENT`](https://www.sqlite.org/c3ref/c_static.html) option, and fits well the reuse of a given statement with the same arguments.
|
||||
> - ``execute(arguments:)`` avoids a temporary allocation for string and blob arguments if the number of arguments is small. Instead of `SQLITE_TRANSIENT`, it uses the low-level [`SQLITE_STATIC`](https://www.sqlite.org/c3ref/c_static.html) option. This fits well the reuse of a given statement with various arguments.
|
||||
>
|
||||
> Don't make a blind choice, and monitor your app performance if it really matters!
|
||||
|
||||
## Caching Prepared Statements
|
||||
|
||||
When the same query will be used several times in the lifetime of an application, one may feel a natural desire to cache prepared statements.
|
||||
|
||||
Don't cache statements yourself.
|
||||
|
||||
> Note: This is because an application lacks the necessary tools. Statements are tied to specific SQLite connections and dispatch queues which are not managed by the application, especially with a ``DatabasePool`` connection. A change in the database schema [may, or may not](https://www.sqlite.org/compile.html#max_schema_retry) invalidate a statement.
|
||||
|
||||
Instead, use the ``Database/cachedStatement(sql:)`` method. GRDB does all the hard caching and memory management:
|
||||
|
||||
```swift
|
||||
let statement = try db.cachedStatement(sql: "INSERT ...")
|
||||
```
|
||||
|
||||
The variant ``Database/cachedStatement(literal:)`` supports [SQL Interpolation]:
|
||||
|
||||
```swift
|
||||
let statement = try db.cachedStatement(literal: "INSERT ...")
|
||||
```
|
||||
|
||||
Should a cached prepared statement throw an error, don't reuse it. Instead, reload one from the cache.
|
||||
|
||||
## Parsing Multiple Prepared Statements from a Single SQL String
|
||||
|
||||
To build multiple statements joined with a semicolon, use ``Database/allStatements(sql:arguments:)``:
|
||||
|
||||
```swift
|
||||
let statements = try db.allStatements(sql: """
|
||||
INSERT INTO player (name, score) VALUES (?, ?);
|
||||
INSERT INTO player (name, score) VALUES (?, ?);
|
||||
""", arguments: ["Arthur", 100, "O'Brien", 1000])
|
||||
while let statement = try statements.next() {
|
||||
try statement.execute()
|
||||
}
|
||||
```
|
||||
|
||||
The variant ``Database/allStatements(literal:)`` supports [SQL Interpolation]:
|
||||
|
||||
```swift
|
||||
let statements = try db.allStatements(literal: """
|
||||
INSERT INTO player (name, score) VALUES (\("Arthur"), \(100));
|
||||
INSERT INTO player (name, score) VALUES (\("O'Brien"), \(1000));
|
||||
""")
|
||||
// An alternative way to iterate all statements
|
||||
try statements.forEach { statement in
|
||||
try statement.execute()
|
||||
}
|
||||
```
|
||||
|
||||
> Tip: When you intend to run all statements in an SQL string but don't care about individual ones, don't bother iterating individual statement instances! Skip this documentation section and just use ``Database/execute(sql:arguments:)``:
|
||||
>
|
||||
> ```swift
|
||||
> try db.execute(sql: """
|
||||
> CREATE TABLE player ...;
|
||||
> INSERT INTO player ...;
|
||||
> """)
|
||||
> ```
|
||||
|
||||
The results of multiple `SELECT` statements can be joined into a single ``Cursor``. This is the GRDB version of the [`sqlite3_exec()`](https://www.sqlite.org/c3ref/exec.html) function:
|
||||
|
||||
```swift
|
||||
let statements = try db.allStatements(sql: """
|
||||
SELECT ...;
|
||||
SELECT ...;
|
||||
""")
|
||||
let players = try statements.flatMap { statement in
|
||||
try Player.fetchCursor(statement)
|
||||
}
|
||||
for let player = try players.next() {
|
||||
print(player.name)
|
||||
}
|
||||
```
|
||||
|
||||
The ``SQLStatementCursor`` returned from `allStatements` can be turned into a regular Swift array, but in this case make sure all individual statements can compile even if the previous ones were not executed:
|
||||
|
||||
```swift
|
||||
// OK: Array of statements
|
||||
let statements = try Array(db.allStatements(sql: """
|
||||
INSERT ...;
|
||||
UPDATE ...;
|
||||
"""))
|
||||
|
||||
// FAILURE: Can't build an array of statements since the INSERT won't
|
||||
// compile until CREATE TABLE is executed.
|
||||
let statements = try Array(db.allStatements(sql: """
|
||||
CREATE TABLE player ...;
|
||||
INSERT INTO player ...;
|
||||
"""))
|
||||
```
|
||||
|
||||
## Topics
|
||||
|
||||
### Executing a Prepared Statement
|
||||
|
||||
- ``execute(arguments:)``
|
||||
|
||||
### Arguments
|
||||
|
||||
- ``arguments``
|
||||
- ``setArguments(_:)``
|
||||
- ``setUncheckedArguments(_:)``
|
||||
- ``validateArguments(_:)``
|
||||
- ``StatementArguments``
|
||||
|
||||
### Statement Informations
|
||||
|
||||
- ``columnCount``
|
||||
- ``columnNames``
|
||||
- ``databaseRegion``
|
||||
- ``index(ofColumn:)``
|
||||
- ``isReadonly``
|
||||
- ``sql``
|
||||
- ``sqliteStatement``
|
||||
- ``SQLiteStatement``
|
||||
|
||||
|
||||
[SQL Interpolation]: https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md
|
||||
@@ -0,0 +1,255 @@
|
||||
# ``GRDB/TransactionObserver``
|
||||
|
||||
A type that tracks database changes and transactions performed in a database.
|
||||
|
||||
## Overview
|
||||
|
||||
`TransactionObserver` is the low-level protocol that supports all <doc:DatabaseObservation> features.
|
||||
|
||||
A transaction observer is notified of individual changes (inserts, updates and deletes), before they are committed to disk, as well as transaction commits and rollbacks.
|
||||
|
||||
## Activate a Transaction Observer
|
||||
|
||||
An observer starts receiving change notifications after it has been added to a database connection with the ``DatabaseWriter/add(transactionObserver:extent:)`` `DatabaseWriter` method, or the ``Database/add(transactionObserver:extent:)`` `Database` method:
|
||||
|
||||
```swift
|
||||
let observer = MyObserver()
|
||||
dbQueue.add(transactionObserver: observer)
|
||||
```
|
||||
|
||||
By default, database holds weak references to its transaction observers: they are not retained, and stop getting notifications after they are deallocated. See <doc:TransactionObserver#Observation-Extent> for more options.
|
||||
|
||||
## Database Changes And Transactions
|
||||
|
||||
Database changes are notified to the ``databaseDidChange(with:)`` callback. This includes indirect changes triggered by `ON DELETE` and `ON UPDATE` actions associated to [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions), and [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
|
||||
|
||||
Transaction completions are notified to the ``databaseWillCommit()-7mksu``, ``databaseDidCommit(_:)`` and ``databaseDidRollback(_:)`` callbacks.
|
||||
|
||||
The only changes and transactions that are not notified are:
|
||||
|
||||
- Read-only transactions.
|
||||
- Changes and transactions performed by external database connections.
|
||||
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
|
||||
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
- The deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite).
|
||||
|
||||
Notified changes are not actually written to disk until the transaction commits, and the `databaseDidCommit` callback is called. On the other side, `databaseDidRollback` confirms their invalidation:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
try db.execute(sql: "INSERT ...") // 1. didChange
|
||||
try db.execute(sql: "UPDATE ...") // 2. didChange
|
||||
} // 3. willCommit, 4. didCommit
|
||||
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute(sql: "INSERT ...") // 1. didChange
|
||||
try db.execute(sql: "UPDATE ...") // 2. didChange
|
||||
return .rollback // 3. didRollback
|
||||
}
|
||||
|
||||
try dbQueue.write { db in
|
||||
try db.execute(sql: "INSERT ...") // 1. didChange
|
||||
throw SomeError()
|
||||
} // 2. didRollback
|
||||
```
|
||||
|
||||
Database statements that are executed outside of any explicit transaction do not drop off the radar:
|
||||
|
||||
```swift
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
try db.execute(sql: "INSERT ...") // 1. didChange, 2. willCommit, 3. didCommit
|
||||
try db.execute(sql: "UPDATE ...") // 4. didChange, 5. willCommit, 6. didCommit
|
||||
}
|
||||
```
|
||||
|
||||
Changes that are on hold because of a [savepoint](https://www.sqlite.org/lang_savepoint.html) are only notified after the savepoint has been released. This makes sure that notified events are only those that have an opportunity to be committed:
|
||||
|
||||
```swift
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute(sql: "INSERT ...") // 1. didChange
|
||||
|
||||
try db.execute(sql: "SAVEPOINT foo")
|
||||
try db.execute(sql: "UPDATE ...") // delayed
|
||||
try db.execute(sql: "UPDATE ...") // delayed
|
||||
try db.execute(sql: "RELEASE SAVEPOINT foo") // 2. didChange, 3. didChange
|
||||
|
||||
try db.execute(sql: "SAVEPOINT bar")
|
||||
try db.execute(sql: "UPDATE ...") // not notified
|
||||
try db.execute(sql: "ROLLBACK TO SAVEPOINT bar")
|
||||
try db.execute(sql: "RELEASE SAVEPOINT bar")
|
||||
|
||||
return .commit // 4. willCommit, 5. didCommit
|
||||
}
|
||||
```
|
||||
|
||||
Eventual errors thrown from `databaseWillCommit` are exposed to the application code:
|
||||
|
||||
```swift
|
||||
do {
|
||||
try dbQueue.inTransaction { db in
|
||||
...
|
||||
return .commit // 1. willCommit (throws), 2. didRollback
|
||||
}
|
||||
} catch {
|
||||
// 3. The error thrown by the transaction observer.
|
||||
}
|
||||
```
|
||||
|
||||
- Note: All callbacks are called in the writer dispatch queue, and serialized with all database updates.
|
||||
|
||||
- Note: The `databaseDidChange` and `databaseWillCommit` callbacks must not touch the SQLite database. This limitation does not apply to `databaseDidCommit` and `databaseDidRollback` which can use their database argument.
|
||||
|
||||
## Filtering Database Events
|
||||
|
||||
**Transaction observers can choose the database changes they are interested in.**
|
||||
|
||||
The ``observes(eventsOfKind:)`` method filters events that are notified to ``databaseDidChange(with:)``. It is the most efficient and recommended change filtering technique, because it is only called once before a database query is executed, and can completely disable change tracking:
|
||||
|
||||
```swift
|
||||
// Calls `observes(eventsOfKind:)` once.
|
||||
// Calls `databaseDidChange(with:)` for every updated row, or not at all.
|
||||
try db.execute(sql: "UPDATE player SET score = score + 1")
|
||||
```
|
||||
|
||||
The ``DatabaseEventKind`` argument of `observes(eventsOfKind:)` can distinguish insertions from deletions and updates, and is also able to tell the columns that are about to be changed.
|
||||
|
||||
For example, an observer can focus on the changes that happen on the "player" database table only:
|
||||
|
||||
```swift
|
||||
class PlayerObserver: TransactionObserver {
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
// Only observe changes to the "player" table.
|
||||
eventKind.tableName == "player"
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
// This method is only called for changes that happen to
|
||||
// the "player" table.
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
When the `observes(eventsOfKind:)` method returns false for all event kinds, the observer is still notified of transactions.
|
||||
|
||||
## Observation Extent
|
||||
|
||||
**You can specify how long an observer is notified of database changes and transactions.**
|
||||
|
||||
The `remove(transactionObserver:)` method explicitly stops notifications, at any time:
|
||||
|
||||
```swift
|
||||
// From a database queue or pool:
|
||||
dbQueue.remove(transactionObserver: observer)
|
||||
|
||||
// From a database connection:
|
||||
dbQueue.inDatabase { db in
|
||||
db.remove(transactionObserver: observer)
|
||||
}
|
||||
```
|
||||
|
||||
Alternatively, use the `extent` parameter of the `add(transactionObserver:extent:)` method:
|
||||
|
||||
```swift
|
||||
let observer = MyObserver()
|
||||
|
||||
// On a database queue or pool:
|
||||
dbQueue.add(transactionObserver: observer) // default extent
|
||||
dbQueue.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
dbQueue.add(transactionObserver: observer, extent: .nextTransaction)
|
||||
dbQueue.add(transactionObserver: observer, extent: .databaseLifetime)
|
||||
|
||||
// On a database connection:
|
||||
dbQueue.inDatabase { db in
|
||||
db.add(transactionObserver: ...)
|
||||
}
|
||||
```
|
||||
|
||||
- The default extent is `.observerLifetime`: the database holds a weak reference to the observer, and the observation automatically ends when the observer is deallocated. Meanwhile, the observer is notified of all changes and transactions.
|
||||
|
||||
- `.nextTransaction` activates the observer until the current or next transaction completes. The database keeps a strong reference to the observer until its `databaseDidCommit` or `databaseDidRollback` callback is called. Hereafter the observer won't get any further notification.
|
||||
|
||||
- `.databaseLifetime` has the database retain and notify the observer until the database connection is closed.
|
||||
|
||||
Finally, an observer can avoid processing database changes until the end of the current transaction. After ``stopObservingDatabaseChangesUntilNextTransaction()``, the `databaseDidChange` callback will not be called until the current transaction completes:
|
||||
|
||||
```swift
|
||||
class PlayerObserver: TransactionObserver {
|
||||
var playerTableWasModified = false
|
||||
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
eventKind.tableName == "player"
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
playerTableWasModified = true
|
||||
|
||||
// It is pointless to keep on tracking further changes:
|
||||
stopObservingDatabaseChangesUntilNextTransaction()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Support for SQLite Pre-Update Hooks
|
||||
|
||||
When SQLite is built with the `SQLITE_ENABLE_PREUPDATE_HOOK` option, `TransactionObserver` gets an extra callback which lets you observe individual column values in the rows modified by a transaction:
|
||||
|
||||
```swift
|
||||
protocol TransactionObserver: AnyObject {
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
/// Notifies before a database change (insert, update, or delete)
|
||||
/// with change information (initial / final values for the row's
|
||||
/// columns).
|
||||
///
|
||||
/// The event is only valid for the duration of this method call. If you
|
||||
/// need to keep it longer, store a copy: event.copy().
|
||||
func databaseWillChange(with event: DatabasePreUpdateEvent)
|
||||
#endif
|
||||
}
|
||||
```
|
||||
|
||||
This extra API can be activated in two ways:
|
||||
|
||||
1. Use the GRDB.swift CocoaPod with a custom compilation option, as below.
|
||||
|
||||
It uses the system SQLite, which is compiled with `SQLITE_ENABLE_PREUPDATE_HOOK` support, but only on iOS 11.0+ (we don't know the minimum version of macOS, tvOS, watchOS):
|
||||
|
||||
```ruby
|
||||
pod 'GRDB.swift'
|
||||
platform :ios, '11.0' # or above
|
||||
|
||||
post_install do |installer|
|
||||
installer.pods_project.targets.select { |target| target.name == "GRDB.swift" }.each do |target|
|
||||
target.build_configurations.each do |config|
|
||||
# Enable extra GRDB APIs
|
||||
config.build_settings['OTHER_SWIFT_FLAGS'] = "$(inherited) -D SQLITE_ENABLE_PREUPDATE_HOOK"
|
||||
# Enable extra SQLite APIs
|
||||
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = "$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1"
|
||||
end
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
**Warning**: make sure you use the right platform version! You will get runtime errors on devices with a lower version.
|
||||
|
||||
**Note**: the `GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1` option in `GCC_PREPROCESSOR_DEFINITIONS` defines some C function prototypes that are lacking from the system `<sqlite3.h>` header. When Xcode eventually ships with an SDK that includes a complete header, you may get a compiler error about duplicate function definitions. When this happens, just remove this `GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1` option.
|
||||
|
||||
2. Use a [custom SQLite build](http://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md) and activate the `SQLITE_ENABLE_PREUPDATE_HOOK` compilation option.
|
||||
|
||||
## Topics
|
||||
|
||||
### Filtering Database Changes
|
||||
|
||||
- ``observes(eventsOfKind:)``
|
||||
- ``DatabaseEventKind``
|
||||
|
||||
### Handling Database Changes
|
||||
|
||||
- ``databaseDidChange(with:)``
|
||||
- ``stopObservingDatabaseChangesUntilNextTransaction()``
|
||||
- ``DatabaseEvent``
|
||||
|
||||
### Handling Transactions
|
||||
|
||||
- ``databaseWillCommit()-7mksu``
|
||||
- ``databaseDidCommit(_:)``
|
||||
- ``databaseDidRollback(_:)``
|
||||
@@ -0,0 +1,264 @@
|
||||
# ``GRDB/ValueObservation``
|
||||
|
||||
`ValueObservation` tracks changes in the results of database requests, and notifies fresh values whenever the database changes.
|
||||
|
||||
## Overview
|
||||
|
||||
`ValueObservation` tracks insertions, updates, and deletions that impact the tracked value, whether performed with raw SQL, or <doc:QueryInterface>. This includes indirect changes triggered by [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
|
||||
|
||||
The only changes that are not notified are:
|
||||
|
||||
- Changes performed by external database connections. See <doc:DatabaseSharing#How-to-perform-cross-process-database-observation> for more information.
|
||||
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
|
||||
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
|
||||
## ValueObservation Usage
|
||||
|
||||
1. Make sure that a unique database connection, ``DatabaseQueue`` or ``DatabasePool``, is kept open during the whole duration of the observation.
|
||||
|
||||
2. Create a `ValueObservation` with a closure that fetches the observed value:
|
||||
|
||||
```swift
|
||||
let observation = ValueObservation.tracking { db in
|
||||
// Fetch and return the observed value
|
||||
}
|
||||
|
||||
// For example, an observation of [Player], which tracks all players:
|
||||
let observation = ValueObservation.tracking { db in
|
||||
try Player.fetchAll(db)
|
||||
}
|
||||
|
||||
// The same observation, using shorthand notation:
|
||||
let observation = ValueObservation.tracking(Player.fetchAll)
|
||||
```
|
||||
|
||||
There is no limit on the values that can be observed. An observation can perform multiple requests, from multiple database tables, and use raw SQL. See ``tracking(_:)`` for some examples.
|
||||
|
||||
3. Start the observation in order to be notified of changes:
|
||||
|
||||
```swift
|
||||
let cancellable = observation.start(in: dbQueue) { error in
|
||||
// Handle error
|
||||
} onChange: { (players: [Player]) in
|
||||
print("Fresh players", players)
|
||||
}
|
||||
```
|
||||
|
||||
4. Stop the observation by calling the ``DatabaseCancellable/cancel()`` method on the object returned by the `start` method. Cancellation is automatic when the cancellable is deallocated:
|
||||
|
||||
```swift
|
||||
cancellable.cancel()
|
||||
```
|
||||
|
||||
`ValueObservation` can also be turned into an async sequence, a Combine publisher, or an RxSwift observable (see the companion library [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB)):
|
||||
|
||||
- Async sequence:
|
||||
|
||||
```swift
|
||||
do {
|
||||
for try await players in observation.values(in: dbQueue) {
|
||||
print("Fresh players", players)
|
||||
}
|
||||
} catch {
|
||||
// Handle error
|
||||
}
|
||||
```
|
||||
|
||||
- Combine Publisher:
|
||||
|
||||
```swift
|
||||
let cancellable = observation.publisher(in: dbQueue).sink { completion in
|
||||
// Handle completion
|
||||
} receiveValue: { (players: [Player]) in
|
||||
print("Fresh players", players)
|
||||
}
|
||||
```
|
||||
|
||||
## ValueObservation Behavior
|
||||
|
||||
`ValueObservation` notifies an initial value before the eventual changes.
|
||||
|
||||
`ValueObservation` only notifies changes committed to disk.
|
||||
|
||||
By default, `ValueObservation` notifies a fresh value whenever any component of its fetched value is modified (any fetched column, row, etc.). This can be configured: see <doc:ValueObservation#Specifying-the-Tracked-Region>.
|
||||
|
||||
By default, `ValueObservation` notifies the initial value, as well as eventual changes and errors, on the main dispatch queue, asynchronously. This can be configured: see <doc:ValueObservation#ValueObservation-Scheduling>.
|
||||
|
||||
`ValueObservation` may coalesce subsequent changes into a single notification.
|
||||
|
||||
`ValueObservation` may notify consecutive identical values. You can filter out the undesired duplicates with the ``removeDuplicates()`` method.
|
||||
|
||||
Starting an observation retains the database connection, until it is stopped. As long as the observation is active, the database connection won't be deallocated.
|
||||
|
||||
The database observation stops when the cancellable returned by the `start` method is cancelled or deallocated, or if an error occurs.
|
||||
|
||||
> Important: Take care that there are use cases that `ValueObservation` is unfit for.
|
||||
>
|
||||
> For example, an application may need to process absolutely all changes, and avoid any coalescing. An application may also need to process changes before any further modifications could be performed in the database file. In those cases, the application needs to track *individual transactions*, not values: use ``DatabaseRegionObservation``.
|
||||
>
|
||||
> If you need to process changes before they are committed to disk, use ``TransactionObserver``.
|
||||
|
||||
## ValueObservation Scheduling
|
||||
|
||||
By default, `ValueObservation` notifies the initial value, as well as eventual changes and errors, on the main dispatch queue, asynchronously:
|
||||
|
||||
```swift
|
||||
// The default scheduling
|
||||
let cancellable = observation.start(in: dbQueue) { error in
|
||||
// Called asynchronously on the main dispatch queue
|
||||
} onChange: { value in
|
||||
// Called asynchronously on the main dispatch queue
|
||||
print("Fresh value", value)
|
||||
}
|
||||
```
|
||||
|
||||
You can change this behavior by adding a `scheduling` argument to the `start()` method.
|
||||
|
||||
For example, the ``ValueObservationScheduler/immediate`` scheduler notifies all values on the main dispatch queue, and notifies the first one immediately when the observation starts.
|
||||
|
||||
It is very useful in graphic applications, because you can configure views right away, without waiting for the initial value to be fetched eventually. You don't have to implement any empty or loading screen, or to prevent some undesired initial animation. Take care that the user interface is not responsive during the fetch of the first value, so only use the `immediate` scheduling for very fast database requests!
|
||||
|
||||
The `immediate` scheduling requires that the observation starts from the main dispatch queue (a fatal error is raised otherwise):
|
||||
|
||||
```swift
|
||||
let cancellable = observation.start(in: dbQueue, scheduling: .immediate) { error in
|
||||
// Called on the main dispatch queue
|
||||
} onChange: { value in
|
||||
// Called on the main dispatch queue
|
||||
print("Fresh value", value)
|
||||
}
|
||||
// <- Here "Fresh value" has already been printed.
|
||||
```
|
||||
|
||||
The other built-in scheduler ``ValueObservationScheduler/async(onQueue:)`` asynchronously schedules values and errors on the dispatch queue of your choice.
|
||||
|
||||
## ValueObservation Sharing
|
||||
|
||||
Sharing a `ValueObservation` spares database resources. When a database change happens, a fresh value is fetched only once, and then notified to all clients of the shared observation.
|
||||
|
||||
You build a shared observation with ``shared(in:scheduling:extent:)``:
|
||||
|
||||
```swift
|
||||
// SharedValueObservation<[Player]>
|
||||
let sharedObservation = ValueObservation
|
||||
.tracking { db in try Player.fetchAll(db) }
|
||||
.shared(in: dbQueue)
|
||||
```
|
||||
|
||||
`ValueObservation` and `SharedValueObservation` are nearly identical, but the latter has no operator such as `map`. As a replacement, you may for example use Combine apis:
|
||||
|
||||
```swift
|
||||
let cancellable = try sharedObservation
|
||||
.publisher() // Turn shared observation into a Combine Publisher
|
||||
.map { ... } // The map operator from Combine
|
||||
.sink(...)
|
||||
```
|
||||
|
||||
|
||||
## Specifying the Tracked Region
|
||||
|
||||
While the standard ``tracking(_:)`` method lets you track changes to a fetched value and receive any changes to it, sometimes your use case might require more granular control.
|
||||
|
||||
Consider a scenario where you'd like to get a specific Player's row, but only when their `score` column changes. You can use ``tracking(region:fetch:)`` to do just that:
|
||||
|
||||
```swift
|
||||
let observation = ValueObservation.tracking(
|
||||
// Define the tracked database region
|
||||
// (the score column of the player with id 1)
|
||||
region: Player.select(Column("score")).filter(id: 1),
|
||||
// Define what to fetch upon such change to the tracked region
|
||||
// (the player with id 1)
|
||||
fetch: { db in try Player.fetchOne(db, id: 1) }
|
||||
)
|
||||
```
|
||||
|
||||
This ``tracking(region:fetch:)`` method lets you entirely separate the **observed region** from the **fetched value** itself, for maximum flexibility. See ``DatabaseRegionConvertible`` for more information about the regions that can be tracked.
|
||||
|
||||
## ValueObservation Performance
|
||||
|
||||
This section further describes runtime aspects of `ValueObservation`, and provides some optimization tips for demanding applications.
|
||||
|
||||
**`ValueObservation` is triggered by database transactions that may modify the tracked value.**
|
||||
|
||||
Precisely speaking, `ValueObservation` tracks changes in a ``DatabaseRegion``, not changes in values.
|
||||
|
||||
For example, if you track the maximum score of players, all transactions that impact the `score` column of the `player` database table (any update, insertion, or deletion) trigger the observation, even if the maximum score itself is not changed.
|
||||
|
||||
You can filter out undesired duplicate notifications with the ``removeDuplicates()`` method.
|
||||
|
||||
**ValueObservation can create database contention.** In other words, active observations take a toll on the constrained database resources. When triggered by impactful transactions, observations fetch fresh values, and can delay read and write database accesses of other application components.
|
||||
|
||||
When needed, you can help GRDB optimize observations and reduce database contention:
|
||||
|
||||
> Tip: Stop observations when possible.
|
||||
>
|
||||
> For example, if a `UIViewController` needs to display database values, it can start the observation in `viewWillAppear`, and stop it in `viewWillDisappear`.
|
||||
>
|
||||
> In a SwiftUI application, you can profit from the [GRDBQuery](https://github.com/groue/GRDBQuery) companion library, and its [`View.queryObservation(_:)`](https://swiftpackageindex.com/groue/grdbquery/documentation/grdbquery/queryobservation) method.
|
||||
|
||||
> Tip: Share observations when possible.
|
||||
>
|
||||
> Each call to `ValueObservation.start` method triggers independent values refreshes. When several components of your app are interested in the same value, consider sharing the observation with ``shared(in:scheduling:extent:)``.
|
||||
|
||||
> Tip: When the observation processes some raw fetched values, use the ``map(_:)`` operator:
|
||||
>
|
||||
> ```swift
|
||||
> // Plain observation
|
||||
> let observation = ValueObservation.tracking { db -> MyValue in
|
||||
> let players = try Player.fetchAll(db)
|
||||
> return computeMyValue(players)
|
||||
> }
|
||||
>
|
||||
> // Optimized observation
|
||||
> let observation = ValueObservation
|
||||
> .tracking { db try Player.fetchAll(db) }
|
||||
> .map { players in computeMyValue(players) }
|
||||
> ```
|
||||
>
|
||||
> The `map` operator performs its job without blocking database accesses, and without blocking the main thread.
|
||||
|
||||
> Tip: When the observation tracks a constant database region, create an optimized observation with the ``trackingConstantRegion(_:)`` method. See the documentation of this method for more information about what constitutes a "constant region", and the nature of the optimization.
|
||||
|
||||
## Topics
|
||||
|
||||
### Creating a ValueObservation
|
||||
|
||||
- ``tracking(_:)``
|
||||
- ``trackingConstantRegion(_:)``
|
||||
- ``tracking(region:fetch:)``
|
||||
- ``tracking(regions:fetch:)``
|
||||
|
||||
### Creating a Shared Observation
|
||||
|
||||
- ``shared(in:scheduling:extent:)``
|
||||
- ``SharedValueObservationExtent``
|
||||
|
||||
### Accessing Observed Values
|
||||
|
||||
- ``publisher(in:scheduling:)``
|
||||
- ``start(in:scheduling:onError:onChange:)``
|
||||
- ``values(in:scheduling:bufferingPolicy:)``
|
||||
- ``DatabaseCancellable``
|
||||
- ``ValueObservationScheduler``
|
||||
|
||||
### Mapping Values
|
||||
|
||||
- ``map(_:)``
|
||||
|
||||
### Filtering Values
|
||||
|
||||
- ``removeDuplicates()``
|
||||
- ``removeDuplicates(by:)``
|
||||
|
||||
### Requiring Write Access
|
||||
|
||||
- ``requiresWriteAccess``
|
||||
|
||||
### Debugging
|
||||
|
||||
- ``handleEvents(willStart:willFetch:willTrackRegion:databaseDidChange:didReceiveValue:didFail:didCancel:)``
|
||||
- ``print(_:to:)``
|
||||
|
||||
### Support
|
||||
|
||||
- ``ValueReducer``
|
||||
@@ -33,7 +33,7 @@ migrator.registerMigration("Add books and author.birthYear") { db in
|
||||
t.column("title", .text).notNull()
|
||||
}
|
||||
|
||||
try db.alter(table: "author") { t
|
||||
try db.alter(table: "author") { t in
|
||||
t.add(column: "birthYear", .integer)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
|
||||
Record types and the query interface build SQL queries for you.
|
||||
|
||||
## Overview
|
||||
|
||||
For an overview, see [Records](https://github.com/groue/GRDB.swift/blob/master/README.md#records), and [The Query Interface](https://github.com/groue/GRDB.swift/blob/master/README.md#the-query-interface).
|
||||
|
||||
## Topics
|
||||
|
||||
### Records
|
||||
|
||||
@@ -62,6 +62,8 @@ try dbQueue.read { db in
|
||||
}
|
||||
```
|
||||
|
||||
For a more detailed overview, see [SQLite API](https://github.com/groue/GRDB.swift/blob/master/README.md#sqlite-api).
|
||||
|
||||
## Topics
|
||||
|
||||
### Fundamental Database Types
|
||||
|
||||
+8
-1
@@ -35,6 +35,10 @@ import Foundation
|
||||
/// - ``FTS5WrapperTokenizer``
|
||||
/// - ``FTS5TokenFlags``
|
||||
/// - ``FTS5Tokenization``
|
||||
///
|
||||
/// ### Low-Level FTS5 Customization
|
||||
///
|
||||
/// - ``api(_:)``
|
||||
public struct FTS5 {
|
||||
/// Options for Latin script characters. Matches the raw "remove_diacritics"
|
||||
/// tokenizer argument.
|
||||
@@ -100,7 +104,10 @@ public struct FTS5 {
|
||||
}
|
||||
}
|
||||
|
||||
static func api(_ db: Database) -> UnsafePointer<fts5_api> {
|
||||
/// Returns a pointer to the `fts5_api` structure.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#extending_fts5>
|
||||
public static func api(_ db: Database) -> UnsafePointer<fts5_api> {
|
||||
// Access to FTS5 is one of the rare SQLite api which was broken in
|
||||
// SQLite 3.20.0+, for security reasons:
|
||||
//
|
||||
|
||||
@@ -533,7 +533,7 @@ extension QueryInterfaceRequest {
|
||||
return try SQLQueryGenerator(relation: relation).makeDeleteStatement(db, selection: selection)
|
||||
}
|
||||
|
||||
/// Returns a cursor over the record deleted by a
|
||||
/// Returns a cursor over the records deleted by a
|
||||
/// `DELETE RETURNING` statement.
|
||||
///
|
||||
/// For example:
|
||||
@@ -553,7 +553,7 @@ extension QueryInterfaceRequest {
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A ``RecordCursor`` over deleted records.
|
||||
/// - returns: A ``RecordCursor`` over the deleted records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func deleteAndFetchCursor(_ db: Database)
|
||||
throws -> RecordCursor<RowDecoder>
|
||||
@@ -646,7 +646,7 @@ extension QueryInterfaceRequest {
|
||||
return try SQLQueryGenerator(relation: relation).makeDeleteStatement(db, selection: selection)
|
||||
}
|
||||
|
||||
/// Returns a cursor over the record deleted by a
|
||||
/// Returns a cursor over the records deleted by a
|
||||
/// `DELETE RETURNING` statement.
|
||||
///
|
||||
/// For example:
|
||||
@@ -666,7 +666,7 @@ extension QueryInterfaceRequest {
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A ``RecordCursor`` over deleted records.
|
||||
/// - returns: A ``RecordCursor`` over the deleted records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
|
||||
public func deleteAndFetchCursor(_ db: Database)
|
||||
@@ -865,7 +865,7 @@ extension QueryInterfaceRequest {
|
||||
return updateStatement
|
||||
}
|
||||
|
||||
/// Returns a cursor over the record updated by an
|
||||
/// Returns a cursor over the records updated by an
|
||||
/// `UPDATE RETURNING` statement.
|
||||
///
|
||||
/// For example:
|
||||
@@ -1018,7 +1018,7 @@ extension QueryInterfaceRequest {
|
||||
return updateStatement
|
||||
}
|
||||
|
||||
/// Returns a cursor over the record updated by an
|
||||
/// Returns a cursor over the records updated by an
|
||||
/// `UPDATE RETURNING` statement.
|
||||
///
|
||||
/// For example:
|
||||
|
||||
@@ -803,9 +803,9 @@ public final class RecordCursor<Record: FetchableRecord>: DatabaseCursor {
|
||||
let _row: Row // Instantiated once, reused for performance
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
|
||||
let statement = try statement.databaseCursorStatement(with: arguments)
|
||||
self._statement = statement
|
||||
_row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
try statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
|
||||
@@ -133,12 +133,15 @@ public protocol TableRecord {
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// static let databaseSelection = [AllColumns()]
|
||||
/// static let databaseSelection: [any SQLSelectable] = [AllColumns()]
|
||||
/// }
|
||||
///
|
||||
/// struct PartialPlayer: TableRecord {
|
||||
/// static let databaseTableName = "player"
|
||||
/// static let databaseSelection = [Column("id"), Column("name")]
|
||||
/// static let databaseSelection: [any SQLSelectable] = [
|
||||
/// Column("id"),
|
||||
/// Column("name"),
|
||||
/// ]
|
||||
/// }
|
||||
///
|
||||
/// // SELECT * FROM player
|
||||
@@ -147,6 +150,11 @@ public protocol TableRecord {
|
||||
/// // SELECT id, name FROM player
|
||||
/// try PartialPlayer.fetchAll(db)
|
||||
/// ```
|
||||
///
|
||||
/// > Important: Make sure the `databaseSelection` property is
|
||||
/// > explicitly declared as `[any SQLSelectable]`. If it is not, the
|
||||
/// > Swift compiler may silently miss the protocol requirement,
|
||||
/// > resulting in sticky `SELECT *` requests.
|
||||
static var databaseSelection: [any SQLSelectable] { get }
|
||||
}
|
||||
|
||||
@@ -661,6 +669,31 @@ extension TableRecord {
|
||||
// MARK: - RecordError
|
||||
|
||||
/// A record error.
|
||||
///
|
||||
/// `RecordError` is thrown by ``MutablePersistableRecord`` types when an
|
||||
/// `update` method could not find any row to update:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// try player.update(db)
|
||||
/// } catch let RecordError.recordNotFound(databaseTableName: table, key: key) {
|
||||
/// print("Key \(key) was not found in table \(table).")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// `RecordError` is also thrown by ``FetchableRecord`` types when a
|
||||
/// `find` method does not find any record:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// let player = try Player.find(db, id: 42)
|
||||
/// } catch let RecordError.recordNotFound(databaseTableName: table, key: key) {
|
||||
/// print("Key \(key) was not found in table \(table).")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// You can create `RecordError` instances with the
|
||||
/// ``TableRecord/recordNotFound(_:id:)`` method and its variants.
|
||||
public enum RecordError: Error {
|
||||
/// A record does not exist in the database.
|
||||
///
|
||||
|
||||
@@ -26,6 +26,8 @@ final class LockedBox<T> {
|
||||
/// $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() }
|
||||
|
||||
@@ -250,6 +250,16 @@ extension ValueConcurrentObserver {
|
||||
return AnyDatabaseCancellable(self)
|
||||
}
|
||||
|
||||
private func startObservation(_ writerDB: Database, observedRegion: DatabaseRegion) {
|
||||
observationState.region = observedRegion
|
||||
assert(observationState.isModified == false)
|
||||
writerDB.add(transactionObserver: self, extent: .observerLifetime)
|
||||
}
|
||||
}
|
||||
|
||||
// swiftlint:disable:next line_length
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
extension ValueConcurrentObserver {
|
||||
/// Synchronously starts the observation, and returns the initial value.
|
||||
///
|
||||
/// Unlike `asyncStart()`, this method does not notify the initial value or error.
|
||||
@@ -259,27 +269,22 @@ extension ValueConcurrentObserver {
|
||||
// without having to wait for an eventual long-running write
|
||||
// transaction to complete.
|
||||
//
|
||||
// Fetch value & tracked region in a synchronous way.
|
||||
//
|
||||
// We perform the initial read from a DatabaseSnapshot, because
|
||||
// it is a handy way to keep a read transaction open until we grab a
|
||||
// write access, and compare the database versions.
|
||||
let initialSnapshot = try databaseAccess.dbPool.makeSnapshot()
|
||||
let (fetchedValue, initialRegion, initialWALSnapshot) = try initialSnapshot.read {
|
||||
db -> (Reducer.Fetched, DatabaseRegion, WALSnapshot?) in
|
||||
// swiftlint:disable:previous closure_parameter_position
|
||||
|
||||
// We perform the initial read from a long-lived WAL snapshot
|
||||
// transaction, because it is a handy way to keep a read transaction
|
||||
// open until we grab a write access, and compare the database versions.
|
||||
let walSnapshotTransaction = try databaseAccess.dbPool.walSnapshotTransaction()
|
||||
let (fetchedValue, initialRegion) = try walSnapshotTransaction.read { db -> (Reducer.Fetched, DatabaseRegion) in
|
||||
switch trackingMode {
|
||||
case let .constantRegion(regions):
|
||||
let fetchedValue = try databaseAccess.fetch(db)
|
||||
let region = try DatabaseRegion.union(regions)(db)
|
||||
let initialRegion = try region.observableRegion(db)
|
||||
return (fetchedValue, initialRegion, try? WALSnapshot(db))
|
||||
return (fetchedValue, initialRegion)
|
||||
|
||||
case .constantRegionRecordedFromSelection,
|
||||
.nonConstantRegionRecordedFromSelection:
|
||||
let (fetchedValue, initialRegion) = try databaseAccess.fetchRecordingObservedRegion(db)
|
||||
return (fetchedValue, initialRegion, try? WALSnapshot(db))
|
||||
return (fetchedValue, initialRegion)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -294,8 +299,7 @@ extension ValueConcurrentObserver {
|
||||
// Start observation
|
||||
asyncStartObservation(
|
||||
from: databaseAccess,
|
||||
initialSnapshot: initialSnapshot,
|
||||
initialWALSnapshot: initialWALSnapshot,
|
||||
walSnapshotTransaction: walSnapshotTransaction,
|
||||
initialRegion: initialRegion)
|
||||
|
||||
return initialValue
|
||||
@@ -310,74 +314,76 @@ extension ValueConcurrentObserver {
|
||||
// without having to wait for an eventual long-running write
|
||||
// transaction to complete.
|
||||
//
|
||||
// We perform the initial read from a DatabaseSnapshot, because
|
||||
// it is a handy way to keep a read transaction open until we grab a
|
||||
// write access, and compare the database versions.
|
||||
do {
|
||||
let initialSnapshot = try databaseAccess.dbPool.makeSnapshot()
|
||||
initialSnapshot.asyncRead { dbResult in
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
do {
|
||||
// Fetch
|
||||
let fetchedValue: Reducer.Fetched
|
||||
let initialRegion: DatabaseRegion
|
||||
let db = try dbResult.get()
|
||||
switch self.trackingMode {
|
||||
case let .constantRegion(regions):
|
||||
fetchedValue = try databaseAccess.fetch(db)
|
||||
let region = try DatabaseRegion.union(regions)(db)
|
||||
initialRegion = try region.observableRegion(db)
|
||||
// We perform the initial read from a long-lived WAL snapshot
|
||||
// transaction, because it is a handy way to keep a read transaction
|
||||
// open until we grab a write access, and compare the database versions.
|
||||
databaseAccess.dbPool.asyncWALSnapshotTransaction { result in
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
do {
|
||||
// Fetch
|
||||
let walSnapshotTransaction = try result.get()
|
||||
// Second async jump because that's how
|
||||
// `DatabasePool.asyncWALSnapshotTransaction` has to be used.
|
||||
walSnapshotTransaction.asyncRead { db in
|
||||
do {
|
||||
let fetchedValue: Reducer.Fetched
|
||||
let initialRegion: DatabaseRegion
|
||||
|
||||
case .constantRegionRecordedFromSelection,
|
||||
.nonConstantRegionRecordedFromSelection:
|
||||
(fetchedValue, initialRegion) = try databaseAccess.fetchRecordingObservedRegion(db)
|
||||
}
|
||||
|
||||
// Reduce
|
||||
//
|
||||
// Reducing is performed asynchronously, so that we do not lock
|
||||
// a database dispatch queue longer than necessary.
|
||||
self.reduceQueue.async {
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
do {
|
||||
guard let initialValue = try self.reducer._value(fetchedValue) else {
|
||||
fatalError("Broken contract: reducer has no initial value")
|
||||
}
|
||||
switch self.trackingMode {
|
||||
case let .constantRegion(regions):
|
||||
fetchedValue = try databaseAccess.fetch(db)
|
||||
let region = try DatabaseRegion.union(regions)(db)
|
||||
initialRegion = try region.observableRegion(db)
|
||||
|
||||
// Notify
|
||||
self.scheduler.schedule {
|
||||
let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange }
|
||||
guard let onChange else { return /* Cancelled */ }
|
||||
onChange(initialValue)
|
||||
}
|
||||
} catch {
|
||||
self.notifyError(error)
|
||||
case .constantRegionRecordedFromSelection,
|
||||
.nonConstantRegionRecordedFromSelection:
|
||||
(fetchedValue, initialRegion) = try databaseAccess.fetchRecordingObservedRegion(db)
|
||||
}
|
||||
|
||||
// Reduce
|
||||
//
|
||||
// Reducing is performed asynchronously, so that we do not lock
|
||||
// a database dispatch queue longer than necessary.
|
||||
self.reduceQueue.async {
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
do {
|
||||
guard let initialValue = try self.reducer._value(fetchedValue) else {
|
||||
fatalError("Broken contract: reducer has no initial value")
|
||||
}
|
||||
|
||||
// Notify
|
||||
self.scheduler.schedule {
|
||||
let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange }
|
||||
guard let onChange else { return /* Cancelled */ }
|
||||
onChange(initialValue)
|
||||
}
|
||||
} catch {
|
||||
self.notifyError(error)
|
||||
}
|
||||
}
|
||||
|
||||
// Start observation
|
||||
self.asyncStartObservation(
|
||||
from: databaseAccess,
|
||||
walSnapshotTransaction: walSnapshotTransaction,
|
||||
initialRegion: initialRegion)
|
||||
} catch {
|
||||
self.notifyError(error)
|
||||
}
|
||||
|
||||
// Start observation
|
||||
self.asyncStartObservation(
|
||||
from: databaseAccess,
|
||||
initialSnapshot: initialSnapshot,
|
||||
initialWALSnapshot: try? WALSnapshot(db),
|
||||
initialRegion: initialRegion)
|
||||
} catch {
|
||||
self.notifyError(error)
|
||||
}
|
||||
} catch {
|
||||
self.notifyError(error)
|
||||
}
|
||||
} catch {
|
||||
self.notifyError(error)
|
||||
}
|
||||
}
|
||||
|
||||
private func asyncStartObservation(
|
||||
from databaseAccess: DatabaseAccess,
|
||||
initialSnapshot: DatabaseSnapshot,
|
||||
initialWALSnapshot: WALSnapshot?,
|
||||
walSnapshotTransaction: WALSnapshotTransaction,
|
||||
initialRegion: DatabaseRegion)
|
||||
{
|
||||
databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in
|
||||
@@ -389,17 +395,15 @@ extension ValueConcurrentObserver {
|
||||
|
||||
// Transaction is needed for comparing version snapshots
|
||||
try writerDB.isolated(readOnly: true) {
|
||||
// Keep initialSnapshot alive until we have compared
|
||||
// database versions. It prevents database checkpointing,
|
||||
// and keeps WAL snapshots (`sqlite3_snapshot`) valid
|
||||
// and comparable.
|
||||
let isModified = withExtendedLifetime(initialSnapshot) {
|
||||
guard let initialWALSnapshot,
|
||||
let currentWALSnapshot = try? WALSnapshot(writerDB)
|
||||
else {
|
||||
// Keep walSnapshotTransaction alive until we have
|
||||
// compared database versions. `WALSnapshot` alone is
|
||||
// not able to prevent database checkpointing, and keep
|
||||
// snapshots comparable.
|
||||
let isModified = withExtendedLifetime(walSnapshotTransaction) {
|
||||
guard let currentWALSnapshot = try? WALSnapshot(writerDB) else {
|
||||
return true
|
||||
}
|
||||
let ordering = initialWALSnapshot.compare(currentWALSnapshot)
|
||||
let ordering = walSnapshotTransaction.walSnapshot.compare(currentWALSnapshot)
|
||||
assert(ordering <= 0, "Unexpected snapshot ordering")
|
||||
return ordering < 0
|
||||
}
|
||||
@@ -463,13 +467,176 @@ extension ValueConcurrentObserver {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#else
|
||||
extension ValueConcurrentObserver {
|
||||
/// Synchronously starts the observation, and returns the initial value.
|
||||
///
|
||||
/// Unlike `asyncStart()`, this method does not notify the initial value or error.
|
||||
private func syncStart(from databaseAccess: DatabaseAccess) throws -> Reducer.Value {
|
||||
// Start from a read access. The whole point of using a DatabasePool
|
||||
// for observing the database is to be able to fetch the initial value
|
||||
// without having to wait for an eventual long-running write
|
||||
// transaction to complete.
|
||||
let (fetchedValue, initialRegion) = try databaseAccess.dbPool.read { db -> (Reducer.Fetched, DatabaseRegion) in
|
||||
switch trackingMode {
|
||||
case let .constantRegion(regions):
|
||||
let fetchedValue = try databaseAccess.fetch(db)
|
||||
let region = try DatabaseRegion.union(regions)(db)
|
||||
let initialRegion = try region.observableRegion(db)
|
||||
return (fetchedValue, initialRegion)
|
||||
|
||||
case .constantRegionRecordedFromSelection,
|
||||
.nonConstantRegionRecordedFromSelection:
|
||||
let (fetchedValue, initialRegion) = try databaseAccess.fetchRecordingObservedRegion(db)
|
||||
return (fetchedValue, initialRegion)
|
||||
}
|
||||
}
|
||||
|
||||
// Reduce
|
||||
let initialValue = try reduceQueue.sync {
|
||||
guard let initialValue = try reducer._value(fetchedValue) else {
|
||||
fatalError("Broken contract: reducer has no initial value")
|
||||
}
|
||||
return initialValue
|
||||
}
|
||||
|
||||
// Start observation
|
||||
asyncStartObservation(
|
||||
from: databaseAccess,
|
||||
initialRegion: initialRegion)
|
||||
|
||||
return initialValue
|
||||
}
|
||||
|
||||
private func startObservation(_ writerDB: Database, observedRegion: DatabaseRegion) {
|
||||
observationState.region = observedRegion
|
||||
assert(observationState.isModified == false)
|
||||
writerDB.add(transactionObserver: self, extent: .observerLifetime)
|
||||
/// Asynchronously starts the observation
|
||||
///
|
||||
/// Unlike `syncStart()`, this method does notify the initial value or error.
|
||||
private func asyncStart(from databaseAccess: DatabaseAccess) {
|
||||
// Start from a read access. The whole point of using a DatabasePool
|
||||
// for observing the database is to be able to fetch the initial value
|
||||
// without having to wait for an eventual long-running write
|
||||
// transaction to complete.
|
||||
databaseAccess.dbPool.asyncRead { dbResult in
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
do {
|
||||
// Fetch
|
||||
let fetchedValue: Reducer.Fetched
|
||||
let initialRegion: DatabaseRegion
|
||||
let db = try dbResult.get()
|
||||
switch self.trackingMode {
|
||||
case let .constantRegion(regions):
|
||||
fetchedValue = try databaseAccess.fetch(db)
|
||||
let region = try DatabaseRegion.union(regions)(db)
|
||||
initialRegion = try region.observableRegion(db)
|
||||
|
||||
case .constantRegionRecordedFromSelection,
|
||||
.nonConstantRegionRecordedFromSelection:
|
||||
(fetchedValue, initialRegion) = try databaseAccess.fetchRecordingObservedRegion(db)
|
||||
}
|
||||
|
||||
// Reduce
|
||||
//
|
||||
// Reducing is performed asynchronously, so that we do not lock
|
||||
// a database dispatch queue longer than necessary.
|
||||
self.reduceQueue.async {
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
do {
|
||||
guard let initialValue = try self.reducer._value(fetchedValue) else {
|
||||
fatalError("Broken contract: reducer has no initial value")
|
||||
}
|
||||
|
||||
// Notify
|
||||
self.scheduler.schedule {
|
||||
let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange }
|
||||
guard let onChange else { return /* Cancelled */ }
|
||||
onChange(initialValue)
|
||||
}
|
||||
} catch {
|
||||
self.notifyError(error)
|
||||
}
|
||||
}
|
||||
|
||||
// Start observation
|
||||
self.asyncStartObservation(
|
||||
from: databaseAccess,
|
||||
initialRegion: initialRegion)
|
||||
} catch {
|
||||
self.notifyError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func asyncStartObservation(
|
||||
from databaseAccess: DatabaseAccess,
|
||||
initialRegion: DatabaseRegion)
|
||||
{
|
||||
databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in
|
||||
let events = self.lock.synchronized { self.notificationCallbacks?.events }
|
||||
guard let events else { return /* Cancelled */ }
|
||||
events.databaseDidChange?()
|
||||
|
||||
do {
|
||||
try writerDB.isolated(readOnly: true) {
|
||||
// Fetch
|
||||
let fetchedValue: Reducer.Fetched
|
||||
let observedRegion: DatabaseRegion
|
||||
switch self.trackingMode {
|
||||
case .constantRegion:
|
||||
fetchedValue = try databaseAccess.fetch(writerDB)
|
||||
observedRegion = initialRegion
|
||||
events.willTrackRegion?(initialRegion)
|
||||
self.startObservation(writerDB, observedRegion: initialRegion)
|
||||
|
||||
case .constantRegionRecordedFromSelection,
|
||||
.nonConstantRegionRecordedFromSelection:
|
||||
(fetchedValue, observedRegion) = try databaseAccess.fetchRecordingObservedRegion(writerDB)
|
||||
events.willTrackRegion?(observedRegion)
|
||||
self.startObservation(writerDB, observedRegion: observedRegion)
|
||||
}
|
||||
|
||||
// Reduce
|
||||
//
|
||||
// Reducing is performed asynchronously, so that we do not lock
|
||||
// the writer dispatch queue longer than necessary.
|
||||
//
|
||||
// Important: reduceQueue.async guarantees the same ordering
|
||||
// between transactions and notifications!
|
||||
self.reduceQueue.async {
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
do {
|
||||
let value = try self.reducer._value(fetchedValue)
|
||||
|
||||
// Notify
|
||||
if let value {
|
||||
self.scheduler.schedule {
|
||||
let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange }
|
||||
guard let onChange else { return /* Cancelled */ }
|
||||
onChange(value)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
let dbPool = self.lock.synchronized { self.databaseAccess?.dbPool }
|
||||
dbPool?.asyncWriteWithoutTransaction { writerDB in
|
||||
self.stopDatabaseObservation(writerDB)
|
||||
}
|
||||
self.notifyError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
self.notifyError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Observing Database Transactions
|
||||
|
||||
|
||||
@@ -4,344 +4,6 @@ import Combine
|
||||
import Dispatch
|
||||
import Foundation
|
||||
|
||||
/// `ValueObservation` tracks changes in the results of database requests, and
|
||||
/// notifies fresh values whenever the database changes.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// Tracked changes are insertions, updates, and deletions that impact the
|
||||
/// tracked value, whether performed with raw SQL, or <doc:QueryInterface>.
|
||||
/// This includes indirect changes triggered by
|
||||
/// [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions)
|
||||
/// or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
|
||||
///
|
||||
/// Changes to internal system tables (such as `sqlite_master`) and changes to
|
||||
/// [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables are
|
||||
/// not notified.
|
||||
///
|
||||
/// ## ValueObservation Usage
|
||||
///
|
||||
/// 1. Make sure that a unique database connection, ``DatabaseQueue`` or
|
||||
/// ``DatabasePool``, is kept open during the whole duration of
|
||||
/// the observation.
|
||||
///
|
||||
/// `ValueObservation` does not notify changes performed by
|
||||
/// external connections.
|
||||
/// See <doc:DatabaseSharing#How-to-perform-cross-process-database-observation>
|
||||
/// for more information.
|
||||
///
|
||||
/// 2. Create a `ValueObservation` with a closure that fetches the
|
||||
/// observed value:
|
||||
///
|
||||
/// ```swift
|
||||
/// let observation = ValueObservation.tracking { db in
|
||||
/// // Fetch and return the observed value
|
||||
/// }
|
||||
///
|
||||
/// // For example, an observation of [Player], which tracks all players:
|
||||
/// let observation = ValueObservation.tracking { db in
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
///
|
||||
/// // The same observation, using shorthand notation:
|
||||
/// let observation = ValueObservation.tracking(Player.fetchAll)
|
||||
/// ```
|
||||
///
|
||||
/// There is no limit on the values that can be observed. An observation
|
||||
/// can perform multiple requests, from multiple database tables, and use
|
||||
/// raw SQL. See ``tracking(_:)`` for some examples.
|
||||
///
|
||||
/// 3. Start the observation in order to be notified of changes:
|
||||
///
|
||||
/// ```swift
|
||||
/// let cancellable = observation.start(in: dbQueue) { error in
|
||||
/// // Handle error
|
||||
/// } onChange: { (players: [Player]) in
|
||||
/// print("Fresh players", players)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// 4. Stop the observation by calling the ``DatabaseCancellable/cancel()``
|
||||
/// method on the object returned by the `start` method. Cancellation is
|
||||
/// automatic when the cancellable is deallocated:
|
||||
///
|
||||
/// ```swift
|
||||
/// cancellable.cancel()
|
||||
/// ```
|
||||
///
|
||||
/// `ValueObservation` can also be turned into an async sequence, a Combine
|
||||
/// publisher, or an RxSwift observable (see the companion library
|
||||
/// [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB)):
|
||||
///
|
||||
/// - Async sequence:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// for try await players in observation.values(in: dbQueue) {
|
||||
/// print("Fresh players", players)
|
||||
/// }
|
||||
/// } catch {
|
||||
/// // Handle error
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - Combine Publisher:
|
||||
///
|
||||
/// ```swift
|
||||
/// let cancellable = observation.publisher(in: dbQueue).sink { completion in
|
||||
/// // Handle completion
|
||||
/// } receiveValue: { (players: [Player]) in
|
||||
/// print("Fresh players", players)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ## ValueObservation Behavior
|
||||
///
|
||||
/// `ValueObservation` notifies an initial value before the eventual changes.
|
||||
///
|
||||
/// `ValueObservation` only notifies changes committed to disk.
|
||||
///
|
||||
/// By default, `ValueObservation` notifies a fresh value whenever any component
|
||||
/// of its fetched value is modified (any fetched column, row, etc.). This can
|
||||
/// be configured:
|
||||
/// see <doc:ValueObservation#Specifying-the-Tracked-Region>.
|
||||
///
|
||||
/// By default, `ValueObservation` notifies the initial value, as well as
|
||||
/// eventual changes and errors, on the main dispatch queue, asynchronously.
|
||||
/// This can be configured:
|
||||
/// see <doc:ValueObservation#ValueObservation-Scheduling>.
|
||||
///
|
||||
/// `ValueObservation` may coalesce subsequent changes into a
|
||||
/// single notification.
|
||||
///
|
||||
/// `ValueObservation` may notify consecutive identical values. You can filter
|
||||
/// out the undesired duplicates with the ``removeDuplicates()`` method.
|
||||
///
|
||||
/// Starting an observation retains the database connection, until it is
|
||||
/// stopped. As long as the observation is active, the database connection
|
||||
/// won't be deallocated.
|
||||
///
|
||||
/// The database observation stops when the cancellable returned by the `start`
|
||||
/// method is cancelled or deallocated, or if an error occurs.
|
||||
///
|
||||
/// Take care that there are use cases that `ValueObservation` is unfit for.
|
||||
/// For example, an application may need to process absolutely all changes,
|
||||
/// and avoid any coalescing. An application may also need to process changes
|
||||
/// before any further modifications could be performed in the database file. In
|
||||
/// those cases, the application needs to track *individual transactions*, not
|
||||
/// values: use ``DatabaseRegionObservation``. If you need to process
|
||||
/// changes before they are committed to disk, use ``TransactionObserver``.
|
||||
///
|
||||
/// ## ValueObservation Scheduling
|
||||
///
|
||||
/// By default, `ValueObservation` notifies the initial value, as well as
|
||||
/// eventual changes and errors, on the main dispatch queue, asynchronously:
|
||||
///
|
||||
/// ```swift
|
||||
/// // The default scheduling
|
||||
/// let cancellable = observation.start(in: dbQueue) { error in
|
||||
/// // Called asynchronously on the main dispatch queue
|
||||
/// } onChange: { value in
|
||||
/// // Called asynchronously on the main dispatch queue
|
||||
/// print("Fresh value", value)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// You can change this behavior by adding a `scheduling` argument to the
|
||||
/// `start()` method.
|
||||
///
|
||||
/// For example, the ``ValueObservationScheduler/immediate`` scheduler
|
||||
/// notifies all values on the main dispatch queue, and notifies the first
|
||||
/// one immediately when the observation starts.
|
||||
///
|
||||
/// It is very useful in graphic applications, because you can configure views
|
||||
/// right away, without waiting for the initial value to be fetched eventually.
|
||||
/// You don't have to implement any empty or loading screen, or to prevent some
|
||||
/// undesired initial animation.
|
||||
///
|
||||
/// The `immediate` scheduling requires that the observation starts from the
|
||||
/// main dispatch queue (a fatal error is raised otherwise):
|
||||
///
|
||||
/// ```swift
|
||||
/// let cancellable = observation.start(in: dbQueue, scheduling: .immediate) { error in
|
||||
/// // Called on the main dispatch queue
|
||||
/// } onChange: { value in
|
||||
/// // Called on the main dispatch queue
|
||||
/// print("Fresh value", value)
|
||||
/// }
|
||||
/// // <- Here "Fresh value" has already been printed.
|
||||
/// ```
|
||||
///
|
||||
/// The other built-in scheduler ``ValueObservationScheduler/async(onQueue:)``
|
||||
/// asynchronously schedules values and errors on the dispatch queue of
|
||||
/// your choice.
|
||||
///
|
||||
/// ## ValueObservation Sharing
|
||||
///
|
||||
/// Sharing a `ValueObservation` spares database resources. When a database
|
||||
/// change happens, a fresh value is fetched only once, and then notified to
|
||||
/// all clients of the shared observation.
|
||||
///
|
||||
/// You build a shared observation with ``shared(in:scheduling:extent:)``:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SharedValueObservation<[Player]>
|
||||
/// let sharedObservation = ValueObservation
|
||||
/// .tracking { db in try Player.fetchAll(db) }
|
||||
/// .shared(in: dbQueue)
|
||||
/// ```
|
||||
///
|
||||
/// `ValueObservation` and `SharedValueObservation` are nearly identical, but
|
||||
/// the latter has no operator such as `map`. As a replacement, you may
|
||||
/// for example use Combine apis:
|
||||
///
|
||||
/// ```swift
|
||||
/// let cancellable = try sharedObservation
|
||||
/// .publisher() // Turn shared observation into a Combine Publisher
|
||||
/// .map { ... } // The map operator from Combine
|
||||
/// .sink(...)
|
||||
/// ```
|
||||
///
|
||||
///
|
||||
/// ## Specifying the Tracked Region
|
||||
///
|
||||
/// While the standard ``tracking(_:)`` method lets you track changes to a
|
||||
/// fetched value and receive any changes to it, sometimes your use case might
|
||||
/// require more granular control.
|
||||
///
|
||||
/// Consider a scenario where you'd like to get a specific Player's row, but
|
||||
/// only when their `score` column changes. You can use
|
||||
/// ``tracking(region:fetch:)`` to do just that:
|
||||
///
|
||||
/// ```swift
|
||||
/// let observation = ValueObservation.tracking(
|
||||
/// // Define what database region constitutes a "change"
|
||||
/// region: Player.select(Column("score")).filter(id: 1),
|
||||
/// // Define what to fetch upon such change
|
||||
/// fetch: { db in try Player.fetchOne(db, id: 1) }
|
||||
/// )
|
||||
/// ```
|
||||
///
|
||||
/// This overload of `ValueObservation` lets you entirely separate the
|
||||
/// **observed region** from the **fetched value** itself, providing utmost
|
||||
/// flexibility. See ``DatabaseRegionConvertible`` for more information about
|
||||
/// the regions that can be tracked.
|
||||
///
|
||||
/// ## ValueObservation Performance
|
||||
///
|
||||
/// This section further describes runtime aspects of `ValueObservation`, and
|
||||
/// provides some optimization tips for demanding applications.
|
||||
///
|
||||
/// **`ValueObservation` is triggered by database transactions that may modify
|
||||
/// the tracked value.**
|
||||
///
|
||||
/// Precisely speaking, `ValueObservation` tracks changes in a
|
||||
/// ``DatabaseRegion``, not changes in values.
|
||||
///
|
||||
/// For example, if you track the maximum score of players, all transactions
|
||||
/// that impact the `score` column of the `player` database table (any update,
|
||||
/// insertion, or deletion) trigger the observation, even if the maximum score
|
||||
/// itself is not changed.
|
||||
///
|
||||
/// You can filter out undesired duplicate notifications with the
|
||||
/// ``removeDuplicates()`` method.
|
||||
///
|
||||
/// **ValueObservation can create database contention.** In other words, active
|
||||
/// observations take a toll on the constrained database resources. When
|
||||
/// triggered by impactful transactions, observations fetch fresh values, and
|
||||
/// can delay read and write database accesses of other application components.
|
||||
///
|
||||
/// When needed, you can help GRDB optimize observations and reduce
|
||||
/// database contention:
|
||||
///
|
||||
/// > Tip: Stop observations when possible.
|
||||
/// >
|
||||
/// > For example, if a `UIViewController` needs to display database values, it
|
||||
/// > can start the observation in `viewWillAppear`, and stop it in
|
||||
/// > `viewWillDisappear`.
|
||||
/// >
|
||||
/// > In a SwiftUI application, you can profit from the
|
||||
/// > [GRDBQuery](https://github.com/groue/GRDBQuery) companion library, and its
|
||||
/// > [`View.queryObservation(_:)`](https://swiftpackageindex.com/groue/grdbquery/documentation/grdbquery/queryobservation)
|
||||
/// > method.
|
||||
///
|
||||
/// > Tip: Share observations when possible.
|
||||
/// >
|
||||
/// > Each call to `ValueObservation.start` method triggers independent values
|
||||
/// > refreshes. When several components of your app are interested in the same
|
||||
/// > value, consider sharing the observation
|
||||
/// > with ``shared(in:scheduling:extent:)``.
|
||||
///
|
||||
/// > Tip: Use a ``DatabasePool``, because it can perform multi-threaded
|
||||
/// > database accesses.
|
||||
///
|
||||
/// > Tip: When the observation processes some raw fetched values, use the
|
||||
/// > ``map(_:)`` operator:
|
||||
/// >
|
||||
/// > ```swift
|
||||
/// > // Plain observation
|
||||
/// > let observation = ValueObservation.tracking { db -> MyValue in
|
||||
/// > let players = try Player.fetchAll(db)
|
||||
/// > return computeMyValue(players)
|
||||
/// > }
|
||||
/// >
|
||||
/// > // Optimized observation
|
||||
/// > let observation = ValueObservation
|
||||
/// > .tracking { db try Player.fetchAll(db) }
|
||||
/// > .map { players in computeMyValue(players) }
|
||||
/// > ```
|
||||
/// >
|
||||
/// > The `map` operator helps reducing database contention because it performs
|
||||
/// > its job without blocking database accesses.
|
||||
///
|
||||
/// > Tip: When the observation tracks a constant database region, create an
|
||||
/// > optimized observation with the ``trackingConstantRegion(_:)`` method. See
|
||||
/// > the documentation of this method for more information about what
|
||||
/// > constitutes a "constant region", and the nature of the optimization.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a ValueObservation
|
||||
///
|
||||
/// - ``tracking(_:)``
|
||||
/// - ``trackingConstantRegion(_:)``
|
||||
/// - ``tracking(region:fetch:)``
|
||||
/// - ``tracking(regions:fetch:)``
|
||||
///
|
||||
/// ### Creating a Shared Observation
|
||||
///
|
||||
/// - ``shared(in:scheduling:extent:)``
|
||||
/// - ``SharedValueObservationExtent``
|
||||
///
|
||||
/// ### Accessing Observed Values
|
||||
///
|
||||
/// - ``publisher(in:scheduling:)``
|
||||
/// - ``start(in:scheduling:onError:onChange:)``
|
||||
/// - ``values(in:scheduling:bufferingPolicy:)``
|
||||
/// - ``DatabaseCancellable``
|
||||
/// - ``ValueObservationScheduler``
|
||||
///
|
||||
/// ### Mapping Values
|
||||
///
|
||||
/// - ``map(_:)``
|
||||
///
|
||||
/// ### Filtering Values
|
||||
///
|
||||
/// - ``removeDuplicates()``
|
||||
/// - ``removeDuplicates(by:)``
|
||||
///
|
||||
/// ### Requiring Write Access
|
||||
///
|
||||
/// - ``requiresWriteAccess``
|
||||
///
|
||||
/// ### Debugging
|
||||
///
|
||||
/// - ``handleEvents(willStart:willFetch:willTrackRegion:databaseDidChange:didReceiveValue:didFail:didCancel:)``
|
||||
/// - ``print(_:to:)``
|
||||
///
|
||||
/// ### Support
|
||||
///
|
||||
/// - ``ValueReducer``
|
||||
public struct ValueObservation<Reducer: _ValueReducer> {
|
||||
var events = ValueObservationEvents()
|
||||
|
||||
|
||||
@@ -276,6 +276,7 @@
|
||||
56D110F528AFC90800E64463 /* MutablePersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E728AFC90800E64463 /* MutablePersistableRecord+Save.swift */; };
|
||||
56D110F728AFC90800E64463 /* MutablePersistableRecord+Update.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E828AFC90800E64463 /* MutablePersistableRecord+Update.swift */; };
|
||||
56D110FF28AFC9C600E64463 /* MutablePersistableRecord+DAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110FE28AFC9C600E64463 /* MutablePersistableRecord+DAO.swift */; };
|
||||
56D3332329C38D7B00430680 /* WALSnapshotTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D3332129C38D7A00430680 /* WALSnapshotTransaction.swift */; };
|
||||
56D507611F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; };
|
||||
56D51D021EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; };
|
||||
56DA7D03260FAA1B00A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DA7D02260FAA1A00A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */; };
|
||||
@@ -763,6 +764,7 @@
|
||||
56D110E728AFC90800E64463 /* MutablePersistableRecord+Save.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Save.swift"; sourceTree = "<group>"; };
|
||||
56D110E828AFC90800E64463 /* MutablePersistableRecord+Update.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Update.swift"; sourceTree = "<group>"; };
|
||||
56D110FE28AFC9C600E64463 /* MutablePersistableRecord+DAO.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+DAO.swift"; sourceTree = "<group>"; };
|
||||
56D3332129C38D7A00430680 /* WALSnapshotTransaction.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshotTransaction.swift; sourceTree = "<group>"; };
|
||||
56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = "<group>"; };
|
||||
56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = "<group>"; };
|
||||
56DA7D02260FAA1A00A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordMinimalNonOptionalPrimaryKeySingleTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1462,6 +1464,7 @@
|
||||
56231E6025CEBF06001DFD2F /* RowDecodingError.swift */,
|
||||
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
|
||||
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
|
||||
56D3332129C38D7A00430680 /* WALSnapshotTransaction.swift */,
|
||||
56A6EB2226076F6A00C27594 /* SQL.swift */,
|
||||
56E9FAC32210468500C703A8 /* SQLInterpolation.swift */,
|
||||
56FBFED52210731000945324 /* SQLRequest.swift */,
|
||||
@@ -1981,6 +1984,7 @@
|
||||
56D110F328AFC90800E64463 /* MutablePersistableRecord.swift in Sources */,
|
||||
F3BA80831CFB2E67003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
|
||||
5657AABB1D107001006283EF /* NSData.swift in Sources */,
|
||||
56D3332329C38D7B00430680 /* WALSnapshotTransaction.swift in Sources */,
|
||||
5674A6E51F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
|
||||
5656A8652295BD56001FF3FF /* BelongsToAssociation.swift in Sources */,
|
||||
F3BA806A1CFB2E55003DC1BA /* DatabaseQueue.swift in Sources */,
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>6.8.0</string>
|
||||
<string>6.10.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -34,16 +34,6 @@ class DataMemoryTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
// This data should not be copied
|
||||
// (The deprecation warning is expected: we test a deprecated method.)
|
||||
let nonCopiedData = row.dataNoCopy(atIndex: 0)!
|
||||
XCTAssertEqual(nonCopiedData, data)
|
||||
nonCopiedData.withUnsafeBytes {
|
||||
XCTAssertEqual($0.baseAddress, blobPointer)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,16 +62,6 @@ class DataMemoryTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
// This data should not be copied
|
||||
// (The deprecation warning is expected: we test a deprecated method.)
|
||||
let nonCopiedData = nestedRow.dataNoCopy(atIndex: 0)!
|
||||
XCTAssertEqual(nonCopiedData, data)
|
||||
nonCopiedData.withUnsafeBytes {
|
||||
XCTAssertEqual($0.baseAddress, blobPointer)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,14 +89,62 @@ class DataMemoryTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
do {
|
||||
// This data should not be copied:
|
||||
// (The deprecation warning is expected: we test a deprecated method.)
|
||||
let nonCopiedData = row.dataNoCopy(atIndex: 0)!
|
||||
XCTAssertEqual(nonCopiedData, data)
|
||||
nonCopiedData.withUnsafeBytes { nonCopiedBuffer in
|
||||
XCTAssertEqual(nonCopiedBuffer.baseAddress, buffer.baseAddress)
|
||||
}
|
||||
}
|
||||
default:
|
||||
XCTFail("Not a blob")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, deprecated)
|
||||
func testDeprecatedMemoryBehavior() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
// Make sure Data is on the heap (15 bytes is enough)
|
||||
// For more context, see:
|
||||
// https://forums.swift.org/t/swift-5-how-to-test-data-bytesnocopydeallocator/20299/2?u=gwendal.roue
|
||||
let data = Data(repeating: 0xaa, count: 15)
|
||||
|
||||
do {
|
||||
let rows = try Row.fetchCursor(db, sql: "SELECT ?", arguments: [data])
|
||||
while let row = try rows.next() {
|
||||
let blobPointer = sqlite3_column_blob(row.sqliteStatement, 0)
|
||||
// This data should not be copied
|
||||
let nonCopiedData = row.dataNoCopy(atIndex: 0)!
|
||||
XCTAssertEqual(nonCopiedData, data)
|
||||
nonCopiedData.withUnsafeBytes {
|
||||
XCTAssertEqual($0.baseAddress, blobPointer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let adapter = ScopeAdapter(["nested": SuffixRowAdapter(fromIndex: 0)])
|
||||
let rows = try Row.fetchCursor(db, sql: "SELECT ?", arguments: [data], adapter: adapter)
|
||||
while let row = try rows.next() {
|
||||
let blobPointer = sqlite3_column_blob(row.unadapted.sqliteStatement, 0)
|
||||
let nestedRow = row.scopes["nested"]!
|
||||
// This data should not be copied
|
||||
let nonCopiedData = nestedRow.dataNoCopy(atIndex: 0)!
|
||||
XCTAssertEqual(nonCopiedData, data)
|
||||
nonCopiedData.withUnsafeBytes {
|
||||
XCTAssertEqual($0.baseAddress, blobPointer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let row = try Row.fetchOne(db, sql: "SELECT ?", arguments: [data])!
|
||||
let dbValue = row.first!.1 // TODO: think about exposing a (column:,databaseValue:) tuple
|
||||
switch dbValue.storage {
|
||||
case .blob(let data):
|
||||
data.withUnsafeBytes { buffer in
|
||||
// This data should not be copied:
|
||||
let nonCopiedData = row.dataNoCopy(atIndex: 0)!
|
||||
XCTAssertEqual(nonCopiedData, data)
|
||||
nonCopiedData.withUnsafeBytes { nonCopiedBuffer in
|
||||
XCTAssertEqual(nonCopiedBuffer.baseAddress, buffer.baseAddress)
|
||||
}
|
||||
}
|
||||
default:
|
||||
|
||||
@@ -210,101 +210,104 @@ class DatabaseConfigurationTests: GRDBTestCase {
|
||||
_ = group.wait(timeout: .distantFuture)
|
||||
}
|
||||
|
||||
// TODO: fix flaky test
|
||||
// func testBusyModeTimeoutTooShort() throws {
|
||||
// let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
// #if GRDBCIPHER_USE_ENCRYPTION
|
||||
// // Work around SQLCipher bug when two connections are open to the
|
||||
// // same empty database: make sure the database is not empty before
|
||||
// // running this test
|
||||
// try dbQueue1.inDatabase { db in
|
||||
// try db.execute(sql: "CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
|
||||
// }
|
||||
// #endif
|
||||
//
|
||||
// var configuration2 = dbQueue1.configuration
|
||||
// configuration2.busyMode = .timeout(0.1)
|
||||
// let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite", configuration: configuration2)
|
||||
//
|
||||
// let s1 = DispatchSemaphore(value: 0)
|
||||
// let s2 = DispatchSemaphore(value: 0)
|
||||
// let queue = DispatchQueue.global(priority: .default)
|
||||
// let group = DispatchGroup()
|
||||
//
|
||||
// queue.async(group: group) {
|
||||
// do {
|
||||
// try dbQueue1.inTransaction(.exclusive) { db in
|
||||
// s2.signal()
|
||||
// queue.asyncAfter(deadline: .now() + 1) {
|
||||
// s1.signal()
|
||||
// }
|
||||
// _ = s1.wait(timeout: .distantFuture)
|
||||
// return .commit
|
||||
// }
|
||||
// } catch {
|
||||
// XCTFail("\(error)")
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// queue.async(group: group) {
|
||||
// do {
|
||||
// _ = s2.wait(timeout: .distantFuture)
|
||||
// try dbQueue2.inTransaction(.exclusive) { db in return .commit }
|
||||
// XCTFail("Expected error")
|
||||
// } catch DatabaseError.SQLITE_BUSY {
|
||||
// } catch {
|
||||
// XCTFail("\(error)")
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// _ = group.wait(timeout: .distantFuture)
|
||||
// }
|
||||
func testBusyModeTimeoutTooShort() throws {
|
||||
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
#if GRDBCIPHER_USE_ENCRYPTION
|
||||
// Work around SQLCipher bug when two connections are open to the
|
||||
// same empty database: make sure the database is not empty before
|
||||
// running this test
|
||||
try dbQueue1.inDatabase { db in
|
||||
try db.execute(sql: "CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
|
||||
}
|
||||
#endif
|
||||
|
||||
var configuration2 = dbQueue1.configuration
|
||||
configuration2.busyMode = .timeout(0.1)
|
||||
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite", configuration: configuration2)
|
||||
|
||||
let s1 = DispatchSemaphore(value: 0)
|
||||
let s2 = DispatchSemaphore(value: 0)
|
||||
let queue = DispatchQueue.global(qos: .default)
|
||||
let group = DispatchGroup()
|
||||
|
||||
queue.async(group: group) {
|
||||
do {
|
||||
try dbQueue1.inTransaction(.exclusive) { db in
|
||||
// Let dbQueue2 attempt at opening an exclusive transaction
|
||||
s2.signal()
|
||||
// Wait for dbQueue2 to fail 😈
|
||||
_ = s1.wait(timeout: .distantFuture)
|
||||
return .commit
|
||||
}
|
||||
} catch {
|
||||
XCTFail("\(error)")
|
||||
}
|
||||
}
|
||||
|
||||
queue.async(group: group) {
|
||||
do {
|
||||
// Wait for dbQueue1 to start an exclusive transaction
|
||||
_ = s2.wait(timeout: .distantFuture)
|
||||
try dbQueue2.inTransaction(.exclusive) { db in return .commit }
|
||||
XCTFail("Expected error")
|
||||
} catch DatabaseError.SQLITE_BUSY {
|
||||
} catch {
|
||||
XCTFail("\(error)")
|
||||
}
|
||||
// Let dbQueue1 end its transaction
|
||||
s1.signal()
|
||||
}
|
||||
|
||||
_ = group.wait(timeout: .distantFuture)
|
||||
}
|
||||
|
||||
// TODO: fix flaky test. It fails on Xcode 10.0, tvOS 10.0
|
||||
// func testBusyModeTimeoutTooLong() throws {
|
||||
// let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
// #if GRDBCIPHER_USE_ENCRYPTION
|
||||
// // Work around SQLCipher bug when two connections are open to the
|
||||
// // same empty database: make sure the database is not empty before
|
||||
// // running this test
|
||||
// try dbQueue1.inDatabase { db in
|
||||
// try db.execute(sql: "CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
|
||||
// }
|
||||
// #endif
|
||||
//
|
||||
// var configuration2 = dbQueue1.configuration
|
||||
// configuration2.busyMode = .timeout(1)
|
||||
// let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite", configuration: configuration2)
|
||||
//
|
||||
// let s1 = DispatchSemaphore(value: 0)
|
||||
// let s2 = DispatchSemaphore(value: 0)
|
||||
// let queue = DispatchQueue.global(priority: .default)
|
||||
// let group = DispatchGroup()
|
||||
//
|
||||
// queue.async(group: group) {
|
||||
// do {
|
||||
// try dbQueue1.inTransaction(.exclusive) { db in
|
||||
// s2.signal()
|
||||
// queue.asyncAfter(deadline: .now() + 0.1) {
|
||||
// s1.signal()
|
||||
// }
|
||||
// _ = s1.wait(timeout: .distantFuture)
|
||||
// return .commit
|
||||
// }
|
||||
// } catch {
|
||||
// XCTFail("\(error)")
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// queue.async(group: group) {
|
||||
// do {
|
||||
// _ = s2.wait(timeout: .distantFuture)
|
||||
// try dbQueue2.inTransaction(.exclusive) { db in return .commit }
|
||||
// } catch {
|
||||
// XCTFail("\(error)")
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// _ = group.wait(timeout: .distantFuture)
|
||||
// }
|
||||
func testBusyModeTimeoutTooLong() throws {
|
||||
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
#if GRDBCIPHER_USE_ENCRYPTION
|
||||
// Work around SQLCipher bug when two connections are open to the
|
||||
// same empty database: make sure the database is not empty before
|
||||
// running this test
|
||||
try dbQueue1.inDatabase { db in
|
||||
try db.execute(sql: "CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
|
||||
}
|
||||
#endif
|
||||
|
||||
var configuration2 = dbQueue1.configuration
|
||||
configuration2.busyMode = .timeout(1)
|
||||
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite", configuration: configuration2)
|
||||
|
||||
let s1 = DispatchSemaphore(value: 0)
|
||||
let s2 = DispatchSemaphore(value: 0)
|
||||
let queue = DispatchQueue.global(qos: .default)
|
||||
let group = DispatchGroup()
|
||||
|
||||
queue.async(group: group) {
|
||||
do {
|
||||
try dbQueue1.inTransaction(.exclusive) { db in
|
||||
// Let dbQueue2 attempt at opening an exclusive transaction
|
||||
s2.signal()
|
||||
// Wait for a delay and end dbQueue1 transaction
|
||||
queue.asyncAfter(deadline: .now() + 0.1) {
|
||||
s1.signal()
|
||||
}
|
||||
_ = s1.wait(timeout: .distantFuture)
|
||||
return .commit
|
||||
}
|
||||
} catch {
|
||||
XCTFail("\(error)")
|
||||
}
|
||||
}
|
||||
|
||||
queue.async(group: group) {
|
||||
do {
|
||||
// Wait for dbQueue1 to start an exclusive transaction
|
||||
_ = s2.wait(timeout: .distantFuture)
|
||||
try dbQueue2.inTransaction(.exclusive) { db in return .commit }
|
||||
} catch {
|
||||
XCTFail("\(error)")
|
||||
}
|
||||
}
|
||||
|
||||
_ = group.wait(timeout: .distantFuture)
|
||||
}
|
||||
}
|
||||
@@ -120,83 +120,129 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
|
||||
|
||||
#endif
|
||||
|
||||
// TODO: fix flaky test
|
||||
// func testDatabasePoolReleaseMemoryClosesReaderConnections() throws {
|
||||
// let countQueue = DispatchQueue(label: "GRDB")
|
||||
// var openConnectionCount = 0
|
||||
// var totalOpenConnectionCount = 0
|
||||
//
|
||||
// dbConfiguration.SQLiteConnectionDidOpen = {
|
||||
// countQueue.sync {
|
||||
// totalOpenConnectionCount += 1
|
||||
// openConnectionCount += 1
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// dbConfiguration.SQLiteConnectionDidClose = {
|
||||
// countQueue.sync {
|
||||
// openConnectionCount -= 1
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// let dbPool = try makeDatabasePool()
|
||||
// try dbPool.write { db in
|
||||
// try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
|
||||
// for _ in 0..<2 {
|
||||
// try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // Block 1 Block 2 Block3
|
||||
// // SELECT * FROM items
|
||||
// // step
|
||||
// // >
|
||||
// let s1 = DispatchSemaphore(value: 0)
|
||||
// // SELECT * FROM items
|
||||
// // step
|
||||
// // >
|
||||
// let s2 = DispatchSemaphore(value: 0)
|
||||
// // step step
|
||||
// // >
|
||||
// let s3 = DispatchSemaphore(value: 0)
|
||||
// // end end releaseMemory
|
||||
//
|
||||
// let block1 = { () in
|
||||
// try! dbPool.read { db in
|
||||
// let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items")
|
||||
// XCTAssertTrue(try cursor.next() != nil)
|
||||
// s1.signal()
|
||||
// _ = s2.wait(timeout: .distantFuture)
|
||||
// XCTAssertTrue(try cursor.next() != nil)
|
||||
// s3.signal()
|
||||
// XCTAssertTrue(try cursor.next() == nil)
|
||||
// }
|
||||
// }
|
||||
// let block2 = { () in
|
||||
// _ = s1.wait(timeout: .distantFuture)
|
||||
// try! dbPool.read { db in
|
||||
// let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items")
|
||||
// XCTAssertTrue(try cursor.next() != nil)
|
||||
// s2.signal()
|
||||
// XCTAssertTrue(try cursor.next() != nil)
|
||||
// XCTAssertTrue(try cursor.next() == nil)
|
||||
// }
|
||||
// }
|
||||
// let block3 = { () in
|
||||
// _ = s3.wait(timeout: .distantFuture)
|
||||
// dbPool.releaseMemory()
|
||||
// }
|
||||
// let blocks = [block1, block2, block3]
|
||||
// DispatchQueue.concurrentPerform(iterations: blocks.count) { index in // FIXME: this crashes sometimes
|
||||
// blocks[index]()
|
||||
// }
|
||||
//
|
||||
// // Two readers, one writer
|
||||
// XCTAssertEqual(totalOpenConnectionCount, 3)
|
||||
//
|
||||
// // Writer is still open
|
||||
// XCTAssertEqual(openConnectionCount, 1)
|
||||
// }
|
||||
func test_DatabasePool_releaseMemory_closes_reader_connections() throws {
|
||||
// A complicated test setup that opens multiple reader connections.
|
||||
let countQueue = DispatchQueue(label: "GRDB")
|
||||
var openConnectionCount = 0
|
||||
var totalOpenConnectionCount = 0
|
||||
|
||||
dbConfiguration.SQLiteConnectionDidOpen = {
|
||||
countQueue.sync {
|
||||
totalOpenConnectionCount += 1
|
||||
openConnectionCount += 1
|
||||
}
|
||||
}
|
||||
|
||||
dbConfiguration.SQLiteConnectionDidClose = {
|
||||
countQueue.sync {
|
||||
openConnectionCount -= 1
|
||||
}
|
||||
}
|
||||
|
||||
let dbPool = try makeDatabasePool()
|
||||
try dbPool.write { db in
|
||||
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
|
||||
for _ in 0..<2 {
|
||||
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
|
||||
}
|
||||
}
|
||||
|
||||
// Block 1 Block 2 Block3
|
||||
// SELECT * FROM items
|
||||
// step
|
||||
// >
|
||||
let s1 = DispatchSemaphore(value: 0)
|
||||
// SELECT * FROM items
|
||||
// step
|
||||
// >
|
||||
let s2 = DispatchSemaphore(value: 0)
|
||||
// step step
|
||||
// >
|
||||
let s3 = DispatchSemaphore(value: 0)
|
||||
// end end releaseMemory
|
||||
|
||||
let block1 = { () in
|
||||
try! dbPool.read { db in
|
||||
let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items")
|
||||
XCTAssertTrue(try cursor.next() != nil)
|
||||
s1.signal()
|
||||
_ = s2.wait(timeout: .distantFuture)
|
||||
XCTAssertTrue(try cursor.next() != nil)
|
||||
s3.signal()
|
||||
XCTAssertTrue(try cursor.next() == nil)
|
||||
}
|
||||
}
|
||||
let block2 = { () in
|
||||
_ = s1.wait(timeout: .distantFuture)
|
||||
try! dbPool.read { db in
|
||||
let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items")
|
||||
XCTAssertTrue(try cursor.next() != nil)
|
||||
s2.signal()
|
||||
XCTAssertTrue(try cursor.next() != nil)
|
||||
XCTAssertTrue(try cursor.next() == nil)
|
||||
}
|
||||
}
|
||||
let block3 = { () in
|
||||
_ = s3.wait(timeout: .distantFuture)
|
||||
dbPool.releaseMemory()
|
||||
}
|
||||
let blocks = [block1, block2, block3]
|
||||
DispatchQueue.concurrentPerform(iterations: blocks.count) { index in // FIXME: this crashes sometimes
|
||||
blocks[index]()
|
||||
}
|
||||
|
||||
// Two readers, one writer
|
||||
XCTAssertEqual(totalOpenConnectionCount, 3)
|
||||
|
||||
// Writer is still open
|
||||
XCTAssertEqual(openConnectionCount, 1)
|
||||
}
|
||||
|
||||
func test_DatabasePool_releaseMemory_closes_reader_connections_when_persistentReadOnlyConnections_is_false() throws {
|
||||
var persistentConnectionCount = 0
|
||||
|
||||
dbConfiguration.SQLiteConnectionDidOpen = {
|
||||
persistentConnectionCount += 1
|
||||
}
|
||||
|
||||
dbConfiguration.SQLiteConnectionDidClose = {
|
||||
persistentConnectionCount -= 1
|
||||
}
|
||||
|
||||
dbConfiguration.persistentReadOnlyConnections = false
|
||||
|
||||
let dbPool = try makeDatabasePool()
|
||||
XCTAssertEqual(persistentConnectionCount, 1) // writer
|
||||
|
||||
try dbPool.read { _ in }
|
||||
XCTAssertEqual(persistentConnectionCount, 2) // writer + reader
|
||||
|
||||
dbPool.releaseMemory()
|
||||
XCTAssertEqual(persistentConnectionCount, 1) // writer
|
||||
}
|
||||
|
||||
func test_DatabasePool_releaseMemory_does_not_close_reader_connections_when_persistentReadOnlyConnections_is_true() throws {
|
||||
var persistentConnectionCount = 0
|
||||
|
||||
dbConfiguration.SQLiteConnectionDidOpen = {
|
||||
persistentConnectionCount += 1
|
||||
}
|
||||
|
||||
dbConfiguration.SQLiteConnectionDidClose = {
|
||||
persistentConnectionCount -= 1
|
||||
}
|
||||
|
||||
dbConfiguration.persistentReadOnlyConnections = true
|
||||
|
||||
let dbPool = try makeDatabasePool()
|
||||
XCTAssertEqual(persistentConnectionCount, 1) // writer
|
||||
|
||||
try dbPool.read { _ in }
|
||||
XCTAssertEqual(persistentConnectionCount, 2) // writer + reader
|
||||
|
||||
dbPool.releaseMemory()
|
||||
XCTAssertEqual(persistentConnectionCount, 2) // writer + reader
|
||||
}
|
||||
|
||||
func testBlocksRetainConnection() throws {
|
||||
let countQueue = DispatchQueue(label: "GRDB")
|
||||
|
||||
@@ -543,6 +543,10 @@ class DatabaseRegionTests : GRDBTestCase {
|
||||
XCTAssertEqual(tableName, "foo")
|
||||
XCTAssertEqual(columnNames, Set(["bar", "baz"]))
|
||||
}
|
||||
do {
|
||||
let statement = try db.makeStatement(sql: "UPDATE foo SET bar = 'bar' WHERE baz = 'baz'")
|
||||
XCTAssertEqual(statement.databaseRegion.description, "foo(baz)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -622,4 +622,66 @@ class DatabaseTests : GRDBTestCase {
|
||||
// 999 should be safe: https://www.sqlite.org/limits.html
|
||||
XCTAssertGreaterThanOrEqual(count, 999)
|
||||
}
|
||||
|
||||
func testCache() throws {
|
||||
// See "In-memory Databases And Shared Cache" in https://www.sqlite.org/inmemorydb.html
|
||||
dbConfiguration.prepareDatabase { db in
|
||||
db.trace { print($0)}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.writeWithoutTransaction { db in // transaction prevents DETACH DATABASE from wording
|
||||
var region = DatabaseRegion()
|
||||
try db.recordingSelection(®ion) {
|
||||
try db.withCache(atPath: ":memory:") {
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE player(id INTEGER PRIMARY KEY, name TEXT);
|
||||
CREATE TABLE award(id INTEGER PRIMARY KEY, playerId INTEGER REFERENCES player(id), color TEXT);
|
||||
INSERT INTO player (name) VALUES ('Barbara');
|
||||
INSERT INTO player (name) VALUES ('Zoe');
|
||||
INSERT INTO player (name) VALUES ('Gaston');
|
||||
INSERT INTO player (name) VALUES ('Bernard');
|
||||
INSERT INTO player (name) VALUES ('Henri');
|
||||
INSERT INTO award(playerId, color) VALUES (1, 'Gold');
|
||||
INSERT INTO award(playerId, color) VALUES (1, 'Silver');
|
||||
INSERT INTO award(playerId, color) VALUES (1, 'Gold');
|
||||
INSERT INTO award(playerId, color) VALUES (2, 'Silver');
|
||||
INSERT INTO award(playerId, color) VALUES (3, 'Gold');
|
||||
INSERT INTO award(playerId, color) VALUES (4, 'Silver');
|
||||
""")
|
||||
|
||||
struct Player: TableRecord, FetchableRecord, Decodable {
|
||||
static let awards = hasMany(Award.self)
|
||||
var id: Int64
|
||||
var name: String
|
||||
}
|
||||
struct Award: TableRecord, FetchableRecord, Decodable {
|
||||
var id: Int64
|
||||
var playerId: Int64
|
||||
var color: String
|
||||
}
|
||||
|
||||
do {
|
||||
_ = try Row.fetchAll(db, sql: "SELECT * FROM player ORDER BY name")
|
||||
}
|
||||
do {
|
||||
// Test cache ordering with rowid disambiguation
|
||||
_ = try Row.fetchAll(db, sql: "SELECT rowid AS rowID, * FROM player ORDER BY name")
|
||||
}
|
||||
do {
|
||||
struct PlayerWithAwards: FetchableRecord, Decodable {
|
||||
var player: Player
|
||||
var awards: [Award]
|
||||
}
|
||||
|
||||
_ = try Player
|
||||
.filter(Column("name") != "Gaston")
|
||||
.including(all: Player.awards.filter(Column("color") != "Gold"))
|
||||
.asRequest(of: PlayerWithAwards.self)
|
||||
.fetchAll(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
try print(region.observableRegion(db))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,7 @@ class StatementArgumentsTests: GRDBTestCase {
|
||||
// Missing arguments
|
||||
try statement.validateArguments([])
|
||||
XCTFail("Expected error")
|
||||
} catch is DatabaseError {
|
||||
} catch DatabaseError.SQLITE_MISUSE {
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
}
|
||||
@@ -42,7 +42,7 @@ class StatementArgumentsTests: GRDBTestCase {
|
||||
// Two few arguments
|
||||
try statement.validateArguments(["foo"])
|
||||
XCTFail("Expected error")
|
||||
} catch is DatabaseError {
|
||||
} catch DatabaseError.SQLITE_MISUSE {
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
}
|
||||
@@ -51,7 +51,7 @@ class StatementArgumentsTests: GRDBTestCase {
|
||||
// Two many arguments
|
||||
try statement.validateArguments(["foo", 1, "bar"])
|
||||
XCTFail("Expected error")
|
||||
} catch is DatabaseError {
|
||||
} catch DatabaseError.SQLITE_MISUSE {
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
}
|
||||
@@ -60,7 +60,7 @@ class StatementArgumentsTests: GRDBTestCase {
|
||||
// Missing arguments
|
||||
try statement.validateArguments([:])
|
||||
XCTFail("Expected error")
|
||||
} catch is DatabaseError {
|
||||
} catch DatabaseError.SQLITE_MISUSE {
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
}
|
||||
@@ -69,7 +69,7 @@ class StatementArgumentsTests: GRDBTestCase {
|
||||
// Unmappable arguments
|
||||
try statement.validateArguments(["firstName": "foo", "age": 1])
|
||||
XCTFail("Expected error")
|
||||
} catch is DatabaseError {
|
||||
} catch DatabaseError.SQLITE_MISUSE {
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
}
|
||||
@@ -117,7 +117,7 @@ class StatementArgumentsTests: GRDBTestCase {
|
||||
do {
|
||||
try updateStatement.setArguments([1])
|
||||
XCTFail("Expected error")
|
||||
} catch is DatabaseError {
|
||||
} catch DatabaseError.SQLITE_MISUSE {
|
||||
XCTAssertEqual(updateStatement.arguments, arguments)
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
@@ -126,7 +126,7 @@ class StatementArgumentsTests: GRDBTestCase {
|
||||
do {
|
||||
try selectStatement.setArguments([1])
|
||||
XCTFail("Expected error")
|
||||
} catch is DatabaseError {
|
||||
} catch DatabaseError.SQLITE_MISUSE {
|
||||
XCTAssertEqual(selectStatement.arguments, arguments)
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
@@ -184,7 +184,7 @@ class StatementArgumentsTests: GRDBTestCase {
|
||||
// Missing arguments
|
||||
try statement.validateArguments([])
|
||||
XCTFail("Expected error")
|
||||
} catch is DatabaseError {
|
||||
} catch DatabaseError.SQLITE_MISUSE {
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
}
|
||||
@@ -193,7 +193,7 @@ class StatementArgumentsTests: GRDBTestCase {
|
||||
// Missing arguments
|
||||
try statement.validateArguments(["foo"])
|
||||
XCTFail("Expected error")
|
||||
} catch is DatabaseError {
|
||||
} catch DatabaseError.SQLITE_MISUSE {
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
}
|
||||
@@ -202,7 +202,7 @@ class StatementArgumentsTests: GRDBTestCase {
|
||||
// Too many arguments
|
||||
try statement.validateArguments(["foo", 1, "baz"])
|
||||
XCTFail("Expected error")
|
||||
} catch is DatabaseError {
|
||||
} catch DatabaseError.SQLITE_MISUSE {
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
}
|
||||
@@ -211,7 +211,7 @@ class StatementArgumentsTests: GRDBTestCase {
|
||||
// Missing arguments
|
||||
try statement.validateArguments([:])
|
||||
XCTFail("Expected error")
|
||||
} catch is DatabaseError {
|
||||
} catch DatabaseError.SQLITE_MISUSE {
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
}
|
||||
@@ -220,7 +220,7 @@ class StatementArgumentsTests: GRDBTestCase {
|
||||
// Missing arguments
|
||||
try statement.validateArguments(["firstName": "foo"])
|
||||
XCTFail("Expected error")
|
||||
} catch is DatabaseError {
|
||||
} catch DatabaseError.SQLITE_MISUSE {
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
}
|
||||
@@ -268,7 +268,7 @@ class StatementArgumentsTests: GRDBTestCase {
|
||||
do {
|
||||
try updateStatement.setArguments(["name": name])
|
||||
XCTFail("Expected error")
|
||||
} catch is DatabaseError {
|
||||
} catch DatabaseError.SQLITE_MISUSE {
|
||||
XCTAssertEqual(updateStatement.arguments, arguments)
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
@@ -277,7 +277,7 @@ class StatementArgumentsTests: GRDBTestCase {
|
||||
do {
|
||||
try selectStatement.setArguments(["name": name])
|
||||
XCTFail("Expected error")
|
||||
} catch is DatabaseError {
|
||||
} catch DatabaseError.SQLITE_MISUSE {
|
||||
XCTAssertEqual(selectStatement.arguments, arguments)
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
@@ -343,7 +343,7 @@ class StatementArgumentsTests: GRDBTestCase {
|
||||
// Missing arguments
|
||||
try statement.validateArguments([])
|
||||
XCTFail("Expected error")
|
||||
} catch is DatabaseError {
|
||||
} catch DatabaseError.SQLITE_MISUSE {
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
}
|
||||
@@ -352,7 +352,7 @@ class StatementArgumentsTests: GRDBTestCase {
|
||||
// Missing arguments
|
||||
try statement.validateArguments(["foo"])
|
||||
XCTFail("Expected error")
|
||||
} catch is DatabaseError {
|
||||
} catch DatabaseError.SQLITE_MISUSE {
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
}
|
||||
@@ -361,7 +361,7 @@ class StatementArgumentsTests: GRDBTestCase {
|
||||
// Too many arguments
|
||||
try statement.validateArguments(["foo", 1, "baz"])
|
||||
XCTFail("Expected error")
|
||||
} catch is DatabaseError {
|
||||
} catch DatabaseError.SQLITE_MISUSE {
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
}
|
||||
@@ -370,7 +370,7 @@ class StatementArgumentsTests: GRDBTestCase {
|
||||
// Missing arguments
|
||||
try statement.validateArguments([:])
|
||||
XCTFail("Expected error")
|
||||
} catch is DatabaseError {
|
||||
} catch DatabaseError.SQLITE_MISUSE {
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
}
|
||||
@@ -379,7 +379,7 @@ class StatementArgumentsTests: GRDBTestCase {
|
||||
// Missing arguments
|
||||
try statement.validateArguments(["name": "foo"])
|
||||
XCTFail("Expected error")
|
||||
} catch is DatabaseError {
|
||||
} catch DatabaseError.SQLITE_MISUSE {
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
}
|
||||
@@ -428,7 +428,7 @@ class StatementArgumentsTests: GRDBTestCase {
|
||||
do {
|
||||
try updateStatement.setArguments(["name": name])
|
||||
XCTFail("Expected error")
|
||||
} catch is DatabaseError {
|
||||
} catch DatabaseError.SQLITE_MISUSE {
|
||||
XCTAssertEqual(updateStatement.arguments, arguments)
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
@@ -437,7 +437,7 @@ class StatementArgumentsTests: GRDBTestCase {
|
||||
do {
|
||||
try selectStatement.setArguments(["name": name])
|
||||
XCTFail("Expected error")
|
||||
} catch is DatabaseError {
|
||||
} catch DatabaseError.SQLITE_MISUSE {
|
||||
XCTAssertEqual(selectStatement.arguments, arguments)
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
|
||||
@@ -277,7 +277,8 @@ class TableRecordDeleteTests: GRDBTestCase {
|
||||
|
||||
_ = try Person.filter(keys: [1, 2]).deleteAndFetchCursor(db).next()
|
||||
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (1, 2) RETURNING *")
|
||||
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) {
|
||||
_ = try Person.filter(id: 1).deleteAndFetchCursor(db).next()
|
||||
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" = 1 RETURNING *")
|
||||
@@ -285,7 +286,14 @@ class TableRecordDeleteTests: GRDBTestCase {
|
||||
_ = try Person.filter(ids: [1, 2]).deleteAndFetchCursor(db).next()
|
||||
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (1, 2) RETURNING *")
|
||||
}
|
||||
|
||||
#else
|
||||
_ = try Person.filter(id: 1).deleteAndFetchCursor(db).next()
|
||||
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" = 1 RETURNING *")
|
||||
|
||||
_ = try Person.filter(ids: [1, 2]).deleteAndFetchCursor(db).next()
|
||||
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (1, 2) RETURNING *")
|
||||
#endif
|
||||
|
||||
_ = try Person.filter(sql: "id = 1").deleteAndFetchCursor(db).next()
|
||||
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE id = 1 RETURNING *")
|
||||
|
||||
|
||||
@@ -441,4 +441,155 @@ class UpdateStatementTests : GRDBTestCase {
|
||||
XCTAssertEqual(value, 3)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLITE_STATIC vs SQLITE_TRANSIENT
|
||||
|
||||
func test_SQLITE_STATIC_then_SQLITE_TRANSIENT() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE t(a);
|
||||
""")
|
||||
|
||||
func test(value: some DatabaseValueConvertible) throws {
|
||||
defer { try! db.execute(sql: "DELETE FROM t") }
|
||||
|
||||
// Execute with temporary bindings (SQLITE_STATIC)
|
||||
let statement = try db.makeStatement(sql: "INSERT INTO t VALUES (?)")
|
||||
try statement.execute(arguments: [value])
|
||||
|
||||
// Execute with non temporary bindings (SQLITE_TRANSIENT)
|
||||
try statement.execute()
|
||||
|
||||
// Since bindings are not temporary, they are not cleared,
|
||||
// so insert the value again.
|
||||
sqlite3_reset(statement.sqliteStatement)
|
||||
sqlite3_step(statement.sqliteStatement)
|
||||
sqlite3_reset(statement.sqliteStatement)
|
||||
|
||||
// Test that we have inserted the value thrice.
|
||||
try XCTAssertEqual(
|
||||
DatabaseValue.fetchSet(db, sql: "SELECT a FROM t"),
|
||||
[value.databaseValue])
|
||||
}
|
||||
|
||||
try test(value: "Foo")
|
||||
try test(value: "")
|
||||
try test(value: "Hello".data(using: .utf8)!)
|
||||
try test(value: Data())
|
||||
try test(value: 42)
|
||||
try test(value: 1.23)
|
||||
}
|
||||
}
|
||||
|
||||
func test_SQLITE_STATIC() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE t(a);
|
||||
""")
|
||||
|
||||
func test(value: some DatabaseValueConvertible) throws {
|
||||
defer { try! db.execute(sql: "DELETE FROM t") }
|
||||
|
||||
// Execute with temporary bindings (SQLITE_STATIC)
|
||||
let statement = try db.makeStatement(sql: "INSERT INTO t VALUES (?)")
|
||||
try statement.execute(arguments: [value])
|
||||
|
||||
// Since bindings were temporary, and cleared, we now insert NULL
|
||||
sqlite3_reset(statement.sqliteStatement)
|
||||
sqlite3_step(statement.sqliteStatement)
|
||||
sqlite3_reset(statement.sqliteStatement)
|
||||
|
||||
// Test that we have inserted the value, and NULL
|
||||
try XCTAssertEqual(
|
||||
DatabaseValue.fetchSet(db, sql: "SELECT a FROM t"),
|
||||
[value.databaseValue, .null])
|
||||
}
|
||||
|
||||
try test(value: "Foo")
|
||||
try test(value: "")
|
||||
try test(value: "Hello".data(using: .utf8)!)
|
||||
try test(value: Data())
|
||||
try test(value: 42)
|
||||
try test(value: 1.23)
|
||||
}
|
||||
}
|
||||
|
||||
func test_SQLITE_TRANSIENT_due_to_high_number_of_arguments() throws {
|
||||
// SQLITE_STATIC optimization is disabled for more than 20 arguments.
|
||||
let argumentCount = 21
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
// "a0, a1, a2, ..."
|
||||
let columns = (0..<argumentCount).map { "a\($0)" }.joined(separator: ",")
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE t(\(columns));
|
||||
""")
|
||||
|
||||
func test(value: some DatabaseValueConvertible) throws {
|
||||
defer { try! db.execute(sql: "DELETE FROM t") }
|
||||
|
||||
// Execute with non temporary bindings (SQLITE_TRANSIENT),
|
||||
// because there are more than 20 arguments
|
||||
let statement = try db.makeStatement(sql: "INSERT INTO t VALUES (\(databaseQuestionMarks(count: argumentCount)))")
|
||||
try statement.execute(arguments: StatementArguments(Array(repeating: value, count: argumentCount)))
|
||||
|
||||
// Since bindings are not temporary, they are not cleared,
|
||||
// so insert the value again.
|
||||
sqlite3_reset(statement.sqliteStatement)
|
||||
sqlite3_step(statement.sqliteStatement)
|
||||
sqlite3_reset(statement.sqliteStatement)
|
||||
|
||||
// Test that we have inserted the value twice.
|
||||
try XCTAssertEqual(
|
||||
DatabaseValue.fetchSet(db, sql: "SELECT a0 FROM t"),
|
||||
[value.databaseValue])
|
||||
}
|
||||
|
||||
try test(value: "Foo")
|
||||
try test(value: "")
|
||||
try test(value: "Hello".data(using: .utf8)!)
|
||||
try test(value: Data())
|
||||
try test(value: 42)
|
||||
try test(value: 1.23)
|
||||
}
|
||||
}
|
||||
|
||||
func test_SQLITE_TRANSIENT() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE t(a);
|
||||
""")
|
||||
|
||||
func test(value: some DatabaseValueConvertible) throws {
|
||||
defer { try! db.execute(sql: "DELETE FROM t") }
|
||||
|
||||
// Execute with non temporary bindings (SQLITE_TRANSIENT)
|
||||
let statement = try db.makeStatement(sql: "INSERT INTO t VALUES (?)")
|
||||
try statement.setArguments([value])
|
||||
try statement.execute()
|
||||
|
||||
// Since bindings are not temporary, they are not cleared,
|
||||
// so insert the value again.
|
||||
sqlite3_reset(statement.sqliteStatement)
|
||||
sqlite3_step(statement.sqliteStatement)
|
||||
sqlite3_reset(statement.sqliteStatement)
|
||||
|
||||
// Test that we have inserted the value twice.
|
||||
try XCTAssertEqual(
|
||||
DatabaseValue.fetchSet(db, sql: "SELECT a FROM t"),
|
||||
[value.databaseValue])
|
||||
}
|
||||
|
||||
try test(value: "Foo")
|
||||
try test(value: "")
|
||||
try test(value: "Hello".data(using: .utf8)!)
|
||||
try test(value: Data())
|
||||
try test(value: 42)
|
||||
try test(value: 1.23)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -412,8 +412,8 @@ class ValueObservationTests: GRDBTestCase {
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
|
||||
try! dbPool.write { db in
|
||||
try db.execute(sql: """
|
||||
INSERT INTO t DEFAULT VALUES;
|
||||
""")
|
||||
INSERT INTO t DEFAULT VALUES;
|
||||
""")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
|
||||
class ArgumentsTests: XCTestCase {
|
||||
static let shortString = "foo"
|
||||
static let longString = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus consectetur felis eget nibh aliquet ullamcorper. Nam sodales, tellus a cursus tincidunt, arcu purus suscipit elit, nec congue erat ipsum a purus."
|
||||
|
||||
var dbDirectoryPath: String!
|
||||
var dbQueue: DatabaseQueue!
|
||||
|
||||
override func setUpWithError() throws {
|
||||
let dbDirectoryName = "ArgumentsTests-\(ProcessInfo.processInfo.globallyUniqueString)"
|
||||
dbDirectoryPath = (NSTemporaryDirectory() as NSString).appendingPathComponent(dbDirectoryName)
|
||||
try FileManager.default.createDirectory(atPath: dbDirectoryPath, withIntermediateDirectories: true)
|
||||
let dbPath = (dbDirectoryPath as NSString).appendingPathComponent("db.sqlite")
|
||||
dbQueue = try DatabaseQueue(path: dbPath)
|
||||
}
|
||||
|
||||
override func tearDownWithError() throws {
|
||||
dbQueue = nil
|
||||
try FileManager.default.removeItem(atPath: dbDirectoryPath)
|
||||
}
|
||||
|
||||
func test_shortString_legacy_performance_() throws {
|
||||
try dbQueue.write { db in
|
||||
try db.execute(sql: "CREATE TABLE t(a)")
|
||||
|
||||
let statement = try db.makeStatement(sql: "INSERT INTO t(a) VALUES (?)")
|
||||
let arguments: StatementArguments = [Self.shortString]
|
||||
measure {
|
||||
for _ in 0..<1_000_000 {
|
||||
// Simulate old implementation of statement.execute(arguments: arguments)
|
||||
try! statement.setArguments(arguments)
|
||||
try! statement.execute()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_shortString_SQLITE_STATIC_performance() throws {
|
||||
try dbQueue.write { db in
|
||||
try db.execute(sql: "CREATE TABLE t(a)")
|
||||
|
||||
let statement = try db.makeStatement(sql: "INSERT INTO t(a) VALUES (?)")
|
||||
let arguments: StatementArguments = [Self.shortString]
|
||||
measure {
|
||||
for _ in 0..<1_000_000 {
|
||||
try! statement.execute(arguments: arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_shortString_SQLITE_TRANSIENT_performance() throws {
|
||||
try dbQueue.write { db in
|
||||
try db.execute(sql: "CREATE TABLE t(a)")
|
||||
|
||||
let statement = try db.makeStatement(sql: "INSERT INTO t(a) VALUES (?)")
|
||||
let arguments: StatementArguments = [Self.shortString]
|
||||
try statement.setArguments(arguments)
|
||||
measure {
|
||||
for _ in 0..<1_000_000 {
|
||||
try! statement.execute()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_longString_legacy_performance_() throws {
|
||||
try dbQueue.write { db in
|
||||
try db.execute(sql: "CREATE TABLE t(a)")
|
||||
|
||||
let statement = try db.makeStatement(sql: "INSERT INTO t(a) VALUES (?)")
|
||||
let arguments: StatementArguments = [Self.longString]
|
||||
measure {
|
||||
for _ in 0..<1_000_000 {
|
||||
// Simulate old implementation of statement.execute(arguments: arguments)
|
||||
try! statement.setArguments(arguments)
|
||||
try! statement.execute()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_longString_SQLITE_STATIC_performance() throws {
|
||||
try dbQueue.write { db in
|
||||
try db.execute(sql: "CREATE TABLE t(a)")
|
||||
|
||||
let statement = try db.makeStatement(sql: "INSERT INTO t(a) VALUES (?)")
|
||||
let arguments: StatementArguments = [Self.longString]
|
||||
measure {
|
||||
for _ in 0..<1_000_000 {
|
||||
try! statement.execute(arguments: arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_longString_SQLITE_TRANSIENT_performance() throws {
|
||||
try dbQueue.write { db in
|
||||
try db.execute(sql: "CREATE TABLE t(a)")
|
||||
|
||||
let statement = try db.makeStatement(sql: "INSERT INTO t(a) VALUES (?)")
|
||||
let arguments: StatementArguments = [Self.longString]
|
||||
try! statement.setArguments(arguments)
|
||||
measure {
|
||||
for _ in 0..<1_000_000 {
|
||||
try! statement.execute()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,7 @@
|
||||
5690AFDC212058CB001530EA /* FetchRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFDA212058CB001530EA /* FetchRecordDecodableTests.swift */; };
|
||||
56A3FEA827A85F4800B0292E /* Realm in Frameworks */ = {isa = PBXBuildFile; productRef = 56A3FEA727A85F4800B0292E /* Realm */; };
|
||||
56A3FEAA27A85F4800B0292E /* RealmSwift in Frameworks */ = {isa = PBXBuildFile; productRef = 56A3FEA927A85F4800B0292E /* RealmSwift */; };
|
||||
56A6F4AC29BBC8E200E22662 /* ArgumentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A6F4AB29BBC8E200E22662 /* ArgumentsTests.swift */; };
|
||||
56B6D0E52618BF78003CC455 /* FetchRecordOptimizedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D0E42618BF78003CC455 /* FetchRecordOptimizedTests.swift */; };
|
||||
56B6D0E62618BF78003CC455 /* FetchRecordOptimizedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D0E42618BF78003CC455 /* FetchRecordOptimizedTests.swift */; };
|
||||
56B6D0EA2618C00C003CC455 /* InsertRecordOptimizedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D0E92618C00C003CC455 /* InsertRecordOptimizedTests.swift */; };
|
||||
@@ -97,6 +98,7 @@
|
||||
567986AD23A378CD0076902D /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = "<group>"; };
|
||||
5690AFD72120589A001530EA /* InsertRecordEncodableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InsertRecordEncodableTests.swift; sourceTree = "<group>"; };
|
||||
5690AFDA212058CB001530EA /* FetchRecordDecodableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRecordDecodableTests.swift; sourceTree = "<group>"; };
|
||||
56A6F4AB29BBC8E200E22662 /* ArgumentsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArgumentsTests.swift; sourceTree = "<group>"; };
|
||||
56B6D0E42618BF78003CC455 /* FetchRecordOptimizedTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRecordOptimizedTests.swift; sourceTree = "<group>"; };
|
||||
56B6D0E92618C00C003CC455 /* InsertRecordOptimizedTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InsertRecordOptimizedTests.swift; sourceTree = "<group>"; };
|
||||
56BB86121BA9886D001F9168 /* InsertRecordClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InsertRecordClassTests.swift; sourceTree = "<group>"; };
|
||||
@@ -143,7 +145,7 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567986B923A378CD0076902D /* GRDB.framework */,
|
||||
567986BB23A378CD0076902D /* GRDBOSXTests.xctest */,
|
||||
567986BB23A378CD0076902D /* GRDBTests.xctest */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
@@ -160,6 +162,7 @@
|
||||
children = (
|
||||
56BB862D1BA98933001F9168 /* GRDBPerformanceComparisonTests-Bridging.h */,
|
||||
56DE7B2D1C42B23B00861EB8 /* PerformanceModel.xcdatamodeld */,
|
||||
56A6F4AB29BBC8E200E22662 /* ArgumentsTests.swift */,
|
||||
567071FA208A509C006AD95A /* DateParsingTests.swift */,
|
||||
56DE7B271C41302500861EB8 /* FetchNamedValuesTests.swift */,
|
||||
56DE7B291C4130AF00861EB8 /* FetchPositionalValuesTests.swift */,
|
||||
@@ -307,7 +310,7 @@
|
||||
remoteRef = 567986B823A378CD0076902D /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
567986BB23A378CD0076902D /* GRDBOSXTests.xctest */ = {
|
||||
567986BB23A378CD0076902D /* GRDBTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBTests.xctest;
|
||||
@@ -346,6 +349,7 @@
|
||||
56DE7B281C41302500861EB8 /* FetchNamedValuesTests.swift in Sources */,
|
||||
5690AFD82120589A001530EA /* InsertRecordEncodableTests.swift in Sources */,
|
||||
56B6D0EA2618C00C003CC455 /* InsertRecordOptimizedTests.swift in Sources */,
|
||||
56A6F4AC29BBC8E200E22662 /* ArgumentsTests.swift in Sources */,
|
||||
5690AFDB212058CB001530EA /* FetchRecordDecodableTests.swift in Sources */,
|
||||
56D507831F6D7B2E00AE1C5B /* InsertRecordStructTests.swift in Sources */,
|
||||
56DE7B241C412F7E00861EB8 /* InsertPositionalValuesTests.swift in Sources */,
|
||||
|
||||
+7
-7
@@ -12,10 +12,10 @@
|
||||
{
|
||||
"identity" : "realm-core",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/realm/realm-core",
|
||||
"location" : "https://github.com/realm/realm-core.git",
|
||||
"state" : {
|
||||
"revision" : "3c4b86da569368c4ee5ccca2a112d511cc6fa936",
|
||||
"version" : "12.11.0"
|
||||
"revision" : "dd91f5f967c4ae89c37e24ab2a0315c31106648f",
|
||||
"version" : "13.6.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -23,8 +23,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/realm/realm-swift.git",
|
||||
"state" : {
|
||||
"revision" : "dc1672b3011eb992ce95db4feec83cd897626a16",
|
||||
"version" : "10.32.1"
|
||||
"revision" : "8ac6fe1aa5d0fb0100062d80863416a4d70de8ca",
|
||||
"version" : "10.37.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -32,8 +32,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/stephencelis/SQLite.swift.git",
|
||||
"state" : {
|
||||
"revision" : "4d543d811ee644fa4cc4bfa0be996b4dd6ba0f54",
|
||||
"version" : "0.13.3"
|
||||
"revision" : "7a2e3cd27de56f6d396e84f63beefd0267b55ccb",
|
||||
"version" : "0.14.1"
|
||||
}
|
||||
}
|
||||
],
|
||||
|
||||
@@ -40,7 +40,7 @@ BUILD_ROOT = $1
|
||||
|
||||
# DERIVED_DATA
|
||||
tmp = BUILD_ROOT
|
||||
while !File.exists?(File.join(tmp, 'SourcePackages'))
|
||||
while !File.exist?(File.join(tmp, 'SourcePackages'))
|
||||
parent = File.dirname(tmp)
|
||||
exit 1 if tmp == parent
|
||||
tmp = parent
|
||||
|
||||
Reference in new issue
Block a user