mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-02 04:48:44 +00:00
Compare commits
45
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
36e30a6f1e | ||
|
|
368514c33b | ||
|
|
21b1322e05 | ||
|
|
819f4572df | ||
|
|
7b01c9b72b | ||
|
|
7f9d1503a0 | ||
|
|
14567635e4 | ||
|
|
205387d2d2 | ||
|
|
c8f0328413 | ||
|
|
e784b10314 | ||
|
|
34fa177a47 | ||
|
|
67ebcb325c | ||
|
|
a3036feb48 | ||
|
|
14d4c842e4 | ||
|
|
79276d7f68 | ||
|
|
14fdba1ef3 | ||
|
|
8b5017714f | ||
|
|
a1a9c3aefe | ||
|
|
d664db9610 | ||
|
|
2c4492a098 | ||
|
|
c0ef0e0f99 | ||
|
|
81a699cae9 | ||
|
|
bd954c6791 | ||
|
|
2f94eb307a | ||
|
|
51083da42d | ||
|
|
c229891b6d | ||
|
|
c24bf5d118 | ||
|
|
ccfe3149d7 | ||
|
|
ce71d6c19f | ||
|
|
129e53d54e | ||
|
|
bc5dd31366 | ||
|
|
aa0079aeb8 | ||
|
|
74ef238376 | ||
|
|
9d7a487971 | ||
|
|
ac2f2e8643 | ||
|
|
e281149a2d | ||
|
|
3ee256e7e8 | ||
|
|
361599aacd | ||
|
|
64a024097d | ||
|
|
60ea10948b | ||
|
|
5dba64d545 | ||
|
|
2212a17950 | ||
|
|
24fa06d646 | ||
|
|
fd788900b6 | ||
|
|
b31be05ee3 |
No files matched your search
+44
-1
@@ -7,6 +7,8 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 7.x Releases
|
||||
|
||||
- `7.10.x` Releases - [7.10.0](#7100)
|
||||
- `7.9.x` Releases - [7.9.0](#790)
|
||||
- `7.8.x` Releases - [7.8.0](#780)
|
||||
- `7.7.x` Releases - [7.7.0](#770) - [7.7.1](#771)
|
||||
- `7.6.x` Releases - [7.6.0](#760) - [7.6.1](#761)
|
||||
@@ -140,6 +142,47 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 7.10.0
|
||||
|
||||
Released February 15, 2025
|
||||
|
||||
- **Documentation fixes** by [@bellebethcooper](https://github.com/bellebethcooper), [@Cykelero](https://github.com/Cykelero), and [@leejungyeob](https://github.com/leejungyeob) in [#1842](https://github.com/groue/GRDB.swift/pull/1842), [#1846](https://github.com/groue/GRDB.swift/pull/1846), [#1848](https://github.com/groue/GRDB.swift/pull/1848)
|
||||
- **New**: Linux adjustments by [@thinkpractice](https://github.com/thinkpractice) in [#1825](https://github.com/groue/GRDB.swift/pull/1825)
|
||||
- **New**: SQLCipher adjustments by [@R4N](https://github.com/R4N) in [#1845](https://github.com/groue/GRDB.swift/pull/1845)
|
||||
- **New**: Android and Windows adjustments by [@marcprux](https://github.com/marcprux) in [#1849](https://github.com/groue/GRDB.swift/pull/1849), [#1850](https://github.com/groue/GRDB.swift/pull/1850)
|
||||
- **New**: Configure whether UPSERT should update all columns, or no column by [@groue](https://github.com/groue) in [#1852](https://github.com/groue/GRDB.swift/pull/1852)
|
||||
|
||||
## 7.9.0
|
||||
|
||||
Released December 13, 2025
|
||||
|
||||
- **Breaking Change**: Simplify the compiler checks for the availability of SQLite snapshots by [@groue](https://github.com/groue) in [#1826](https://github.com/groue/GRDB.swift/pull/1826)
|
||||
|
||||
This change aims at easing Linux and Android compatibility.
|
||||
|
||||
**The library requirements are raised to Swift 6.1+, Xcode 16.3+.**
|
||||
|
||||
- **Breaking Change**: Accept multiple SQLCipher libraries by [@groue](https://github.com/groue) in [#1819](https://github.com/groue/GRDB.swift/pull/1819)
|
||||
|
||||
This change aims at easing building GRDB against various SQLCipher flavors.
|
||||
|
||||
**The compiler flag that enables new GRDB APIs for SQLCipher is now `SQLITE_HAS_CODEC`.**
|
||||
|
||||
- **Fixed**: Fix cancellation of async tasks that use the FTS5 full-text engine by [@groue](https://github.com/groue) in [#1839](https://github.com/groue/GRDB.swift/pull/1839)
|
||||
|
||||
This workarounds an [SQLite bug](https://sqlite.org/forum/forumpost/95413eb410) that would trigger a GRDB crash, and improves the robustness of the library regarding database accesses cancellation and database interruption.
|
||||
|
||||
- **New**: Improve the ergonomics of `DatabaseMigrator.registerMigration(_:foreignKeyChecks:merging:migrate)`, introduced in [#1818](https://github.com/groue/GRDB.swift/pull/1818), by accepting that the name of the merged migration is included in the set of merged migrations:
|
||||
|
||||
```swift
|
||||
// Used to fail, now OK:
|
||||
migrator.registerMigration("v3", merging: ["v1", "v2", "v3"]) { ... }
|
||||
// ~~~~ ~~~~
|
||||
|
||||
// The above code is equivalent to:
|
||||
migrator.registerMigration("v3", merging: ["v1", "v2"]) { ... }
|
||||
```
|
||||
|
||||
## 7.8.0
|
||||
|
||||
Released October 2, 2025
|
||||
@@ -4370,7 +4413,7 @@ Released April 3, 2017
|
||||
|
||||
**Breaking Changes**
|
||||
|
||||
- SQLite C API is now available right from the GRBD module: you don't need any longer to import `SQLiteiPhoneOS` module et al (see documentation for [Raw SQLite Pointers](https://github.com/groue/GRDB.swift#raw-sqlite-pointers)).
|
||||
- SQLite C API is now available right from the GRDB module: you don't need any longer to import `SQLiteiPhoneOS` module et al (see documentation for [Raw SQLite Pointers](https://github.com/groue/GRDB.swift#raw-sqlite-pointers)).
|
||||
- The [manual installation procedure for WatchOS extensions](https://github.com/groue/GRDB.swift#installation) has changed.
|
||||
- [Carthage](https://github.com/Carthage/Carthage) is no longer supported. At the present time it is unable to support the various frameworks built by GRDB (system SQLite, SQLCipher, custom SQLite builds, etc.)
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '7.8.0'
|
||||
s.version = '7.10.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -292,6 +292,7 @@
|
||||
56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */; };
|
||||
56BCA2622E6C28F800E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */; };
|
||||
56BF2282241781C5003D86EB /* UtilsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF2281241781C5003D86EB /* UtilsTests.swift */; };
|
||||
56C7979B2EE99BD000AA265D /* Issue1838Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C7979A2EE99BD000AA265D /* Issue1838Tests.swift */; };
|
||||
56CC922C201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */; };
|
||||
56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */; };
|
||||
56CC9246201E058100CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9245201E058000CB597E /* DropFirstCursorTests.swift */; };
|
||||
@@ -802,6 +803,7 @@
|
||||
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSavepointTests.swift; sourceTree = "<group>"; };
|
||||
56C48E731C9A9923005DF1D9 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = module.modulemap; sourceTree = "<group>"; };
|
||||
56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDBDeploymentTarget.xcconfig; sourceTree = "<group>"; };
|
||||
56C7979A2EE99BD000AA265D /* Issue1838Tests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Issue1838Tests.swift; sourceTree = "<group>"; };
|
||||
56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DropWhileCursorTests.swift; sourceTree = "<group>"; };
|
||||
56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = "<group>"; };
|
||||
56CC9245201E058000CB597E /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1448,6 +1450,7 @@
|
||||
56B964C21DA521450002DA19 /* FTS5TableBuilderTests.swift */,
|
||||
5698ACCA1DA62A2D0056AF8C /* FTS5TokenizerTests.swift */,
|
||||
56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */,
|
||||
56C7979A2EE99BD000AA265D /* Issue1838Tests.swift */,
|
||||
);
|
||||
name = FTS;
|
||||
sourceTree = "<group>";
|
||||
@@ -2130,6 +2133,7 @@
|
||||
56D496C11D81373A008276D7 /* DatabaseQueueBackupTests.swift in Sources */,
|
||||
562393721DEE104400A6B01F /* MapCursorTests.swift in Sources */,
|
||||
56D496571D81303E008276D7 /* FoundationDateComponentsTests.swift in Sources */,
|
||||
56C7979B2EE99BD000AA265D /* Issue1838Tests.swift in Sources */,
|
||||
568C3F7A2A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift in Sources */,
|
||||
56D496701D81309E008276D7 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
|
||||
5622060C1E420EB3005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */,
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
#if SQLITE_HAS_CODEC
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else
|
||||
#error("No SQLCipher library configured")
|
||||
#endif
|
||||
import Foundation
|
||||
|
||||
extension Database {
|
||||
|
||||
/// Destination of SQLCipher logs.
|
||||
///
|
||||
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_log>
|
||||
public struct SQLCipherLogTarget: Sendable {
|
||||
public var rawValue: String
|
||||
public init(rawValue: String) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
public static let stdout = Self(rawValue: "stdout")
|
||||
public static let stderr = Self(rawValue: "stderr")
|
||||
public static let device = Self(rawValue: "device")
|
||||
public static func file(_ path: String) -> Self { Self(rawValue: path) }
|
||||
}
|
||||
|
||||
/// Granularitly of SQLCipher log outputs.
|
||||
///
|
||||
/// Each log level is more verbose than the last. With ``debug`` and
|
||||
/// ``trace`` the logging system will generate a significant log volume.
|
||||
///
|
||||
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_log_level>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Log Levels
|
||||
///
|
||||
/// - ``none``
|
||||
/// - ``error``
|
||||
/// - ``warn``
|
||||
/// - ``info``
|
||||
/// - ``debug``
|
||||
/// - ``trace``
|
||||
public struct SQLCipherLogLevel: RawRepresentable, Sendable {
|
||||
public var rawValue: String
|
||||
public init(rawValue: String) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
public static let none = Self(rawValue: "NONE")
|
||||
public static let error = Self(rawValue: "ERROR")
|
||||
public static let warn = Self(rawValue: "WARN")
|
||||
public static let info = Self(rawValue: "INFO")
|
||||
public static let debug = Self(rawValue: "DEBUG")
|
||||
public static let trace = Self(rawValue: "TRACE")
|
||||
}
|
||||
|
||||
/// - Returns: the SQLCipher version
|
||||
///
|
||||
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_version>
|
||||
public var cipherVersion: String {
|
||||
get throws { try String.fetchOne(self, sql: "PRAGMA cipher_version")! }
|
||||
}
|
||||
|
||||
/// - Returns: the SQLCipher fips status: 1 for fips mode, 0 for non-fips mode
|
||||
/// The FIPS status will not be initialized until the database connection has been keyed
|
||||
///
|
||||
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_fips_status>
|
||||
public var cipherFipsStatus: String? {
|
||||
get throws { try String.fetchOne(self, sql: "PRAGMA cipher_fips_status") }
|
||||
}
|
||||
|
||||
/// - Returns: The compiled crypto provider.
|
||||
/// The database must be keyed before requesting the name of the crypto provider.
|
||||
///
|
||||
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_provider>
|
||||
public var cipherProvider: String? {
|
||||
get throws { try String.fetchOne(self, sql: "PRAGMA cipher_provider") }
|
||||
}
|
||||
|
||||
/// - Returns: the version number provided from the compiled crypto provider.
|
||||
/// This value, if known, is available only after the database has been keyed.
|
||||
///
|
||||
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_provider_version>
|
||||
public var cipherProviderVersion: String? {
|
||||
get throws { try String.fetchOne(self, sql: "PRAGMA cipher_provider_version") }
|
||||
}
|
||||
|
||||
/// Sets the passphrase used to crypt and decrypt an SQLCipher database.
|
||||
///
|
||||
/// Call this method from `Configuration.prepareDatabase`,
|
||||
/// as in the example below:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// try db.usePassphrase("secret")
|
||||
/// }
|
||||
public func usePassphrase(_ passphrase: String) throws {
|
||||
guard var data = passphrase.data(using: .utf8) else {
|
||||
throw DatabaseError(message: "invalid passphrase")
|
||||
}
|
||||
defer {
|
||||
data.resetBytes(in: 0..<data.count)
|
||||
}
|
||||
try usePassphrase(data)
|
||||
}
|
||||
|
||||
/// Sets the passphrase used to crypt and decrypt an SQLCipher database.
|
||||
///
|
||||
/// Call this method from `Configuration.prepareDatabase`,
|
||||
/// as in the example below:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// try db.usePassphrase(passphraseData)
|
||||
/// }
|
||||
public func usePassphrase(_ passphrase: Data) throws {
|
||||
let code = passphrase.withUnsafeBytes {
|
||||
sqlite3_key(sqliteConnection, $0.baseAddress, CInt($0.count))
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Changes the passphrase used by an SQLCipher encrypted database.
|
||||
public func changePassphrase(_ passphrase: String) throws {
|
||||
guard var data = passphrase.data(using: .utf8) else {
|
||||
throw DatabaseError(message: "invalid passphrase")
|
||||
}
|
||||
defer {
|
||||
data.resetBytes(in: 0..<data.count)
|
||||
}
|
||||
try changePassphrase(data)
|
||||
}
|
||||
|
||||
/// Changes the passphrase used by an SQLCipher encrypted database.
|
||||
public func changePassphrase(_ passphrase: Data) throws {
|
||||
// FIXME: sqlite3_rekey is discouraged.
|
||||
//
|
||||
// https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320
|
||||
//
|
||||
// > We (Zetetic) have been discouraging the use of sqlite3_rekey in
|
||||
// > favor of attaching a new database with the desired encryption
|
||||
// > options and using sqlcipher_export() to migrate the contents and
|
||||
// > schema of the original db into the new one:
|
||||
// > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/
|
||||
let code = passphrase.withUnsafeBytes {
|
||||
sqlite3_rekey(sqliteConnection, $0.baseAddress, CInt($0.count))
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: lastErrorMessage)
|
||||
}
|
||||
}
|
||||
|
||||
/// When using Commercial or Enterprise SQLCipher packages you must call
|
||||
/// `PRAGMA cipher_license` with a valid license code prior to executing
|
||||
/// cryptographic operations on an encrypted database.
|
||||
/// Failure to provide a license code, or use of an expired trial code,
|
||||
/// will result in an `SQLITE_AUTH (23)` error code reported from the SQLite API
|
||||
/// License Codes will activate SQLCipher Commercial or Enterprise packages
|
||||
/// from Zetetic: <https://www.zetetic.net/sqlcipher/buy/>
|
||||
/// 15-day free trials are available by request: <https://www.zetetic.net/sqlcipher/trial/>
|
||||
///
|
||||
/// Call this method from ``Configuration/prepareDatabase(_:)``,
|
||||
/// as in the example below:
|
||||
///
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// try db.applySQLCipherLicense(license)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_license>
|
||||
/// - Parameter license: base64 SQLCipher license code to activate SQLCipher commercial
|
||||
public func applySQLCipherLicense(_ license: String) throws {
|
||||
try execute(sql: "PRAGMA cipher_license = '\(license)'")
|
||||
}
|
||||
|
||||
/// Instructs SQLCipher to log internal debugging and operational information.
|
||||
///
|
||||
/// The supplied ``logLevel`` determines the granularity of the logs output.
|
||||
///
|
||||
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_log>
|
||||
/// - Parameter logLevel: The granularity to use for the logging system - defaults to `DEBUG`.
|
||||
/// - Parameter target: The destination of SQLCipher logs - defaults to `.device`.
|
||||
public func enableCipherLogging(
|
||||
logLevel: SQLCipherLogLevel = .debug,
|
||||
target: SQLCipherLogTarget = .device
|
||||
) throws {
|
||||
// Pragma do not support SQL arguments. We need to generate SQL that contains literal values:
|
||||
// PRAGMA cipher_log = '/path/to/file'
|
||||
// PRAGMA cipher_log_level = 'xxx'
|
||||
let context = SQLGenerationContext(self, argumentsSink: .literalValues)
|
||||
try execute(sql: SQL("PRAGMA cipher_log = \(target.rawValue)").sql(context))
|
||||
try execute(sql: SQL("PRAGMA cipher_log_level = \(logLevel.rawValue.uppercased())").sql(context))
|
||||
}
|
||||
|
||||
/// Instructs SQLCipher to disable logging internal debugging and operational information.
|
||||
///
|
||||
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_log>
|
||||
public func disableCipherLogging() throws {
|
||||
try execute(sql: "PRAGMA cipher_log_level = NONE")
|
||||
}
|
||||
|
||||
internal func validateSQLCipher() throws {
|
||||
// https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688
|
||||
//
|
||||
// > In order to avoid situations where SQLite might be used
|
||||
// > improperly at runtime, we strongly recommend that
|
||||
// > applications institute a runtime test to ensure that the
|
||||
// > application is actually using SQLCipher on the active
|
||||
// > connection.
|
||||
if try String.fetchOne(self, sql: "PRAGMA cipher_version") == nil {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: """
|
||||
GRDB is not linked against SQLCipher. \
|
||||
Check https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
internal func dropAllDatabaseObjects() throws {
|
||||
// SQLCipher does not support the backup API:
|
||||
// https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631
|
||||
// So we'll drop all database objects one after the other.
|
||||
|
||||
// Prevent foreign keys from messing with drop table statements
|
||||
let foreignKeysEnabled = try Bool.fetchOne(self, sql: "PRAGMA foreign_keys")!
|
||||
if foreignKeysEnabled {
|
||||
try execute(sql: "PRAGMA foreign_keys = OFF")
|
||||
}
|
||||
|
||||
try throwingFirstError(
|
||||
execute: {
|
||||
// Remove all database objects, one after the other
|
||||
try inTransaction {
|
||||
let sql = "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'"
|
||||
while let row = try Row.fetchOne(self, sql: sql) {
|
||||
let type: String = row["type"]
|
||||
let name: String = row["name"]
|
||||
try execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)")
|
||||
}
|
||||
return .commit
|
||||
}
|
||||
},
|
||||
finally: {
|
||||
// Restore foreign keys if needed
|
||||
if foreignKeysEnabled {
|
||||
try execute(sql: "PRAGMA foreign_keys = ON")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
@@ -513,6 +513,27 @@ extension Database {
|
||||
publicStatementArguments: configuration.publicStatementArguments)
|
||||
}
|
||||
|
||||
/// Always throws an error
|
||||
func statementCompilationDidFail(
|
||||
at statementStart: UnsafePointer<CChar>,
|
||||
withResultCode resultCode: CInt
|
||||
) throws -> Never {
|
||||
switch ResultCode(rawValue: resultCode) {
|
||||
case .SQLITE_INTERRUPT, .SQLITE_ABORT:
|
||||
// The only error that a user sees when a Task is cancelled
|
||||
// is CancellationError.
|
||||
try suspensionMutex.load().checkCancellation()
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
// Throw compilation failure
|
||||
throw DatabaseError(
|
||||
resultCode: resultCode,
|
||||
message: lastErrorMessage,
|
||||
sql: String(cString: statementStart))
|
||||
}
|
||||
|
||||
private func checkForAutocommitTransition() {
|
||||
if sqlite3_get_autocommit(sqliteConnection) == 0 {
|
||||
if autocommitState == .on {
|
||||
|
||||
+62
-125
@@ -4,8 +4,9 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
import GRDBSQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
@@ -641,24 +642,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
private func validateSQLCipher() throws {
|
||||
// https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688
|
||||
//
|
||||
// > In order to avoid situations where SQLite might be used
|
||||
// > improperly at runtime, we strongly recommend that
|
||||
// > applications institute a runtime test to ensure that the
|
||||
// > application is actually using SQLCipher on the active
|
||||
// > connection.
|
||||
if try String.fetchOne(self, sql: "PRAGMA cipher_version") == nil {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: """
|
||||
GRDB is not linked against SQLCipher. \
|
||||
Check https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688
|
||||
""")
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
private func validateFormat() throws {
|
||||
// Users are surprised when they open a picture as a database and
|
||||
// see no error (https://github.com/groue/GRDB.swift/issues/54).
|
||||
@@ -863,7 +846,16 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
readOnlyDepth -= 1
|
||||
assert(readOnlyDepth >= 0, "unbalanced endReadOnly()")
|
||||
if readOnlyDepth == 0 {
|
||||
try internalCachedStatement(sql: "PRAGMA query_only = 0").execute()
|
||||
// We MUST ignore interruptions when we leave the read-only mode,
|
||||
// otherwise user could not write with this database
|
||||
// connection again.
|
||||
//
|
||||
// It's OK to ignore interruption, since interruption is
|
||||
// concurrent and we can pretend it occurred before or after
|
||||
// the PRAGMA.
|
||||
try ignoringInterruption {
|
||||
try internalCachedStatement(sql: "PRAGMA query_only = 0").execute()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1300,6 +1292,31 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
return try value()
|
||||
}
|
||||
|
||||
/// Returns the result of `value`. If `value` throws an interruption
|
||||
/// error, it is retried a second time.
|
||||
func ignoringInterruption<T>(_ value: () throws -> T) rethrows -> T {
|
||||
do {
|
||||
return try value() // swiftlint:disable:next statement_position
|
||||
}
|
||||
catch is CancellationError,
|
||||
DatabaseError.SQLITE_INTERRUPT,
|
||||
DatabaseError.SQLITE_ABORT
|
||||
{
|
||||
// Maybe we were unlucky, and user has interrupted the database
|
||||
// during `value` execution.
|
||||
//
|
||||
// Another possible cause for this error is the FTS5 bug
|
||||
// described at <https://sqlite.org/forum/forumpost/137c7662b3>,
|
||||
// which leaves the database in a sticky interrupted state.
|
||||
// To workaround this bug, we must leave the interrupted state
|
||||
// before retrying:
|
||||
resetAllPreparedStatements()
|
||||
|
||||
// Retry
|
||||
return try value()
|
||||
}
|
||||
}
|
||||
|
||||
/// Support for `checkForSuspensionViolation(from:)`
|
||||
private func journalMode() throws -> String {
|
||||
if let journalMode = journalModeCache {
|
||||
@@ -1764,7 +1781,16 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// which rollback errors should be ignored, and which rollback errors
|
||||
// should be exposed to the library user.
|
||||
if isInsideTransaction {
|
||||
try execute(sql: "ROLLBACK TRANSACTION")
|
||||
// We MUST ignore interruptions during the rollback, otherwise
|
||||
// we could leave a transaction open, and trigger a fatal error in
|
||||
// `SerializedDatabase.preconditionNoUnsafeTransactionLeft`.
|
||||
//
|
||||
// It's OK to ignore interruption, since interruption is
|
||||
// concurrent and we can pretend it occurred before or after
|
||||
// the rollback.
|
||||
try ignoringInterruption {
|
||||
try execute(sql: "ROLLBACK TRANSACTION")
|
||||
}
|
||||
}
|
||||
assert(!isInsideTransaction)
|
||||
}
|
||||
@@ -1779,6 +1805,19 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
|
||||
}
|
||||
|
||||
/// Resets all prepared statements.
|
||||
///
|
||||
/// This method helps clearing the interrupted state, as a workaround
|
||||
/// for https://sqlite.org/forum/forumpost/137c7662b3, discovered
|
||||
/// in https://github.com/groue/GRDB.swift/issues/1838.
|
||||
func resetAllPreparedStatements() {
|
||||
var stmt: SQLiteStatement? = sqlite3_next_stmt(sqliteConnection, nil)
|
||||
while stmt != nil {
|
||||
sqlite3_reset(stmt)
|
||||
stmt = sqlite3_next_stmt(sqliteConnection, stmt)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Memory Management
|
||||
|
||||
/// Frees as much memory as possible.
|
||||
@@ -1796,35 +1835,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
func erase() throws {
|
||||
#if SQLITE_HAS_CODEC
|
||||
// SQLCipher does not support the backup API:
|
||||
// https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631
|
||||
// So we'll drop all database objects one after the other.
|
||||
|
||||
// Prevent foreign keys from messing with drop table statements
|
||||
let foreignKeysEnabled = try Bool.fetchOne(self, sql: "PRAGMA foreign_keys")!
|
||||
if foreignKeysEnabled {
|
||||
try execute(sql: "PRAGMA foreign_keys = OFF")
|
||||
}
|
||||
|
||||
try throwingFirstError(
|
||||
execute: {
|
||||
// Remove all database objects, one after the other
|
||||
try inTransaction {
|
||||
let sql = "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'"
|
||||
while let row = try Row.fetchOne(self, sql: sql) {
|
||||
let type: String = row["type"]
|
||||
let name: String = row["name"]
|
||||
try execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)")
|
||||
}
|
||||
return .commit
|
||||
}
|
||||
},
|
||||
finally: {
|
||||
// Restore foreign keys if needed
|
||||
if foreignKeysEnabled {
|
||||
try execute(sql: "PRAGMA foreign_keys = ON")
|
||||
}
|
||||
})
|
||||
try dropAllDatabaseObjects()
|
||||
#else
|
||||
try DatabaseQueue().backup(to: self)
|
||||
#endif
|
||||
@@ -1947,80 +1958,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
@available(*, unavailable)
|
||||
extension Database: Sendable { }
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
extension Database {
|
||||
|
||||
// MARK: - Encryption
|
||||
|
||||
/// Sets the passphrase used to crypt and decrypt an SQLCipher database.
|
||||
///
|
||||
/// Call this method from `Configuration.prepareDatabase`,
|
||||
/// as in the example below:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// try db.usePassphrase("secret")
|
||||
/// }
|
||||
public func usePassphrase(_ passphrase: String) throws {
|
||||
guard var data = passphrase.data(using: .utf8) else {
|
||||
throw DatabaseError(message: "invalid passphrase")
|
||||
}
|
||||
defer {
|
||||
data.resetBytes(in: 0..<data.count)
|
||||
}
|
||||
try usePassphrase(data)
|
||||
}
|
||||
|
||||
/// Sets the passphrase used to crypt and decrypt an SQLCipher database.
|
||||
///
|
||||
/// Call this method from `Configuration.prepareDatabase`,
|
||||
/// as in the example below:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// try db.usePassphrase(passphraseData)
|
||||
/// }
|
||||
public func usePassphrase(_ passphrase: Data) throws {
|
||||
let code = passphrase.withUnsafeBytes {
|
||||
sqlite3_key(sqliteConnection, $0.baseAddress, CInt($0.count))
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Changes the passphrase used by an SQLCipher encrypted database.
|
||||
public func changePassphrase(_ passphrase: String) throws {
|
||||
guard var data = passphrase.data(using: .utf8) else {
|
||||
throw DatabaseError(message: "invalid passphrase")
|
||||
}
|
||||
defer {
|
||||
data.resetBytes(in: 0..<data.count)
|
||||
}
|
||||
try changePassphrase(data)
|
||||
}
|
||||
|
||||
/// Changes the passphrase used by an SQLCipher encrypted database.
|
||||
public func changePassphrase(_ passphrase: Data) throws {
|
||||
// FIXME: sqlite3_rekey is discouraged.
|
||||
//
|
||||
// https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320
|
||||
//
|
||||
// > We (Zetetic) have been discouraging the use of sqlite3_rekey in
|
||||
// > favor of attaching a new database with the desired encryption
|
||||
// > options and using sqlcipher_export() to migrate the contents and
|
||||
// > schema of the original db into the new one:
|
||||
// > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/
|
||||
let code = passphrase.withUnsafeBytes {
|
||||
sqlite3_rekey(sqliteConnection, $0.baseAddress, CInt($0.count))
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: lastErrorMessage)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
extension Database {
|
||||
/// Returns the count of changes executed by one statement execution.
|
||||
func countChanges<T>(_ count: inout Int, forTable tableName: String, updates: () throws -> T) throws -> T {
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -5,8 +5,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
@@ -140,7 +140,7 @@ public final class DatabaseSnapshotPool {
|
||||
let walSnapshot = try db.isolated(readOnly: true) {
|
||||
try WALSnapshot(db)
|
||||
}
|
||||
var holderConfig = Configuration()
|
||||
var holderConfig = configuration
|
||||
holderConfig.allowsUnsafeTransactions = true
|
||||
snapshotHolder = try DatabaseQueue(path: path, configuration: holderConfig)
|
||||
try snapshotHolder.inDatabase { db in
|
||||
@@ -199,7 +199,7 @@ public final class DatabaseSnapshotPool {
|
||||
var configuration = Self.configure(configuration)
|
||||
|
||||
// Acquire and hold WAL snapshot
|
||||
var holderConfig = Configuration()
|
||||
var holderConfig = configuration
|
||||
holderConfig.allowsUnsafeTransactions = true
|
||||
snapshotHolder = try DatabaseQueue(path: path, configuration: holderConfig)
|
||||
let walSnapshot = try snapshotHolder.inDatabase { db in
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -48,6 +48,6 @@ private final class DispatchQueueExecutor: SerialExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
#if os(Linux)
|
||||
#if os(Linux) || os(Android) || os(Windows)
|
||||
extension DispatchQueueExecutor: @unchecked Sendable {}
|
||||
#endif
|
||||
+2
-2
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
@@ -60,7 +60,7 @@ public final class Statement {
|
||||
|
||||
/// The column names, ordered from left to right.
|
||||
public lazy var columnNames: [String] = {
|
||||
// swiftlint:disable:next redundant_self_in_closure
|
||||
// swiftlint:disable:next redundant_self
|
||||
let sqliteStatement = self.sqliteStatement
|
||||
return (0..<CInt(columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
|
||||
}()
|
||||
@@ -150,10 +150,7 @@ public final class Statement {
|
||||
&sqliteStatement, statementEnd)
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(
|
||||
resultCode: code,
|
||||
message: database.lastErrorMessage,
|
||||
sql: String(cString: statementStart))
|
||||
try database.statementCompilationDidFail(at: statementStart, withResultCode: code)
|
||||
}
|
||||
|
||||
guard let sqliteStatement else {
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
@@ -14,6 +14,8 @@ import GRDBSQLite
|
||||
import string_h
|
||||
#elseif os(Linux)
|
||||
import Glibc
|
||||
#elseif os(Android)
|
||||
import Android
|
||||
#elseif os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(visionOS)
|
||||
import Darwin
|
||||
#elseif os(Windows)
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
#if !os(Windows)
|
||||
import Foundation
|
||||
|
||||
private let integerRoundingBehavior = NSDecimalNumberHandler(
|
||||
@@ -104,4 +103,3 @@ extension NSNumber: DatabaseValueConvertible {
|
||||
}
|
||||
|
||||
private let posixLocale = Locale(identifier: "en_US_POSIX")
|
||||
#endif
|
||||
@@ -1,6 +1,5 @@
|
||||
import Foundation
|
||||
|
||||
#if !os(Windows)
|
||||
/// NSURL stores its absoluteString in the database.
|
||||
extension NSURL: DatabaseValueConvertible {
|
||||
|
||||
@@ -20,7 +19,6 @@ extension NSURL: DatabaseValueConvertible {
|
||||
return cast(URL(string: string))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// URL stores its absoluteString in the database.
|
||||
extension URL: DatabaseValueConvertible { }
|
||||
@@ -4,15 +4,14 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
#if !os(Windows)
|
||||
/// NSUUID adopts DatabaseValueConvertible
|
||||
extension NSUUID: DatabaseValueConvertible {
|
||||
/// Returns a BLOB database value containing the uuid bytes.
|
||||
@@ -52,7 +51,6 @@ extension NSUUID: DatabaseValueConvertible {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// UUID adopts DatabaseValueConvertible
|
||||
extension UUID: DatabaseValueConvertible {
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -5,8 +5,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
+2
-2
@@ -5,8 +5,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -5,8 +5,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -5,8 +5,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -5,8 +5,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -1872,6 +1872,18 @@ public struct ColumnAssignment {
|
||||
}
|
||||
}
|
||||
|
||||
/// A strategy for updating database rows in case of upsert conflict.
|
||||
public struct UpsertUpdateStrategy: OptionSet, Sendable {
|
||||
public let rawValue: Int
|
||||
public init(rawValue: Int) { self.rawValue = rawValue }
|
||||
|
||||
/// Only the specified columns are updated in the existing row.
|
||||
public static let noColumnUnlessSpecified = Self([])
|
||||
|
||||
/// All columns are updated in the existing row, unless specified otherwise.
|
||||
public static let allColumns = Self(rawValue: 1 << 0)
|
||||
}
|
||||
|
||||
extension ColumnExpression {
|
||||
/// Returns an assignment of this column to an SQL expression.
|
||||
///
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -42,6 +42,7 @@ final class DAO<Record: MutablePersistableRecord> {
|
||||
func upsertStatement(
|
||||
_ db: Database,
|
||||
onConflict conflictTargetColumns: [String],
|
||||
updating strategy: UpsertUpdateStrategy,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Record>) -> [ColumnAssignment])?,
|
||||
updateCondition: ((
|
||||
_ existing: TableAlias<Record>,
|
||||
@@ -78,20 +79,22 @@ final class DAO<Record: MutablePersistableRecord> {
|
||||
sql += " DO UPDATE SET "
|
||||
let excluded = TableAlias<Record>(name: "excluded")
|
||||
var assignments = assignments?(excluded) ?? []
|
||||
let lowercaseExcludedColumns = Set(primaryKey.columns.map { $0.lowercased() })
|
||||
.union(conflictTargetColumns.map { $0.lowercased() })
|
||||
for column in persistenceContainer.columns {
|
||||
let lowercasedColumn = column.lowercased()
|
||||
if lowercaseExcludedColumns.contains(lowercasedColumn) {
|
||||
// excluded (primary key or conflict target)
|
||||
continue
|
||||
if strategy.contains(.allColumns) {
|
||||
let lowercaseExcludedColumns = Set(primaryKey.columns.map { $0.lowercased() })
|
||||
.union(conflictTargetColumns.map { $0.lowercased() })
|
||||
for column in persistenceContainer.columns {
|
||||
let lowercasedColumn = column.lowercased()
|
||||
if lowercaseExcludedColumns.contains(lowercasedColumn) {
|
||||
// excluded (primary key or conflict target)
|
||||
continue
|
||||
}
|
||||
if assignments.contains(where: { $0.columnName.lowercased() == lowercasedColumn }) {
|
||||
// already updated from the `assignments` argument
|
||||
continue
|
||||
}
|
||||
// overwrite
|
||||
assignments.append(Column(column).set(to: excluded[column]))
|
||||
}
|
||||
if assignments.contains(where: { $0.columnName.lowercased() == lowercasedColumn }) {
|
||||
// already updated from the `assignments` argument
|
||||
continue
|
||||
}
|
||||
// overwrite
|
||||
assignments.append(Column(column).set(to: excluded[column]))
|
||||
}
|
||||
let context = SQLGenerationContext(db)
|
||||
let updateSQL = try assignments
|
||||
|
||||
@@ -73,55 +73,52 @@ extension MutablePersistableRecord {
|
||||
/// let upsertedPlayer = try player.upsertAndFetch(db)
|
||||
/// ```
|
||||
///
|
||||
/// With `conflictTarget` and `assignments` arguments, you can further
|
||||
/// control the upsert behavior. Make sure you check
|
||||
/// With the `conflictTarget`, `strategy`, and `assignments` arguments,
|
||||
/// you can further control the upsert behavior. Make sure you check
|
||||
/// <https://www.sqlite.org/lang_UPSERT.html> for detailed information.
|
||||
///
|
||||
/// The conflict target are the columns of the uniqueness constraint
|
||||
/// (primary key or unique index) that triggers the upsert. If empty, all
|
||||
/// uniqueness constraint are considered.
|
||||
///
|
||||
/// The assignments describe how to update columns in case of violation of
|
||||
/// a uniqueness constraint. In the next example, we insert the new
|
||||
/// vocabulary word "jovial" if that word is not already in the dictionary.
|
||||
/// If the word is already in the dictionary, it increments the counter,
|
||||
/// does not overwrite the tainted flag, and overwrites the
|
||||
/// remaining columns:
|
||||
/// The strategy controls which columns are updated in case of
|
||||
/// uniqueness constraint violation: all columns unless specified (the
|
||||
/// default), or only the specified columns.
|
||||
///
|
||||
/// For example, compare:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE TABLE vocabulary(
|
||||
/// // word TEXT PRIMARY KEY,
|
||||
/// // kind TEXT NOT NULL,
|
||||
/// // isTainted BOOLEAN DEFAULT 0,
|
||||
/// // count INT DEFAULT 1))
|
||||
/// struct Vocabulary: Encodable, MutablePersistableRecord {
|
||||
/// var word: String
|
||||
/// var kind: String
|
||||
/// var isTainted: Bool
|
||||
/// // In case of conflict, updates all columns, including columns added
|
||||
/// // in a future migration.
|
||||
/// let upserted = try player.upsertAndFetch(db)
|
||||
///
|
||||
/// // In case of conflict, updates all columns, including future ones,
|
||||
/// // but 'score'.
|
||||
/// let upserted = try player.upsertAndFetch(db) { _ in
|
||||
/// [Column("score").noOverwrite]
|
||||
/// }
|
||||
///
|
||||
/// // INSERT INTO vocabulary(word, kind, isTainted)
|
||||
/// // VALUES('jovial', 'adjective', 0)
|
||||
/// // ON CONFLICT(word) DO UPDATE SET \
|
||||
/// // count = count + 1,
|
||||
/// // kind = excluded.kind
|
||||
/// // RETURNING *
|
||||
/// var vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false)
|
||||
/// let upserted = try vocabulary.upsertAndFetch(
|
||||
/// db,
|
||||
/// onConflict: ["word"],
|
||||
/// doUpdate: { _ in
|
||||
/// [Column("count") += 1,
|
||||
/// Column("isTainted").noOverwrite]
|
||||
/// })
|
||||
/// // In case of conflict, do not update any column.
|
||||
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified)
|
||||
///
|
||||
/// // In case of conflict, only update 'name'.
|
||||
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified) { excluded in
|
||||
/// [Column("name").set(to: excluded[Column("name")])]
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictTarget: The conflict target.
|
||||
/// - parameter strategy: The default strategy, `.allColumns`, updates
|
||||
/// all columns in case of conflict, unless specified otherwise in the
|
||||
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
|
||||
/// update the columns assigned in the `assignments` parameter.
|
||||
/// - parameter assignments: An optional function that returns an array of
|
||||
/// ``ColumnAssignment``. In case of violation of a uniqueness
|
||||
/// constraints, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values.
|
||||
/// constraint, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values, or not, depending on the
|
||||
/// chosen `strategy`. To use the value that would have been inserted
|
||||
/// had the constraint not failed, use the `excluded` parameter.
|
||||
/// - returns: The upserted record.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
|
||||
/// error thrown by the persistence callbacks defined by the record type.
|
||||
@@ -129,26 +126,36 @@ extension MutablePersistableRecord {
|
||||
public mutating func upsertAndFetch(
|
||||
_ db: Database,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
updating strategy: UpsertUpdateStrategy = .allColumns,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
throws -> Self
|
||||
where Self: FetchableRecord
|
||||
{
|
||||
try upsertAndFetch(db, as: Self.self, onConflict: conflictTarget, doUpdate: assignments)
|
||||
try upsertAndFetch(
|
||||
db, as: Self.self, onConflict: conflictTarget,
|
||||
updating: strategy, doUpdate: assignments)
|
||||
}
|
||||
|
||||
/// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and
|
||||
/// returns the upserted record.
|
||||
///
|
||||
/// See `upsertAndFetch(_:onConflict:doUpdate:)` for more information about
|
||||
/// the `conflictTarget` and `assignments` parameters.
|
||||
/// See ``upsertAndFetch(_:onConflict:updating:doUpdate:)`` for more
|
||||
/// information about the `conflictTarget`, `strategy`, and
|
||||
/// `assignments` parameters.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter returnedType: The type of the returned record.
|
||||
/// - parameter conflictTarget: The conflict target.
|
||||
/// - parameter strategy: The default strategy, `.allColumns`, updates
|
||||
/// all columns in case of conflict, unless specified otherwise in the
|
||||
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
|
||||
/// update the columns assigned in the `assignments` parameter.
|
||||
/// - parameter assignments: An optional function that returns an array of
|
||||
/// ``ColumnAssignment``. In case of violation of a uniqueness
|
||||
/// constraints, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values.
|
||||
/// constraint, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values, or not, depending on the
|
||||
/// chosen `strategy`. To use the value that would have been inserted
|
||||
/// had the constraint not failed, use the `excluded` parameter.
|
||||
/// - returns: A record of type `returnedType`.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
|
||||
/// error thrown by the persistence callbacks defined by the record type.
|
||||
@@ -157,6 +164,7 @@ extension MutablePersistableRecord {
|
||||
_ db: Database,
|
||||
as returnedType: T.Type,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
updating strategy: UpsertUpdateStrategy = .allColumns,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
throws -> T
|
||||
{
|
||||
@@ -166,7 +174,7 @@ extension MutablePersistableRecord {
|
||||
try aroundSave(db) {
|
||||
success = try upsertAndFetchWithCallbacks(
|
||||
db, onConflict: conflictTarget,
|
||||
doUpdate: assignments,
|
||||
updating: strategy, doUpdate: assignments,
|
||||
selection: T.databaseSelection,
|
||||
decode: { try T(row: $0) })
|
||||
return PersistenceSuccess(success!.inserted)
|
||||
@@ -250,55 +258,52 @@ extension MutablePersistableRecord {
|
||||
/// let upsertedPlayer = try player.upsertAndFetch(db)
|
||||
/// ```
|
||||
///
|
||||
/// With `conflictTarget` and `assignments` arguments, you can further
|
||||
/// control the upsert behavior. Make sure you check
|
||||
/// With the `conflictTarget`, `strategy`, and `assignments` arguments,
|
||||
/// you can further control the upsert behavior. Make sure you check
|
||||
/// <https://www.sqlite.org/lang_UPSERT.html> for detailed information.
|
||||
///
|
||||
/// The conflict target are the columns of the uniqueness constraint
|
||||
/// (primary key or unique index) that triggers the upsert. If empty, all
|
||||
/// uniqueness constraint are considered.
|
||||
///
|
||||
/// The assignments describe how to update columns in case of violation of
|
||||
/// a uniqueness constraint. In the next example, we insert the new
|
||||
/// vocabulary word "jovial" if that word is not already in the dictionary.
|
||||
/// If the word is already in the dictionary, it increments the counter,
|
||||
/// does not overwrite the tainted flag, and overwrites the
|
||||
/// remaining columns:
|
||||
/// The strategy controls which columns are updated in case of
|
||||
/// uniqueness constraint violation: all columns unless specified (the
|
||||
/// default), or only the specified columns.
|
||||
///
|
||||
/// For example, compare:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE TABLE vocabulary(
|
||||
/// // word TEXT PRIMARY KEY,
|
||||
/// // kind TEXT NOT NULL,
|
||||
/// // isTainted BOOLEAN DEFAULT 0,
|
||||
/// // count INT DEFAULT 1))
|
||||
/// struct Vocabulary: Encodable, MutablePersistableRecord {
|
||||
/// var word: String
|
||||
/// var kind: String
|
||||
/// var isTainted: Bool
|
||||
/// // In case of conflict, updates all columns, including columns added
|
||||
/// // in a future migration.
|
||||
/// let upserted = try player.upsertAndFetch(db)
|
||||
///
|
||||
/// // In case of conflict, updates all columns, including future ones,
|
||||
/// // but 'score'.
|
||||
/// let upserted = try player.upsertAndFetch(db) { _ in
|
||||
/// [Column("score").noOverwrite]
|
||||
/// }
|
||||
///
|
||||
/// // INSERT INTO vocabulary(word, kind, isTainted)
|
||||
/// // VALUES('jovial', 'adjective', 0)
|
||||
/// // ON CONFLICT(word) DO UPDATE SET \
|
||||
/// // count = count + 1,
|
||||
/// // kind = excluded.kind
|
||||
/// // RETURNING *
|
||||
/// var vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false)
|
||||
/// let upserted = try vocabulary.upsertAndFetch(
|
||||
/// db,
|
||||
/// onConflict: ["word"],
|
||||
/// doUpdate: { _ in
|
||||
/// [Column("count") += 1,
|
||||
/// Column("isTainted").noOverwrite]
|
||||
/// })
|
||||
/// // In case of conflict, do not update any column.
|
||||
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified)
|
||||
///
|
||||
/// // In case of conflict, only update 'name'.
|
||||
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified) { excluded in
|
||||
/// [Column("name").set(to: excluded[Column("name")])]
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictTarget: The conflict target.
|
||||
/// - parameter strategy: The default strategy, `.allColumns`, updates
|
||||
/// all columns in case of conflict, unless specified otherwise in the
|
||||
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
|
||||
/// update the columns assigned in the `assignments` parameter.
|
||||
/// - parameter assignments: An optional function that returns an array of
|
||||
/// ``ColumnAssignment``. In case of violation of a uniqueness
|
||||
/// constraints, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values.
|
||||
/// constraint, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values, or not, depending on the
|
||||
/// chosen `strategy`. To use the value that would have been inserted
|
||||
/// had the constraint not failed, use the `excluded` parameter.
|
||||
/// - returns: The upserted record.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
|
||||
/// error thrown by the persistence callbacks defined by the record type.
|
||||
@@ -307,26 +312,36 @@ extension MutablePersistableRecord {
|
||||
public mutating func upsertAndFetch(
|
||||
_ db: Database,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
updating strategy: UpsertUpdateStrategy = .allColumns,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
throws -> Self
|
||||
where Self: FetchableRecord
|
||||
{
|
||||
try upsertAndFetch(db, as: Self.self, onConflict: conflictTarget, doUpdate: assignments)
|
||||
try upsertAndFetch(
|
||||
db, as: Self.self, onConflict: conflictTarget,
|
||||
updating: strategy, doUpdate: assignments)
|
||||
}
|
||||
|
||||
/// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and
|
||||
/// returns the upserted record.
|
||||
///
|
||||
/// See ``upsertAndFetch(_:onConflict:doUpdate:)`` for more information
|
||||
/// about the `conflictTarget` and `assignments` parameters.
|
||||
/// See ``upsertAndFetch(_:onConflict:updating:doUpdate:)`` for more
|
||||
/// information about the `conflictTarget`, `strategy`, and
|
||||
/// `assignments` parameters.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter returnedType: The type of the returned record.
|
||||
/// - parameter conflictTarget: The conflict target.
|
||||
/// - parameter strategy: The default strategy, `.allColumns`, updates
|
||||
/// all columns in case of conflict, unless specified otherwise in the
|
||||
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
|
||||
/// update the columns assigned in the `assignments` parameter.
|
||||
/// - parameter assignments: An optional function that returns an array of
|
||||
/// ``ColumnAssignment``. In case of violation of a uniqueness
|
||||
/// constraints, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values.
|
||||
/// constraint, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values, or not, depending on the
|
||||
/// chosen `strategy`. To use the value that would have been inserted
|
||||
/// had the constraint not failed, use the `excluded` parameter.
|
||||
/// - returns: A record of type `returnedType`.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
|
||||
/// error thrown by the persistence callbacks defined by the record type.
|
||||
@@ -336,6 +351,7 @@ extension MutablePersistableRecord {
|
||||
_ db: Database,
|
||||
as returnedType: T.Type,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
updating strategy: UpsertUpdateStrategy = .allColumns,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
throws -> T
|
||||
{
|
||||
@@ -345,7 +361,7 @@ extension MutablePersistableRecord {
|
||||
try aroundSave(db) {
|
||||
success = try upsertAndFetchWithCallbacks(
|
||||
db, onConflict: conflictTarget,
|
||||
doUpdate: assignments,
|
||||
updating: strategy, doUpdate: assignments,
|
||||
selection: T.databaseSelection,
|
||||
decode: { try T(row: $0) })
|
||||
return PersistenceSuccess(success!.inserted)
|
||||
@@ -369,6 +385,7 @@ extension MutablePersistableRecord {
|
||||
{
|
||||
let (inserted, _) = try upsertAndFetchWithCallbacks(
|
||||
db, onConflict: [],
|
||||
updating: .allColumns,
|
||||
doUpdate: nil,
|
||||
selection: [],
|
||||
decode: { _ in /* Nothing to decode */ })
|
||||
@@ -379,6 +396,7 @@ extension MutablePersistableRecord {
|
||||
mutating func upsertAndFetchWithCallbacks<T>(
|
||||
_ db: Database,
|
||||
onConflict conflictTarget: [String],
|
||||
updating strategy: UpsertUpdateStrategy,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])?,
|
||||
selection: [any SQLSelectable],
|
||||
decode: (Row) throws -> T)
|
||||
@@ -390,7 +408,7 @@ extension MutablePersistableRecord {
|
||||
try aroundInsert(db) {
|
||||
success = try upsertAndFetchWithoutCallbacks(
|
||||
db, onConflict: conflictTarget,
|
||||
doUpdate: assignments,
|
||||
updating: strategy, doUpdate: assignments,
|
||||
selection: selection,
|
||||
decode: decode)
|
||||
return success!.inserted
|
||||
@@ -409,6 +427,7 @@ extension MutablePersistableRecord {
|
||||
func upsertAndFetchWithoutCallbacks<T>(
|
||||
_ db: Database,
|
||||
onConflict conflictTarget: [String],
|
||||
updating strategy: UpsertUpdateStrategy,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])?,
|
||||
selection: [any SQLSelectable],
|
||||
decode: (Row) throws -> T)
|
||||
@@ -419,8 +438,8 @@ extension MutablePersistableRecord {
|
||||
|
||||
let dao = try DAO(db, self)
|
||||
let statement = try dao.upsertStatement(
|
||||
db,
|
||||
onConflict: conflictTarget,
|
||||
db, onConflict: conflictTarget,
|
||||
updating: strategy,
|
||||
doUpdate: assignments,
|
||||
updateCondition: nil,
|
||||
returning: selection)
|
||||
|
||||
@@ -62,8 +62,9 @@
|
||||
/// - ``insertAndFetch(_:onConflict:as:)``
|
||||
/// - ``insertAndFetch(_:onConflict:selection:fetch:)``
|
||||
/// - ``insertAndFetch(_:onConflict:fetch:select:)``
|
||||
/// - ``upsertAndFetch(_:onConflict:doUpdate:)``
|
||||
/// - ``upsertAndFetch(_:as:onConflict:doUpdate:)``
|
||||
/// - ``upsertAndFetch(_:onConflict:updating:doUpdate:)``
|
||||
/// - ``upsertAndFetch(_:as:onConflict:updating:doUpdate:)``
|
||||
/// - ``UpsertUpdateStrategy``
|
||||
///
|
||||
/// ### Updating a Record
|
||||
///
|
||||
|
||||
@@ -73,55 +73,52 @@ extension PersistableRecord {
|
||||
/// let upsertedPlayer = try player.upsertAndFetch(db)
|
||||
/// ```
|
||||
///
|
||||
/// With `conflictTarget` and `assignments` arguments, you can further
|
||||
/// control the upsert behavior. Make sure you check
|
||||
/// With the `conflictTarget`, `strategy`, and `assignments` arguments,
|
||||
/// you can further control the upsert behavior. Make sure you check
|
||||
/// <https://www.sqlite.org/lang_UPSERT.html> for detailed information.
|
||||
///
|
||||
/// The conflict target are the columns of the uniqueness constraint
|
||||
/// (primary key or unique index) that triggers the upsert. If empty, all
|
||||
/// uniqueness constraint are considered.
|
||||
///
|
||||
/// The assignments describe how to update columns in case of violation of
|
||||
/// a uniqueness constraint. In the next example, we insert the new
|
||||
/// vocabulary word "jovial" if that word is not already in the dictionary.
|
||||
/// If the word is already in the dictionary, it increments the counter,
|
||||
/// does not overwrite the tainted flag, and overwrites the
|
||||
/// remaining columns:
|
||||
/// The strategy controls which columns are updated in case of
|
||||
/// uniqueness constraint violation: all columns unless specified (the
|
||||
/// default), or only the specified columns.
|
||||
///
|
||||
/// For example, compare:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE TABLE vocabulary(
|
||||
/// // word TEXT PRIMARY KEY,
|
||||
/// // kind TEXT NOT NULL,
|
||||
/// // isTainted BOOLEAN DEFAULT 0,
|
||||
/// // count INT DEFAULT 1))
|
||||
/// struct Vocabulary: Encodable, PersistableRecord {
|
||||
/// var word: String
|
||||
/// var kind: String
|
||||
/// var isTainted: Bool
|
||||
/// // In case of conflict, updates all columns, including columns added
|
||||
/// // in a future migration.
|
||||
/// let upserted = try player.upsertAndFetch(db)
|
||||
///
|
||||
/// // In case of conflict, updates all columns, including future ones,
|
||||
/// // but 'score'.
|
||||
/// let upserted = try player.upsertAndFetch(db) { _ in
|
||||
/// [Column("score").noOverwrite]
|
||||
/// }
|
||||
///
|
||||
/// // INSERT INTO vocabulary(word, kind, isTainted)
|
||||
/// // VALUES('jovial', 'adjective', 0)
|
||||
/// // ON CONFLICT(word) DO UPDATE SET \
|
||||
/// // count = count + 1,
|
||||
/// // kind = excluded.kind
|
||||
/// // RETURNING *
|
||||
/// let vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false)
|
||||
/// let upserted = try vocabulary.upsertAndFetch(
|
||||
/// db,
|
||||
/// onConflict: ["word"],
|
||||
/// doUpdate: { _ in
|
||||
/// [Column("count") += 1,
|
||||
/// Column("isTainted").noOverwrite]
|
||||
/// })
|
||||
/// // In case of conflict, do not update any column.
|
||||
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified)
|
||||
///
|
||||
/// // In case of conflict, only update 'name'.
|
||||
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified) { excluded in
|
||||
/// [Column("name").set(to: excluded[Column("name")])]
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictTarget: The conflict target.
|
||||
/// - parameter strategy: The default strategy, `.allColumns`, updates
|
||||
/// all columns in case of conflict, unless specified otherwise in the
|
||||
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
|
||||
/// update the columns assigned in the `assignments` parameter.
|
||||
/// - parameter assignments: An optional function that returns an array of
|
||||
/// ``ColumnAssignment``. In case of violation of a uniqueness
|
||||
/// constraints, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values.
|
||||
/// constraint, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values, or not, depending on the
|
||||
/// chosen `strategy`. To use the value that would have been inserted
|
||||
/// had the constraint not failed, use the `excluded` parameter.
|
||||
/// - returns: The upserted record.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
|
||||
/// error thrown by the persistence callbacks defined by the record type.
|
||||
@@ -129,26 +126,36 @@ extension PersistableRecord {
|
||||
public func upsertAndFetch(
|
||||
_ db: Database,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
updating strategy: UpsertUpdateStrategy = .allColumns,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
throws -> Self
|
||||
where Self: FetchableRecord
|
||||
{
|
||||
try upsertAndFetch(db, as: Self.self, onConflict: conflictTarget, doUpdate: assignments)
|
||||
try upsertAndFetch(
|
||||
db, as: Self.self, onConflict: conflictTarget,
|
||||
updating: strategy, doUpdate: assignments)
|
||||
}
|
||||
|
||||
/// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and
|
||||
/// returns the upserted record.
|
||||
///
|
||||
/// See `upsertAndFetch(_:onConflict:doUpdate:)` for more information about
|
||||
/// the `conflictTarget` and `assignments` parameters.
|
||||
/// See ``upsertAndFetch(_:onConflict:updating:doUpdate:)`` for more
|
||||
/// information about the `conflictTarget`, `strategy`, and
|
||||
/// `assignments` parameters.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter returnedType: The type of the returned record.
|
||||
/// - parameter conflictTarget: The conflict target.
|
||||
/// - parameter strategy: The default strategy, `.allColumns`, updates
|
||||
/// all columns in case of conflict, unless specified otherwise in the
|
||||
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
|
||||
/// update the columns assigned in the `assignments` parameter.
|
||||
/// - parameter assignments: An optional function that returns an array of
|
||||
/// ``ColumnAssignment``. In case of violation of a uniqueness
|
||||
/// constraints, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values.
|
||||
/// constraint, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values, or not, depending on the
|
||||
/// chosen `strategy`. To use the value that would have been inserted
|
||||
/// had the constraint not failed, use the `excluded` parameter.
|
||||
/// - returns: A record of type `returnedType`.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
|
||||
/// error thrown by the persistence callbacks defined by the record type.
|
||||
@@ -157,6 +164,7 @@ extension PersistableRecord {
|
||||
_ db: Database,
|
||||
as returnedType: T.Type,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
updating strategy: UpsertUpdateStrategy = .allColumns,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
throws -> T
|
||||
{
|
||||
@@ -166,7 +174,7 @@ extension PersistableRecord {
|
||||
try aroundSave(db) {
|
||||
success = try upsertAndFetchWithCallbacks(
|
||||
db, onConflict: conflictTarget,
|
||||
doUpdate: assignments,
|
||||
updating: strategy, doUpdate: assignments,
|
||||
selection: T.databaseSelection,
|
||||
decode: { try T(row: $0) })
|
||||
return PersistenceSuccess(success!.inserted)
|
||||
@@ -250,55 +258,52 @@ extension PersistableRecord {
|
||||
/// let upsertedPlayer = try player.upsertAndFetch(db)
|
||||
/// ```
|
||||
///
|
||||
/// With `conflictTarget` and `assignments` arguments, you can further
|
||||
/// control the upsert behavior. Make sure you check
|
||||
/// With the `conflictTarget`, `strategy`, and `assignments` arguments,
|
||||
/// you can further control the upsert behavior. Make sure you check
|
||||
/// <https://www.sqlite.org/lang_UPSERT.html> for detailed information.
|
||||
///
|
||||
/// The conflict target are the columns of the uniqueness constraint
|
||||
/// (primary key or unique index) that triggers the upsert. If empty, all
|
||||
/// uniqueness constraint are considered.
|
||||
///
|
||||
/// The assignments describe how to update columns in case of violation of
|
||||
/// a uniqueness constraint. In the next example, we insert the new
|
||||
/// vocabulary word "jovial" if that word is not already in the dictionary.
|
||||
/// If the word is already in the dictionary, it increments the counter,
|
||||
/// does not overwrite the tainted flag, and overwrites the
|
||||
/// remaining columns:
|
||||
/// The strategy controls which columns are updated in case of
|
||||
/// uniqueness constraint violation: all columns unless specified (the
|
||||
/// default), or only the specified columns.
|
||||
///
|
||||
/// For example, compare:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE TABLE vocabulary(
|
||||
/// // word TEXT PRIMARY KEY,
|
||||
/// // kind TEXT NOT NULL,
|
||||
/// // isTainted BOOLEAN DEFAULT 0,
|
||||
/// // count INT DEFAULT 1))
|
||||
/// struct Vocabulary: Encodable, PersistableRecord {
|
||||
/// var word: String
|
||||
/// var kind: String
|
||||
/// var isTainted: Bool
|
||||
/// // In case of conflict, updates all columns, including columns added
|
||||
/// // in a future migration.
|
||||
/// let upserted = try player.upsertAndFetch(db)
|
||||
///
|
||||
/// // In case of conflict, updates all columns, including future ones,
|
||||
/// // but 'score'.
|
||||
/// let upserted = try player.upsertAndFetch(db) { _ in
|
||||
/// [Column("score").noOverwrite]
|
||||
/// }
|
||||
///
|
||||
/// // INSERT INTO vocabulary(word, kind, isTainted)
|
||||
/// // VALUES('jovial', 'adjective', 0)
|
||||
/// // ON CONFLICT(word) DO UPDATE SET \
|
||||
/// // count = count + 1,
|
||||
/// // kind = excluded.kind
|
||||
/// // RETURNING *
|
||||
/// let vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false)
|
||||
/// let upserted = try vocabulary.upsertAndFetch(
|
||||
/// db,
|
||||
/// onConflict: ["word"],
|
||||
/// doUpdate: { _ in
|
||||
/// [Column("count") += 1,
|
||||
/// Column("isTainted").noOverwrite]
|
||||
/// })
|
||||
/// // In case of conflict, do not update any column.
|
||||
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified)
|
||||
///
|
||||
/// // In case of conflict, only update 'name'.
|
||||
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified) { excluded in
|
||||
/// [Column("name").set(to: excluded[Column("name")])]
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictTarget: The conflict target.
|
||||
/// - parameter strategy: The default strategy, `.allColumns`, updates
|
||||
/// all columns in case of conflict, unless specified otherwise in the
|
||||
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
|
||||
/// update the columns assigned in the `assignments` parameter.
|
||||
/// - parameter assignments: An optional function that returns an array of
|
||||
/// ``ColumnAssignment``. In case of violation of a uniqueness
|
||||
/// constraints, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values.
|
||||
/// constraint, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values, or not, depending on the
|
||||
/// chosen `strategy`. To use the value that would have been inserted
|
||||
/// had the constraint not failed, use the `excluded` parameter.
|
||||
/// - returns: The upserted record.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
|
||||
/// error thrown by the persistence callbacks defined by the record type.
|
||||
@@ -307,26 +312,36 @@ extension PersistableRecord {
|
||||
public func upsertAndFetch(
|
||||
_ db: Database,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
updating strategy: UpsertUpdateStrategy = .allColumns,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
throws -> Self
|
||||
where Self: FetchableRecord
|
||||
{
|
||||
try upsertAndFetch(db, as: Self.self, onConflict: conflictTarget, doUpdate: assignments)
|
||||
try upsertAndFetch(
|
||||
db, as: Self.self, onConflict: conflictTarget,
|
||||
updating: strategy, doUpdate: assignments)
|
||||
}
|
||||
|
||||
/// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and
|
||||
/// returns the upserted record.
|
||||
///
|
||||
/// See ``upsertAndFetch(_:onConflict:doUpdate:)`` for more information
|
||||
/// about the `conflictTarget` and `assignments` parameters.
|
||||
/// See ``upsertAndFetch(_:onConflict:updating:doUpdate:)`` for more
|
||||
/// information about the `conflictTarget`, `strategy`, and
|
||||
/// `assignments` parameters.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter returnedType: The type of the returned record.
|
||||
/// - parameter conflictTarget: The conflict target.
|
||||
/// - parameter strategy: The default strategy, `.allColumns`, updates
|
||||
/// all columns in case of conflict, unless specified otherwise in the
|
||||
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
|
||||
/// update the columns assigned in the `assignments` parameter.
|
||||
/// - parameter assignments: An optional function that returns an array of
|
||||
/// ``ColumnAssignment``. In case of violation of a uniqueness
|
||||
/// constraints, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values.
|
||||
/// constraint, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values, or not, depending on the
|
||||
/// chosen `strategy`. To use the value that would have been inserted
|
||||
/// had the constraint not failed, use the `excluded` parameter.
|
||||
/// - returns: A record of type `returnedType`.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
|
||||
/// error thrown by the persistence callbacks defined by the record type.
|
||||
@@ -336,6 +351,7 @@ extension PersistableRecord {
|
||||
_ db: Database,
|
||||
as returnedType: T.Type,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
updating strategy: UpsertUpdateStrategy = .allColumns,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
throws -> T
|
||||
{
|
||||
@@ -345,7 +361,7 @@ extension PersistableRecord {
|
||||
try aroundSave(db) {
|
||||
success = try upsertAndFetchWithCallbacks(
|
||||
db, onConflict: conflictTarget,
|
||||
doUpdate: assignments,
|
||||
updating: strategy, doUpdate: assignments,
|
||||
selection: T.databaseSelection,
|
||||
decode: { try T(row: $0) })
|
||||
return PersistenceSuccess(success!.inserted)
|
||||
@@ -369,6 +385,7 @@ extension PersistableRecord {
|
||||
{
|
||||
let (inserted, _) = try upsertAndFetchWithCallbacks(
|
||||
db, onConflict: [],
|
||||
updating: .allColumns,
|
||||
doUpdate: nil,
|
||||
selection: [],
|
||||
decode: { _ in /* Nothing to decode */ })
|
||||
@@ -379,6 +396,7 @@ extension PersistableRecord {
|
||||
func upsertAndFetchWithCallbacks<T>(
|
||||
_ db: Database,
|
||||
onConflict conflictTarget: [String],
|
||||
updating strategy: UpsertUpdateStrategy,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])?,
|
||||
selection: [any SQLSelectable],
|
||||
decode: (Row) throws -> T)
|
||||
@@ -390,7 +408,7 @@ extension PersistableRecord {
|
||||
try aroundInsert(db) {
|
||||
success = try upsertAndFetchWithoutCallbacks(
|
||||
db, onConflict: conflictTarget,
|
||||
doUpdate: assignments,
|
||||
updating: strategy, doUpdate: assignments,
|
||||
selection: selection,
|
||||
decode: decode)
|
||||
return success!.inserted
|
||||
|
||||
@@ -24,8 +24,9 @@
|
||||
/// - ``insertAndFetch(_:onConflict:as:)``
|
||||
/// - ``insertAndFetch(_:onConflict:selection:fetch:)``
|
||||
/// - ``insertAndFetch(_:onConflict:fetch:select:)``
|
||||
/// - ``upsertAndFetch(_:onConflict:doUpdate:)``
|
||||
/// - ``upsertAndFetch(_:as:onConflict:doUpdate:)``
|
||||
/// - ``upsertAndFetch(_:onConflict:updating:doUpdate:)``
|
||||
/// - ``upsertAndFetch(_:as:onConflict:updating:doUpdate:)``
|
||||
/// - ``UpsertUpdateStrategy``
|
||||
///
|
||||
/// ### Saving a Record
|
||||
///
|
||||
|
||||
@@ -806,14 +806,14 @@ extension ValueConcurrentObserver: TransactionObserver {
|
||||
|
||||
private func asyncFetch(databaseAccess: DatabaseAccess) {
|
||||
databaseAccess.dbPool.asyncRead { [self] dbResult in
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
let isNotifying = lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
let fetchResult = dbResult.flatMap { db in
|
||||
Result { try databaseAccess.fetch(db) }
|
||||
}
|
||||
|
||||
self.reduce(fetchResult)
|
||||
reduce(fetchResult)
|
||||
|
||||
fetchingStateMutex.withLock { state in
|
||||
switch state {
|
||||
|
||||
@@ -345,7 +345,7 @@ extension ValueObservation {
|
||||
/// - parameter reader: A DatabaseReader.
|
||||
/// - parameter scheduler: A ValueObservationScheduler. By default,
|
||||
/// fresh values are dispatched on the cooperative thread pool.
|
||||
/// - parameter bufferingPolicy: see the documntation
|
||||
/// - parameter bufferingPolicy: see the documentation
|
||||
/// of `AsyncThrowingStream`.
|
||||
public func values(
|
||||
in reader: any DatabaseReader,
|
||||
|
||||
@@ -287,6 +287,7 @@
|
||||
56C0539722ACEECD0029D27D /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538C22ACEECD0029D27D /* ValueReducer.swift */; };
|
||||
56C0539B22ACEECD0029D27D /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538E22ACEECD0029D27D /* Map.swift */; };
|
||||
56C0539D22ACEECD0029D27D /* RemoveDuplicates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538F22ACEECD0029D27D /* RemoveDuplicates.swift */; };
|
||||
56C7979D2EE99BE900AA265D /* Issue1838Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C7979C2EE99BE900AA265D /* Issue1838Tests.swift */; };
|
||||
56C7A6AE1D2DFF6100EFB0C2 /* FoundationNSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */; };
|
||||
56C9EB9B2495324700FE5D55 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 56C9EB9A2495324700FE5D55 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
|
||||
56CC9234201E009000CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */; };
|
||||
@@ -814,6 +815,7 @@
|
||||
56C0538F22ACEECD0029D27D /* RemoveDuplicates.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RemoveDuplicates.swift; sourceTree = "<group>"; };
|
||||
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSavepointTests.swift; sourceTree = "<group>"; };
|
||||
56C494421ED726C500CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = GRDBDeploymentTarget.xcconfig; path = SQLiteCustom/GRDBDeploymentTarget.xcconfig; sourceTree = "<group>"; };
|
||||
56C7979C2EE99BE900AA265D /* Issue1838Tests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Issue1838Tests.swift; sourceTree = "<group>"; };
|
||||
56C9EB9A2495324700FE5D55 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = grdb_config.h; path = SQLiteCustom/grdb_config.h; sourceTree = "<group>"; };
|
||||
56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropWhileCursorTests.swift; sourceTree = "<group>"; };
|
||||
56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1441,6 +1443,7 @@
|
||||
5698AC3E1DA2BEBB0056AF8C /* FTS */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56C7979C2EE99BE900AA265D /* Issue1838Tests.swift */,
|
||||
5698AC3F1DA2BED90056AF8C /* FTS3PatternTests.swift */,
|
||||
5698AC481DA2D48A0056AF8C /* FTS3RecordTests.swift */,
|
||||
5698AC881DA389380056AF8C /* FTS3TableBuilderTests.swift */,
|
||||
@@ -2374,6 +2377,7 @@
|
||||
562205FE1E420EA2005860AC /* DatabasePoolConcurrencyTests.swift in Sources */,
|
||||
565EFAF11D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */,
|
||||
56DF0017228DDB8300D611F3 /* AssociationPrefetchingRowTests.swift in Sources */,
|
||||
56C7979D2EE99BE900AA265D /* Issue1838Tests.swift in Sources */,
|
||||
F3BA812E1CFB3064003DC1BA /* RecordPrimaryKeyMultipleTests.swift in Sources */,
|
||||
F3BA81021CFB3032003DC1BA /* CGFloatTests.swift in Sources */,
|
||||
5676FBAA22F5CEB9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */,
|
||||
|
||||
+19
-11
@@ -14,12 +14,6 @@ let darwinPlatforms: [Platform] = [
|
||||
]
|
||||
var swiftSettings: [SwiftSetting] = [
|
||||
.define("SQLITE_ENABLE_FTS5"),
|
||||
// Until Xcode has proper support for package traits, we must enable
|
||||
// SQLITE_ENABLE_SNAPSHOT by default so that Xcode projects that build
|
||||
// a Darwin app can depend on GRDB and profit from WAL snapshots.
|
||||
// Package traits who want to disable snapshots must set SQLITE_DISABLE_SNAPSHOT.
|
||||
// TODO: when Xcode support traits, remove all mentions of SQLITE_DISABLE_SNAPSHOT and update as below:
|
||||
// .define("SQLITE_ENABLE_SNAPSHOT", .when(platforms: darwinPlatforms, traits: ["GRDBSQLite"])),
|
||||
.define("SQLITE_ENABLE_SNAPSHOT"),
|
||||
// Not all Linux distributions have support for WAL snapshots.
|
||||
.define("SQLITE_DISABLE_SNAPSHOT", .when(platforms: [.linux])),
|
||||
@@ -44,6 +38,12 @@ if ProcessInfo.processInfo.environment["SPI_BUILDER"] == "1" {
|
||||
dependencies.append(.package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"))
|
||||
}
|
||||
|
||||
// GRDB+SQLCipher: Uncomment those lines
|
||||
//dependencies.append(.package(url: "https://github.com/sqlcipher/SQLCipher.swift.git", from: "4.11.0"))
|
||||
//cSettings.append(.define("SQLITE_HAS_CODEC"))
|
||||
//swiftSettings.append(.define("SQLITE_HAS_CODEC"))
|
||||
//swiftSettings.append(.define("SQLCipher"))
|
||||
|
||||
let package = Package(
|
||||
name: "GRDB",
|
||||
defaultLocalization: "en", // for tests
|
||||
@@ -54,23 +54,30 @@ let package = Package(
|
||||
.watchOS(.v7),
|
||||
],
|
||||
products: [
|
||||
// GRDB+SQLCipher: Delete the GRDBSQLite library
|
||||
.library(name: "GRDBSQLite", targets: ["GRDBSQLite"]),
|
||||
.library(name: "GRDB", targets: ["GRDB"]),
|
||||
.library(name: "GRDB-dynamic", type: .dynamic, targets: ["GRDB"]),
|
||||
],
|
||||
traits: [
|
||||
"GRDBSQLite",
|
||||
.default(enabledTraits: ["GRDBSQLite"]),
|
||||
],
|
||||
dependencies: dependencies,
|
||||
targets: [
|
||||
// GRDB+SQLCipher: Delete the GRDBSQLite target
|
||||
.systemLibrary(
|
||||
name: "GRDBSQLite",
|
||||
providers: [.apt(["libsqlite3-dev"])]),
|
||||
// GRDB+SQLCipher: Uncomment the GRDBSQLCipher target
|
||||
//.target(
|
||||
// name: "GRDBSQLCipher",
|
||||
// dependencies: [.product(name: "SQLCipher", package: "SQLCipher.swift")]
|
||||
//),
|
||||
.target(
|
||||
name: "GRDB",
|
||||
dependencies: [
|
||||
.target(name: "GRDBSQLite", condition: .when(traits: ["GRDBSQLite"])),
|
||||
// GRDB+SQLCipher: Delete the GRDBSQLite dependency
|
||||
.target(name: "GRDBSQLite"),
|
||||
// GRDB+SQLCipher: Uncomment the SQLCipher and GRDBSQLCipher dependencies
|
||||
//.product(name: "SQLCipher", package: "SQLCipher.swift"),
|
||||
//.target(name: "GRDBSQLCipher"),
|
||||
],
|
||||
path: "GRDB",
|
||||
resources: [.copy("PrivacyInfo.xcprivacy")],
|
||||
@@ -97,6 +104,7 @@ let package = Package(
|
||||
.copy("GRDBTests/Betty.jpeg"),
|
||||
.copy("GRDBTests/InflectionsTests.json"),
|
||||
.copy("GRDBTests/Issue1383.sqlite"),
|
||||
.copy("GRDBTests/db.SQLCipher3"),
|
||||
],
|
||||
cSettings: cSettings,
|
||||
swiftSettings: swiftSettings + [
|
||||
|
||||
@@ -15,17 +15,7 @@
|
||||
<a href="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml"><img alt="CI Status" src="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml/badge.svg?branch=master"></a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
<a href="https://menial.co.uk/base/"><img alt="Base: The best SQLite database editor for macOS" src="https://raw.githubusercontent.com/groue/GRDB.swift/master/Sponsors/base.png"></a>
|
||||
|
||||
<p align="center">
|
||||
<strong>Thank you to <a href="https://menial.co.uk/base/">Base</a> for sponsoring GRDB</strong><br />Base is a small, powerful, comfortable SQLite editor for everyone on macOS.
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
**Latest release**: October 2, 2025 • [version 7.8.0](https://github.com/groue/GRDB.swift/tree/v7.8.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
|
||||
**Latest release**: February 15, 2026 • [version 7.10.0](https://github.com/groue/GRDB.swift/tree/v7.10.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
|
||||
|
||||
**Requirements**: iOS 13.0+ / macOS 10.15+ / tvOS 13.0+ / watchOS 7.0+ • SQLite 3.20.0+ • Swift 6.1+ / Xcode 16.3+
|
||||
|
||||
@@ -110,7 +100,7 @@ try dbQueue.write { db in
|
||||
}
|
||||
|
||||
try dbQueue.read { db in
|
||||
let player = try Player.find(db, id: "1"))
|
||||
let player = try Player.find(db, id: "1")
|
||||
|
||||
let bestPlayers = try Player
|
||||
.order(\.score.desc)
|
||||
@@ -209,7 +199,7 @@ try dbQueue.write { db in
|
||||
|
||||
// Update a record
|
||||
player.score += 10
|
||||
try score.update(db)
|
||||
try player.update(db)
|
||||
|
||||
try player.updateChanges { $0.score += 10 }
|
||||
|
||||
@@ -1662,7 +1652,7 @@ Records
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
if var place = try Player.fetchOne(db, id: 1) {
|
||||
if var player = try Player.fetchOne(db, id: 1) {
|
||||
player.score += 10
|
||||
try player.update(db)
|
||||
}
|
||||
@@ -2220,7 +2210,7 @@ For more information about batch updates, see [Update Requests](#update-requests
|
||||
try player.upsert(db)
|
||||
```
|
||||
|
||||
- `upsertAndFetch(_:onConflict:doUpdate:)` (requires [FetchableRecord] conformance)
|
||||
- `upsertAndFetch(_:onConflict:updating:doUpdate:)` (requires [FetchableRecord] conformance)
|
||||
|
||||
Inserts or updates a record, and returns the upserted record.
|
||||
|
||||
@@ -2230,7 +2220,7 @@ For more information about batch updates, see [Update Requests](#update-requests
|
||||
|
||||
If empty (the default), all uniqueness constraint are considered.
|
||||
|
||||
- `doUpdate`: a closure that returns columns assignments to perform in case of conflict. Other columns are overwritten with the inserted values.
|
||||
- `doUpdate`: a closure that returns columns assignments to perform in case of conflict. Depending on the `options` parameter, other columns are overwritten with the inserted values, or not.
|
||||
|
||||
By default, all inserted columns but the primary key and the conflict target are overwritten.
|
||||
|
||||
@@ -2278,9 +2268,9 @@ For more information about batch updates, see [Update Requests](#update-requests
|
||||
})
|
||||
```
|
||||
|
||||
- `upsertAndFetch(_:as:onConflict:doUpdate:)` (does not require [FetchableRecord] conformance)
|
||||
- `upsertAndFetch(_:as:onConflict:updating:doUpdate:)` (does not require [FetchableRecord] conformance)
|
||||
|
||||
This method is identical to `upsertAndFetch(_:onConflict:doUpdate:)` described above, but you can provide a distinct [FetchableRecord] record type as a result, in order to specify the returned columns.
|
||||
This method is identical to `upsertAndFetch(_:onConflict:updating:doUpdate:)` described above, but you can provide a distinct [FetchableRecord] record type as a result, in order to specify the returned columns.
|
||||
|
||||
### Persistence Methods and the `RETURNING` clause
|
||||
|
||||
@@ -4599,7 +4589,9 @@ Encryption
|
||||
|
||||
**GRDB can encrypt your database with [SQLCipher](http://sqlcipher.net) v3.4+.**
|
||||
|
||||
Use [CocoaPods](http://cocoapods.org/), and specify in your `Podfile`:
|
||||
To use SQLCipher with the [Swift Package Manager](https://swift.org/package-manager/), you must fork GRDB, and modify `Package.swift`. Instructions are in the file itself, in comments that contain "GRDB+SQLCipher".
|
||||
|
||||
To use SQLCipher with [CocoaPods](http://cocoapods.org/), specify in your `Podfile`:
|
||||
|
||||
```ruby
|
||||
# GRDB with SQLCipher 4
|
||||
|
||||
@@ -5,6 +5,7 @@ disabled_rules:
|
||||
- comment_spacing
|
||||
- cyclomatic_complexity
|
||||
- duplicate_enum_cases
|
||||
- duplicate_imports
|
||||
- file_length
|
||||
- for_where
|
||||
- force_cast
|
||||
@@ -62,7 +63,6 @@ opt_in_rules:
|
||||
- redundant_type_annotation
|
||||
- shorthand_optional_binding
|
||||
- sorted_first_last
|
||||
- sorted_imports
|
||||
- toggle_bool
|
||||
- unhandled_throwing_task
|
||||
- vertical_parameter_alignment_on_call
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
// empty c-file
|
||||
@@ -0,0 +1,32 @@
|
||||
#ifndef grdb_config_h
|
||||
#define grdb_config_h
|
||||
|
||||
#include <SQLCipher/sqlite3.h>
|
||||
|
||||
typedef void(*_errorLogCallback)(void *pArg, int iErrCode, const char *zMsg);
|
||||
|
||||
/// Wrapper around sqlite3_config(SQLITE_CONFIG_LOG, ...) which is a variadic
|
||||
/// function that can't be used from Swift.
|
||||
static inline void _registerErrorLogCallback(_errorLogCallback callback) {
|
||||
sqlite3_config(SQLITE_CONFIG_LOG, callback, 0);
|
||||
}
|
||||
|
||||
#if SQLITE_VERSION_NUMBER >= 3029000
|
||||
/// Wrapper around sqlite3_db_config() which is a variadic function that can't
|
||||
/// be used from Swift.
|
||||
static inline void _disableDoubleQuotedStringLiterals(sqlite3 *db) {
|
||||
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 0, (void *)0);
|
||||
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 0, (void *)0);
|
||||
}
|
||||
|
||||
/// Wrapper around sqlite3_db_config() which is a variadic function that can't
|
||||
/// be used from Swift.
|
||||
static inline void _enableDoubleQuotedStringLiterals(sqlite3 *db) {
|
||||
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 1, (void *)0);
|
||||
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 1, (void *)0);
|
||||
}
|
||||
#else
|
||||
static inline void _disableDoubleQuotedStringLiterals(sqlite3 *db) { }
|
||||
static inline void _enableDoubleQuotedStringLiterals(sqlite3 *db) { }
|
||||
#endif
|
||||
#endif /* grdb_config_h */
|
||||
@@ -0,0 +1,4 @@
|
||||
module GRDBSQLCipher {
|
||||
header "SQLCipher_config.h"
|
||||
export *
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 78 KiB |
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>7.8.0</string>
|
||||
<string>7.10.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -148,7 +148,7 @@ class AssociationTableAliasTestsSQLTests : GRDBTestCase {
|
||||
"""
|
||||
|
||||
do {
|
||||
let request = A
|
||||
let request: QueryInterfaceRequest<A> = A
|
||||
.aliased(alias)
|
||||
.select(\.name)
|
||||
.filter(key: 1)
|
||||
@@ -159,7 +159,7 @@ class AssociationTableAliasTestsSQLTests : GRDBTestCase {
|
||||
try assertEqualSQL(db, request, expectedSQL)
|
||||
}
|
||||
do {
|
||||
let request = A
|
||||
let request: QueryInterfaceRequest<A> = A
|
||||
.select(\.name)
|
||||
.filter(key: 1)
|
||||
.filter { $0.name != nil && alias.name == "foo" }
|
||||
@@ -183,7 +183,7 @@ class AssociationTableAliasTestsSQLTests : GRDBTestCase {
|
||||
"""
|
||||
|
||||
do {
|
||||
let request = A
|
||||
let request: QueryInterfaceRequest<A> = A
|
||||
.aliased(alias)
|
||||
.select(\.name)
|
||||
.filter(key: 1)
|
||||
@@ -194,7 +194,7 @@ class AssociationTableAliasTestsSQLTests : GRDBTestCase {
|
||||
try assertEqualSQL(db, request, expectedSQL)
|
||||
}
|
||||
do {
|
||||
let request = A
|
||||
let request: QueryInterfaceRequest<A> = A
|
||||
.select(\.name)
|
||||
.filter(key: 1)
|
||||
.filter { $0.name != nil && alias.name == "foo" }
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -12,24 +12,32 @@ class DatabaseConfigurationTests: GRDBTestCase {
|
||||
connectionCountMutex.increment()
|
||||
}
|
||||
|
||||
connectionCountMutex.store(0)
|
||||
_ = try DatabaseQueue(configuration: configuration)
|
||||
XCTAssertEqual(connectionCountMutex.load(), 1)
|
||||
|
||||
connectionCountMutex.store(0)
|
||||
_ = try makeDatabaseQueue(configuration: configuration)
|
||||
XCTAssertEqual(connectionCountMutex.load(), 2)
|
||||
XCTAssertEqual(connectionCountMutex.load(), 1)
|
||||
|
||||
connectionCountMutex.store(0)
|
||||
let pool = try makeDatabasePool(configuration: configuration)
|
||||
XCTAssertEqual(connectionCountMutex.load(), 3)
|
||||
XCTAssertEqual(connectionCountMutex.load(), 1) // writer
|
||||
|
||||
connectionCountMutex.store(0)
|
||||
try pool.read { _ in }
|
||||
XCTAssertEqual(connectionCountMutex.load(), 4)
|
||||
XCTAssertEqual(connectionCountMutex.load(), 1) // 1st reader
|
||||
|
||||
connectionCountMutex.store(0)
|
||||
try pool.makeSnapshot().read { _ in }
|
||||
XCTAssertEqual(connectionCountMutex.load(), 5)
|
||||
XCTAssertEqual(connectionCountMutex.load(), 1) // snapshot
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
try pool.makeSnapshotPool().read { _ in }
|
||||
XCTAssertEqual(connectionCountMutex.load(), 6)
|
||||
connectionCountMutex.store(0)
|
||||
let snapshotPool = try pool.makeSnapshotPool()
|
||||
XCTAssertEqual(connectionCountMutex.load(), 1) // snapshot
|
||||
try snapshotPool.read { _ in }
|
||||
XCTAssertEqual(connectionCountMutex.load(), 2) // 1st reader
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -896,4 +896,41 @@ class DatabaseWriterTests : GRDBTestCase {
|
||||
try await test(makeDatabasePool())
|
||||
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
|
||||
}
|
||||
|
||||
// Regression test for https://github.com/groue/GRDB.swift/pull/1838
|
||||
func test_cancellation_does_not_prevent_rollback() async throws {
|
||||
func test(_ dbWriter: some DatabaseWriter) async throws {
|
||||
// Numbers that have the test fail more or less reliably
|
||||
// (on my machine) unless the #1838 patch is applied.
|
||||
// When the test fails, we have a fatal error: A transaction has been left opened at the end of a database access.
|
||||
let repeatCount = 400
|
||||
let taskCount = 50
|
||||
for _ in 0..<repeatCount {
|
||||
try await withThrowingTaskGroup(of: Void.self) { group in
|
||||
for _ in 0..<taskCount{
|
||||
let task = Task {
|
||||
try await dbWriter.writeWithoutTransaction { db in
|
||||
try db.beginTransaction()
|
||||
try db.rollback()
|
||||
}
|
||||
}
|
||||
group.addTask {
|
||||
Task {
|
||||
// For the test to fail, we need to be lucky, here:
|
||||
// Cancellation must occur during the compilation
|
||||
// or the execution of the rollback statement.
|
||||
task.cancel()
|
||||
}
|
||||
// Ignore expected CancellationError
|
||||
try? await task.value
|
||||
}
|
||||
}
|
||||
try await group.waitForAll()
|
||||
}
|
||||
}
|
||||
}
|
||||
try await test(makeDatabaseQueue())
|
||||
try await test(makeDatabasePool())
|
||||
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,12 @@ import GRDB
|
||||
|
||||
class EncryptionTests: GRDBTestCase {
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
let testBundle = Bundle.module
|
||||
#else
|
||||
let testBundle = Bundle(for: GRDBTestCase.self)
|
||||
#endif
|
||||
|
||||
func testDatabaseQueueWithPassphraseToDatabaseQueueWithPassphrase() throws {
|
||||
do {
|
||||
var config = Configuration()
|
||||
@@ -707,7 +713,6 @@ class EncryptionTests: GRDBTestCase {
|
||||
else { XCTFail("Unknown SQLCipher version"); return }
|
||||
|
||||
if cipherMajorVersion >= 4 {
|
||||
let testBundle = Bundle(for: type(of: self))
|
||||
let path = testBundle.url(forResource: "db", withExtension: "SQLCipher3")!.path
|
||||
var configuration = Configuration()
|
||||
configuration.prepareDatabase { db in
|
||||
@@ -728,5 +733,69 @@ class EncryptionTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testCipherVersion() throws {
|
||||
try DatabaseQueue().inDatabase { db in
|
||||
_ = try db.cipherVersion
|
||||
}
|
||||
}
|
||||
|
||||
func testCipherFipsStatus() throws {
|
||||
var config = Configuration()
|
||||
config.prepareDatabase { db in
|
||||
try db.usePassphrase("secret")
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue(configuration: config)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertEqual("0", try db.cipherFipsStatus)
|
||||
}
|
||||
}
|
||||
|
||||
func testCipherProvider() throws {
|
||||
var config = Configuration()
|
||||
config.prepareDatabase { db in
|
||||
try db.usePassphrase("secret")
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue(configuration: config)
|
||||
try dbQueue.inDatabase { db in
|
||||
let provider = try db.cipherProvider
|
||||
XCTAssertTrue(["commoncrypto", "libtomcrypt"].contains(provider), "unrecognized cipherProvider: \(provider ?? "")")
|
||||
}
|
||||
}
|
||||
|
||||
func testCipherProviderVersion() throws {
|
||||
var config = Configuration()
|
||||
config.prepareDatabase { db in
|
||||
try db.usePassphrase("secret")
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue(configuration: config)
|
||||
let cipherVersion = try dbQueue.read { try $0.cipherVersion }
|
||||
if "4.10.0".compare(cipherVersion, options: .numeric) == .orderedDescending {
|
||||
throw XCTSkip("cipher_provider_version isn't available until SQLCipher 4.10.0")
|
||||
}
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertNotNil(try db.cipherProviderVersion)
|
||||
}
|
||||
}
|
||||
|
||||
func test_enableCipherLogging() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let cipherVersion = try dbQueue.read { try $0.cipherVersion }
|
||||
if "4.0.0".compare(cipherVersion, options: .numeric) == .orderedDescending {
|
||||
throw XCTSkip("SQLCipher logging is not available")
|
||||
}
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.enableCipherLogging()
|
||||
try db.enableCipherLogging(logLevel: .error)
|
||||
try db.enableCipherLogging(target: .stdout)
|
||||
|
||||
let logFilePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(ProcessInfo.processInfo.globallyUniqueString)
|
||||
defer {
|
||||
try? FileManager.default.removeItem(atPath: logFilePath)
|
||||
}
|
||||
try db.enableCipherLogging(target: .file(logFilePath))
|
||||
XCTAssert(FileManager.default.fileExists(atPath: logFilePath))
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import GRDB
|
||||
import XCTest
|
||||
|
||||
class Issue1838Tests: GRDBTestCase {
|
||||
/// Regression test for <https://github.com/groue/GRDB.swift/issues/1838>.
|
||||
///
|
||||
/// This test passes since <https://github.com/groue/GRDB.swift/pull/1839>
|
||||
/// which workarounds the SQLite bug described at
|
||||
/// <https://sqlite.org/forum/forumpost/95413eb410>.
|
||||
func test_interrupted_rollback() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: "CREATE VIRTUAL TABLE documents USING FTS5(content)")
|
||||
try db.inTransaction {
|
||||
try db.execute(sql: "INSERT INTO documents(content) VALUES ('Document')")
|
||||
dbQueue.interrupt()
|
||||
return .rollback
|
||||
}
|
||||
}
|
||||
|
||||
let documentCount = try dbQueue.read { db in
|
||||
try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents")!
|
||||
}
|
||||
XCTAssertEqual(documentCount, 0)
|
||||
}
|
||||
|
||||
/// Tests about how we handle the FTS5 bug <https://sqlite.org/forum/forumpost/95413eb410>
|
||||
func test_interrupted_commit() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
try dbQueue.write { db in
|
||||
try db.execute(sql: "CREATE VIRTUAL TABLE documents USING FTS5(content)")
|
||||
}
|
||||
|
||||
do {
|
||||
try dbQueue.write { db in
|
||||
try db.execute(sql: "INSERT INTO documents(content) VALUES ('Document')")
|
||||
dbQueue.interrupt()
|
||||
}
|
||||
// Do not assert that the above code throws, because the
|
||||
// FTS5 bug might be fixed in the tested SQLite version.
|
||||
} catch DatabaseError.SQLITE_INTERRUPT {
|
||||
// Fine: That's the FTS5 bug.
|
||||
}
|
||||
|
||||
// Make sure the interrupted state created by the FTS5 bug is no longer active.
|
||||
let documentCount = try dbQueue.read { db in
|
||||
try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents")!
|
||||
}
|
||||
XCTAssertEqual(documentCount, 0)
|
||||
}
|
||||
}
|
||||
@@ -2334,7 +2334,7 @@ extension MutablePersistableRecordTests {
|
||||
}
|
||||
}
|
||||
|
||||
func test_upsertAndFetch_do_update_set_where() throws {
|
||||
func test_upsertAndFetch_do_update_set_where_with_default_strategy() throws {
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
guard Database.sqliteLibVersionNumber >= 3035000 else {
|
||||
throw XCTSkip("UPSERT is not available")
|
||||
@@ -2351,10 +2351,10 @@ extension MutablePersistableRecordTests {
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE vocabulary(
|
||||
word TEXT PRIMARY KEY,
|
||||
kind TEXT,
|
||||
kind TEXT NOT NULL,
|
||||
isTainted BOOLEAN DEFAULT 0,
|
||||
count INT DEFAULT 1);
|
||||
INSERT INTO vocabulary(word, isTainted) VALUES('jovial', 1);
|
||||
INSERT INTO vocabulary(word, kind, isTainted) VALUES('jovial', 'name', 1);
|
||||
""")
|
||||
|
||||
struct Vocabulary: Decodable, MutablePersistableRecord, FetchableRecord {
|
||||
@@ -2376,6 +2376,36 @@ extension MutablePersistableRecordTests {
|
||||
}
|
||||
}
|
||||
|
||||
// No column specified, no unique index specified
|
||||
do {
|
||||
var vocabulary = Vocabulary(word: "jovial", kind: "ambiguous", isTainted: true)
|
||||
let upserted = try vocabulary.upsertAndFetch(db)
|
||||
|
||||
// Test didSave
|
||||
XCTAssertEqual(vocabulary.rowID, 1)
|
||||
|
||||
// Test SQL
|
||||
XCTAssertEqual(lastSQLQuery, """
|
||||
INSERT INTO "vocabulary" ("word", "kind", "isTainted") \
|
||||
VALUES ('jovial','ambiguous',1) \
|
||||
ON CONFLICT \
|
||||
DO UPDATE SET "kind" = "excluded"."kind", "isTainted" = "excluded"."isTainted" \
|
||||
RETURNING *, "rowid"
|
||||
""")
|
||||
|
||||
// Test database state
|
||||
let rows = try Row.fetchAll(db, sql: "SELECT * FROM vocabulary")
|
||||
XCTAssertEqual(rows, [
|
||||
["word": "jovial", "kind": "ambiguous", "isTainted": 1, "count": 1],
|
||||
])
|
||||
|
||||
// Test upserted record
|
||||
XCTAssertEqual(upserted.word, "jovial")
|
||||
XCTAssertEqual(upserted.kind, "ambiguous")
|
||||
XCTAssertEqual(upserted.isTainted, true)
|
||||
XCTAssertEqual(upserted.count, 1)
|
||||
}
|
||||
|
||||
// One column with specific assignment (count)
|
||||
// One column with no assignment (isTainted)
|
||||
// One column with default overwrite assignment (kind)
|
||||
@@ -2490,6 +2520,191 @@ extension MutablePersistableRecordTests {
|
||||
}
|
||||
}
|
||||
|
||||
func test_upsertAndFetch_do_update_set_where_with_noColumnUnlessSpecified_strategy() throws {
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
guard Database.sqliteLibVersionNumber >= 3035000 else {
|
||||
throw XCTSkip("UPSERT is not available")
|
||||
}
|
||||
#else
|
||||
guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
|
||||
throw XCTSkip("UPSERT is not available")
|
||||
}
|
||||
#endif
|
||||
|
||||
try makeDatabaseQueue().write { db in
|
||||
// Test exemples of https://www.sqlite.org/lang_UPSERT.html
|
||||
do {
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE vocabulary(
|
||||
word TEXT PRIMARY KEY,
|
||||
kind TEXT NOT NULL,
|
||||
isTainted BOOLEAN DEFAULT 0,
|
||||
count INT DEFAULT 1);
|
||||
INSERT INTO vocabulary(word, kind, isTainted) VALUES('jovial', 'name', 1);
|
||||
""")
|
||||
|
||||
struct Vocabulary: Decodable, MutablePersistableRecord, FetchableRecord {
|
||||
var word: String
|
||||
var kind: String
|
||||
var isTainted: Bool
|
||||
var count: Int?
|
||||
var rowID: Int64?
|
||||
|
||||
func encode(to container: inout PersistenceContainer) {
|
||||
// Don't encode count and rowID
|
||||
container["word"] = word
|
||||
container["kind"] = kind
|
||||
container["isTainted"] = isTainted
|
||||
}
|
||||
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
rowID = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
// No column specified, no unique index specified
|
||||
do {
|
||||
var vocabulary = Vocabulary(word: "jovial", kind: "ambiguous", isTainted: true)
|
||||
let upserted = try vocabulary.upsertAndFetch(db, updating: .noColumnUnlessSpecified)
|
||||
|
||||
// Test didSave
|
||||
XCTAssertEqual(vocabulary.rowID, 1)
|
||||
|
||||
// Test SQL
|
||||
// Note that something is updated, so that we have
|
||||
// something to return. See <https://sqlite.org/forum/forumpost/1ead75e2c45de9a5>
|
||||
XCTAssertEqual(lastSQLQuery, """
|
||||
INSERT INTO "vocabulary" ("word", "kind", "isTainted") \
|
||||
VALUES ('jovial','ambiguous',1) \
|
||||
ON CONFLICT DO UPDATE SET "word" = "word" \
|
||||
RETURNING *, "rowid"
|
||||
""")
|
||||
|
||||
// Test database state
|
||||
let rows = try Row.fetchAll(db, sql: "SELECT * FROM vocabulary")
|
||||
XCTAssertEqual(rows, [
|
||||
["word": "jovial", "kind": "name", "isTainted": 1, "count": 1],
|
||||
])
|
||||
|
||||
// Test upserted record
|
||||
XCTAssertEqual(upserted.word, "jovial")
|
||||
XCTAssertEqual(upserted.kind, "name")
|
||||
XCTAssertEqual(upserted.isTainted, true)
|
||||
XCTAssertEqual(upserted.count, 1)
|
||||
}
|
||||
|
||||
do {
|
||||
var vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false)
|
||||
let upserted = try vocabulary.upsertAndFetch(
|
||||
db, onConflict: ["word"],
|
||||
updating: .noColumnUnlessSpecified,
|
||||
doUpdate: { excluded in
|
||||
[Column("count") += 1, // increment count
|
||||
Column("kind").set(to: excluded["kind"])] // overwrite kind
|
||||
})
|
||||
|
||||
// Test didSave
|
||||
XCTAssertEqual(vocabulary.rowID, 1)
|
||||
|
||||
// Test SQL
|
||||
XCTAssertEqual(lastSQLQuery, """
|
||||
INSERT INTO "vocabulary" ("word", "kind", "isTainted") \
|
||||
VALUES ('jovial','adjective',0) \
|
||||
ON CONFLICT("word") \
|
||||
DO UPDATE SET "count" = "count" + 1, "kind" = "excluded"."kind" \
|
||||
RETURNING *, "rowid"
|
||||
""")
|
||||
|
||||
// Test database state
|
||||
let rows = try Row.fetchAll(db, sql: "SELECT * FROM vocabulary")
|
||||
XCTAssertEqual(rows, [
|
||||
["word": "jovial", "kind": "adjective", "isTainted": 1, "count": 2],
|
||||
])
|
||||
|
||||
// Test upserted record
|
||||
XCTAssertEqual(upserted.word, "jovial")
|
||||
XCTAssertEqual(upserted.kind, "adjective")
|
||||
XCTAssertEqual(upserted.isTainted, true) // Not overwritten
|
||||
XCTAssertEqual(upserted.count, 2) // incremented
|
||||
}
|
||||
|
||||
// All columns with no assignment: make sure we return something
|
||||
do {
|
||||
var vocabulary = Vocabulary(word: "jovial", kind: "ignored", isTainted: false)
|
||||
let upserted = try vocabulary.upsertAndFetch(
|
||||
db, onConflict: ["word"],
|
||||
updating: .noColumnUnlessSpecified,
|
||||
doUpdate: { _ in
|
||||
[]
|
||||
})
|
||||
|
||||
// Test didSave
|
||||
XCTAssertEqual(vocabulary.rowID, 1)
|
||||
|
||||
// Test SQL (the DO UPDATE clause is not empty, so that the
|
||||
// RETURNING clause could return something).
|
||||
XCTAssertEqual(lastSQLQuery, """
|
||||
INSERT INTO "vocabulary" ("word", "kind", "isTainted") \
|
||||
VALUES ('jovial','ignored',0) \
|
||||
ON CONFLICT("word") \
|
||||
DO UPDATE SET "word" = "word" \
|
||||
RETURNING *, "rowid"
|
||||
""")
|
||||
|
||||
// Test database state
|
||||
let rows = try Row.fetchAll(db, sql: "SELECT * FROM vocabulary")
|
||||
XCTAssertEqual(rows, [
|
||||
["word": "jovial", "kind": "adjective", "isTainted": 1, "count": 2],
|
||||
])
|
||||
|
||||
// Test upserted record
|
||||
XCTAssertEqual(upserted.word, "jovial")
|
||||
XCTAssertEqual(upserted.kind, "adjective")
|
||||
XCTAssertEqual(upserted.isTainted, true)
|
||||
XCTAssertEqual(upserted.count, 2)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE phonebook(name TEXT PRIMARY KEY, phonenumber TEXT);
|
||||
INSERT INTO phonebook(name,phonenumber) VALUES('Alice','ignored');
|
||||
""")
|
||||
|
||||
struct Phonebook: Codable, MutablePersistableRecord, FetchableRecord {
|
||||
var name: String
|
||||
var phonenumber: String
|
||||
}
|
||||
|
||||
var phonebook = Phonebook(name: "Alice", phonenumber: "704-555-1212")
|
||||
let upserted = try phonebook.upsertAndFetch(
|
||||
db, onConflict: ["name"],
|
||||
updating: .noColumnUnlessSpecified,
|
||||
doUpdate: { excluded in
|
||||
[Column("phonenumber").set(to: excluded["phonenumber"])]
|
||||
})
|
||||
|
||||
// Test SQL
|
||||
XCTAssertEqual(lastSQLQuery, """
|
||||
INSERT INTO "phonebook" ("name", "phonenumber") \
|
||||
VALUES ('Alice','704-555-1212') \
|
||||
ON CONFLICT("name") DO UPDATE SET "phonenumber" = "excluded"."phonenumber" \
|
||||
RETURNING *, "rowid"
|
||||
""")
|
||||
|
||||
// Test database state
|
||||
let rows = try Row.fetchAll(db, sql: "SELECT * FROM phonebook")
|
||||
XCTAssertEqual(rows, [
|
||||
["name": "Alice", "phonenumber": "704-555-1212"],
|
||||
])
|
||||
|
||||
// Test upserted record
|
||||
XCTAssertEqual(upserted.name, "Alice")
|
||||
XCTAssertEqual(upserted.phonenumber, "704-555-1212")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_upsertAndFetch() throws {
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
guard Database.sqliteLibVersionNumber >= 3035000 else {
|
||||
|
||||
@@ -2324,7 +2324,7 @@ extension PersistableRecordTests {
|
||||
}
|
||||
}
|
||||
|
||||
func test_upsertAndFetch_do_update_set_where() throws {
|
||||
func test_upsertAndFetch_do_update_set_where_with_default_strategy() throws {
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
guard Database.sqliteLibVersionNumber >= 3035000 else {
|
||||
throw XCTSkip("UPSERT is not available")
|
||||
@@ -2341,10 +2341,10 @@ extension PersistableRecordTests {
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE vocabulary(
|
||||
word TEXT PRIMARY KEY,
|
||||
kind TEXT,
|
||||
kind TEXT NOT NULL,
|
||||
isTainted BOOLEAN DEFAULT 0,
|
||||
count INT DEFAULT 1);
|
||||
INSERT INTO vocabulary(word, isTainted) VALUES('jovial', 1);
|
||||
INSERT INTO vocabulary(word, kind, isTainted) VALUES('jovial', 'name', 1);
|
||||
""")
|
||||
|
||||
struct Vocabulary: Decodable, PersistableRecord, FetchableRecord {
|
||||
@@ -2361,6 +2361,33 @@ extension PersistableRecordTests {
|
||||
}
|
||||
}
|
||||
|
||||
// No column specified, no unique index specified
|
||||
do {
|
||||
let vocabulary = Vocabulary(word: "jovial", kind: "ambiguous", isTainted: true)
|
||||
let upserted = try vocabulary.upsertAndFetch(db)
|
||||
|
||||
// Test SQL
|
||||
XCTAssertEqual(lastSQLQuery, """
|
||||
INSERT INTO "vocabulary" ("word", "kind", "isTainted") \
|
||||
VALUES ('jovial','ambiguous',1) \
|
||||
ON CONFLICT \
|
||||
DO UPDATE SET "kind" = "excluded"."kind", "isTainted" = "excluded"."isTainted" \
|
||||
RETURNING *, "rowid"
|
||||
""")
|
||||
|
||||
// Test database state
|
||||
let rows = try Row.fetchAll(db, sql: "SELECT * FROM vocabulary")
|
||||
XCTAssertEqual(rows, [
|
||||
["word": "jovial", "kind": "ambiguous", "isTainted": 1, "count": 1],
|
||||
])
|
||||
|
||||
// Test upserted record
|
||||
XCTAssertEqual(upserted.word, "jovial")
|
||||
XCTAssertEqual(upserted.kind, "ambiguous")
|
||||
XCTAssertEqual(upserted.isTainted, true)
|
||||
XCTAssertEqual(upserted.count, 1)
|
||||
}
|
||||
|
||||
// One column with specific assignment (count)
|
||||
// One column with no assignment (isTainted)
|
||||
// One column with default overwrite assignment (kind)
|
||||
@@ -2469,6 +2496,152 @@ extension PersistableRecordTests {
|
||||
}
|
||||
}
|
||||
|
||||
func test_upsertAndFetch_do_update_set_where_with_noColumnUnlessSpecified_strategy() throws {
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
guard Database.sqliteLibVersionNumber >= 3035000 else {
|
||||
throw XCTSkip("UPSERT is not available")
|
||||
}
|
||||
#else
|
||||
guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
|
||||
throw XCTSkip("UPSERT is not available")
|
||||
}
|
||||
#endif
|
||||
|
||||
try makeDatabaseQueue().write { db in
|
||||
// Test exemples of https://www.sqlite.org/lang_UPSERT.html
|
||||
do {
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE vocabulary(
|
||||
word TEXT PRIMARY KEY,
|
||||
kind TEXT NOT NULL,
|
||||
isTainted BOOLEAN DEFAULT 0,
|
||||
count INT DEFAULT 1);
|
||||
INSERT INTO vocabulary(word, kind, isTainted) VALUES('jovial', 'name', 1);
|
||||
""")
|
||||
|
||||
struct Vocabulary: Decodable, PersistableRecord, FetchableRecord {
|
||||
var word: String
|
||||
var kind: String
|
||||
var isTainted: Bool
|
||||
var count: Int?
|
||||
|
||||
func encode(to container: inout PersistenceContainer) {
|
||||
// Don't encode count
|
||||
container["word"] = word
|
||||
container["kind"] = kind
|
||||
container["isTainted"] = isTainted
|
||||
}
|
||||
}
|
||||
|
||||
// One column with specific assignment (count)
|
||||
// One column with no assignment (isTainted)
|
||||
// One column with default overwrite assignment (kind)
|
||||
do {
|
||||
let vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false)
|
||||
let upserted = try vocabulary.upsertAndFetch(
|
||||
db, onConflict: ["word"],
|
||||
updating: .noColumnUnlessSpecified,
|
||||
doUpdate: { excluded in
|
||||
[Column("count") += 1, // increment count
|
||||
Column("kind").set(to: excluded["kind"])] // overwrite kind
|
||||
})
|
||||
|
||||
// Test SQL
|
||||
XCTAssertEqual(lastSQLQuery, """
|
||||
INSERT INTO "vocabulary" ("word", "kind", "isTainted") \
|
||||
VALUES ('jovial','adjective',0) \
|
||||
ON CONFLICT("word") \
|
||||
DO UPDATE SET "count" = "count" + 1, "kind" = "excluded"."kind" \
|
||||
RETURNING *, "rowid"
|
||||
""")
|
||||
|
||||
// Test database state
|
||||
let rows = try Row.fetchAll(db, sql: "SELECT * FROM vocabulary")
|
||||
XCTAssertEqual(rows, [
|
||||
["word": "jovial", "kind": "adjective", "isTainted": 1, "count": 2],
|
||||
])
|
||||
|
||||
// Test upserted record
|
||||
XCTAssertEqual(upserted.word, "jovial")
|
||||
XCTAssertEqual(upserted.kind, "adjective")
|
||||
XCTAssertEqual(upserted.isTainted, true) // Not overwritten
|
||||
XCTAssertEqual(upserted.count, 2) // incremented
|
||||
}
|
||||
|
||||
// All columns with no assignment: make sure we return something
|
||||
do {
|
||||
let vocabulary = Vocabulary(word: "jovial", kind: "ignored", isTainted: false)
|
||||
let upserted = try vocabulary.upsertAndFetch(
|
||||
db, onConflict: ["word"],
|
||||
updating: .noColumnUnlessSpecified,
|
||||
doUpdate: { _ in
|
||||
[]
|
||||
})
|
||||
|
||||
// Test SQL (the DO UPDATE clause is not empty, so that the
|
||||
// RETURNING clause could return something).
|
||||
XCTAssertEqual(lastSQLQuery, """
|
||||
INSERT INTO "vocabulary" ("word", "kind", "isTainted") \
|
||||
VALUES ('jovial','ignored',0) \
|
||||
ON CONFLICT("word") \
|
||||
DO UPDATE SET "word" = "word" \
|
||||
RETURNING *, "rowid"
|
||||
""")
|
||||
|
||||
// Test database state
|
||||
let rows = try Row.fetchAll(db, sql: "SELECT * FROM vocabulary")
|
||||
XCTAssertEqual(rows, [
|
||||
["word": "jovial", "kind": "adjective", "isTainted": 1, "count": 2],
|
||||
])
|
||||
|
||||
// Test upserted record
|
||||
XCTAssertEqual(upserted.word, "jovial")
|
||||
XCTAssertEqual(upserted.kind, "adjective")
|
||||
XCTAssertEqual(upserted.isTainted, true)
|
||||
XCTAssertEqual(upserted.count, 2)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE phonebook(name TEXT PRIMARY KEY, phonenumber TEXT);
|
||||
INSERT INTO phonebook(name,phonenumber) VALUES('Alice','ignored');
|
||||
""")
|
||||
|
||||
struct Phonebook: Codable, PersistableRecord, FetchableRecord {
|
||||
var name: String
|
||||
var phonenumber: String
|
||||
}
|
||||
|
||||
let phonebook = Phonebook(name: "Alice", phonenumber: "704-555-1212")
|
||||
let upserted = try phonebook.upsertAndFetch(
|
||||
db, onConflict: ["name"],
|
||||
updating: .noColumnUnlessSpecified,
|
||||
doUpdate: { excluded in
|
||||
[Column("phonenumber").set(to: excluded["phonenumber"])]
|
||||
})
|
||||
|
||||
// Test SQL
|
||||
XCTAssertEqual(lastSQLQuery, """
|
||||
INSERT INTO "phonebook" ("name", "phonenumber") \
|
||||
VALUES ('Alice','704-555-1212') \
|
||||
ON CONFLICT("name") DO UPDATE SET "phonenumber" = "excluded"."phonenumber" \
|
||||
RETURNING *, "rowid"
|
||||
""")
|
||||
|
||||
// Test database state
|
||||
let rows = try Row.fetchAll(db, sql: "SELECT * FROM phonebook")
|
||||
XCTAssertEqual(rows, [
|
||||
["name": "Alice", "phonenumber": "704-555-1212"],
|
||||
])
|
||||
|
||||
// Test upserted record
|
||||
XCTAssertEqual(upserted.name, "Alice")
|
||||
XCTAssertEqual(upserted.phonenumber, "704-555-1212")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_upsertAndFetch() throws {
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
guard Database.sqliteLibVersionNumber >= 3035000 else {
|
||||
@@ -2623,4 +2796,92 @@ extension PersistableRecordTests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_UpsertUpdateStrategy_documentation() throws {
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
guard Database.sqliteLibVersionNumber >= 3035000 else {
|
||||
throw XCTSkip("UPSERT is not available")
|
||||
}
|
||||
#else
|
||||
guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
|
||||
throw XCTSkip("UPSERT is not available")
|
||||
}
|
||||
#endif
|
||||
|
||||
struct Player: Codable, FetchableRecord, PersistableRecord {
|
||||
static let databaseTableName = "other_player"
|
||||
var id: Int64 // The primary key
|
||||
var name: String
|
||||
var score: Int
|
||||
var bestScore: Int
|
||||
}
|
||||
|
||||
try makeDatabaseQueue().write { db in
|
||||
try db.create(table: "other_player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
t.column("bestScore", .integer).notNull()
|
||||
}
|
||||
try Player(id: 1, name: "Arthur", score: 100, bestScore: 200).insert(db)
|
||||
|
||||
try db.inSavepoint {
|
||||
let player = Player(id: 1, name: "Barbara", score: 200, bestScore: 0)
|
||||
let upsertedPlayer = try player.upsertAndFetch(db, updating: .allColumns)
|
||||
XCTAssertEqual(upsertedPlayer.name, "Barbara")
|
||||
XCTAssertEqual(upsertedPlayer.score, 200)
|
||||
XCTAssertEqual(upsertedPlayer.bestScore, 0)
|
||||
return .rollback
|
||||
}
|
||||
|
||||
try db.inSavepoint {
|
||||
let player = Player(id: 1, name: "Barbara", score: 200, bestScore: 0)
|
||||
let upsertedPlayer = try player.upsertAndFetch(db, updating: .allColumns) { excluded in
|
||||
let bestScore = Column("bestScore")
|
||||
return [
|
||||
bestScore.set(to: max(bestScore, excluded[bestScore])),
|
||||
]
|
||||
}
|
||||
XCTAssertEqual(upsertedPlayer.name, "Barbara")
|
||||
XCTAssertEqual(upsertedPlayer.score, 200)
|
||||
XCTAssertEqual(upsertedPlayer.bestScore, 200)
|
||||
return .rollback
|
||||
}
|
||||
|
||||
try db.inSavepoint {
|
||||
let player = Player(id: 1, name: "Barbara", score: 200, bestScore: 1000)
|
||||
let upsertedPlayer = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified)
|
||||
XCTAssertEqual(upsertedPlayer.name, "Arthur")
|
||||
XCTAssertEqual(upsertedPlayer.score, 100)
|
||||
XCTAssertEqual(upsertedPlayer.bestScore, 200)
|
||||
return .rollback
|
||||
}
|
||||
|
||||
try db.inSavepoint {
|
||||
let player = Player(id: 1, name: "Barbara", score: 200, bestScore: 1000)
|
||||
let upsertedPlayer = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified) { excluded in
|
||||
let name = Column("name")
|
||||
return [name.set(to: excluded[name])]
|
||||
}
|
||||
XCTAssertEqual(upsertedPlayer.name, "Barbara")
|
||||
XCTAssertEqual(upsertedPlayer.score, 100)
|
||||
XCTAssertEqual(upsertedPlayer.bestScore, 200)
|
||||
return .rollback
|
||||
}
|
||||
|
||||
try db.inSavepoint {
|
||||
let player = Player(id: 1, name: "Barbara", score: 200, bestScore: 1000)
|
||||
let upsertedPlayer = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified) { excluded in
|
||||
let bestScore = Column("bestScore")
|
||||
return [
|
||||
bestScore.set(to: max(bestScore, excluded[bestScore])),
|
||||
]
|
||||
}
|
||||
XCTAssertEqual(upsertedPlayer.name, "Arthur")
|
||||
XCTAssertEqual(upsertedPlayer.score, 100)
|
||||
XCTAssertEqual(upsertedPlayer.bestScore, 1000)
|
||||
return .rollback
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
|
||||
#warning("TODO: document the caveat that didInsert(with:) is unreliable due to last insert rowid not set by triggers: https://sqlite.org/c3ref/last_insert_rowid.html. See also https://sqlite.org/forum/forumpost/fb1c3b4a13")
|
||||
private struct Player: Codable,
|
||||
Equatable,
|
||||
Identifiable,
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
@@ -598,7 +598,6 @@ class TableRecordUpdateTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
func testRequestUpdateAndFetchCursor_view() throws {
|
||||
#warning("TODO: document this caveat")
|
||||
// Mixing INSTEAD OF triggers and RETURNING used to trigger a bug
|
||||
// that was fixed in SQLite 3.42. The SQLite test linked below
|
||||
// landed on 2023-03-28, and SQLite 3.42 shipped on 2023-05-16.
|
||||
|
||||
@@ -4,8 +4,8 @@ import SQLCipher
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
Binary file not shown.
Reference in new issue
Block a user