mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-06 05:28:44 +00:00
Compare commits
47
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 | ||
|
|
3dd3bbf0c5 | ||
|
|
d7cf0f9e59 | ||
|
|
389c3e0d4a | ||
|
|
a212bf9e89 | ||
|
|
65186104cc | ||
|
|
2f108508fa | ||
|
|
5513eab099 | ||
|
|
2ad2d20a89 | ||
|
|
dd90fe6e62 | ||
|
|
691207567a | ||
|
|
c7f1dd7470 | ||
|
|
8e5b9ca9bd | ||
|
|
dc7d47c066 | ||
|
|
14f60ad48f | ||
|
|
e758fde941 | ||
|
|
7477e1cff8 | ||
|
|
2d6fe172c3 | ||
|
|
0526853dde |
No files matched your search
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"editor.formatOnSave": false,
|
||||
"editor.insertSpaces": true,
|
||||
"editor.tabSize": 4,
|
||||
"editor.detectIndentation": false,
|
||||
"editor.trimAutoWhitespace": false
|
||||
}
|
||||
@@ -7,6 +7,7 @@ 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)
|
||||
@@ -141,6 +142,16 @@ 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
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '7.9.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.'
|
||||
|
||||
@@ -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
|
||||
|
||||
+4
-123
@@ -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).
|
||||
@@ -1852,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
|
||||
@@ -2003,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
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
#if os(Linux)
|
||||
@preconcurrency import Dispatch
|
||||
#else
|
||||
import Dispatch
|
||||
#endif
|
||||
|
||||
/// An actor that runs in a DispatchQueue.
|
||||
///
|
||||
@@ -44,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)) }
|
||||
}()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
#if canImport(CoreGraphics)
|
||||
import CoreGraphics
|
||||
#elseif !canImport(Darwin)
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
/// CGFloat adopts DatabaseValueConvertible
|
||||
extension CGFloat: DatabaseValueConvertible {
|
||||
@@ -15,4 +18,3 @@ extension CGFloat: DatabaseValueConvertible {
|
||||
return CGFloat(double)
|
||||
}
|
||||
}
|
||||
#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,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(Linux)
|
||||
/// NSDate is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
extension NSDate: DatabaseValueConvertible {
|
||||
@@ -41,7 +40,6 @@ extension NSDate: DatabaseValueConvertible {
|
||||
return cast(date)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Date is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
#if !os(Linux)
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
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
|
||||
@@ -68,4 +67,3 @@ extension Decimal: StatementColumnConvertible {
|
||||
|
||||
@usableFromInline
|
||||
let _posixLocale = Locale(identifier: "en_US_POSIX")
|
||||
#endif
|
||||
@@ -1,4 +1,3 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// NSData is convertible to and from DatabaseValue.
|
||||
@@ -24,4 +23,3 @@ extension NSData: DatabaseValueConvertible {
|
||||
return cast(data)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,4 +1,3 @@
|
||||
#if !os(Linux) && !os(Windows)
|
||||
import Foundation
|
||||
|
||||
private let integerRoundingBehavior = NSDecimalNumberHandler(
|
||||
@@ -81,10 +80,18 @@ extension NSNumber: DatabaseValueConvertible {
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64) where self is NSDecimalNumber.Type:
|
||||
let number = NSDecimalNumber(value: int64)
|
||||
return number as? Self
|
||||
case .int64(let int64):
|
||||
return self.init(value: int64)
|
||||
let number = NSNumber(value: int64)
|
||||
return number as? Self
|
||||
case .double(let double) where self is NSDecimalNumber.Type:
|
||||
let number = NSDecimalNumber(value: double)
|
||||
return number as? Self
|
||||
case .double(let double):
|
||||
return self.init(value: double)
|
||||
let number = NSNumber(value: double)
|
||||
return number as? Self
|
||||
case let .string(string):
|
||||
// Must match Decimal.fromDatabaseValue(_:)
|
||||
guard let decimal = Decimal(string: string, locale: posixLocale) else { return nil }
|
||||
@@ -96,4 +103,3 @@ extension NSNumber: DatabaseValueConvertible {
|
||||
}
|
||||
|
||||
private let posixLocale = Locale(identifier: "en_US_POSIX")
|
||||
#endif
|
||||
@@ -1,4 +1,3 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// NSString adopts DatabaseValueConvertible
|
||||
@@ -24,4 +23,3 @@ extension NSString: DatabaseValueConvertible {
|
||||
return self.init(string: string)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,12 +1,15 @@
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux) && !os(Windows)
|
||||
/// NSURL stores its absoluteString in the database.
|
||||
extension NSURL: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a TEXT database value containing the absolute URL.
|
||||
public var databaseValue: DatabaseValue {
|
||||
absoluteString?.databaseValue ?? .null
|
||||
#if !canImport(Darwin)
|
||||
absoluteString.databaseValue
|
||||
#else
|
||||
absoluteString?.databaseValue ?? .null
|
||||
#endif
|
||||
}
|
||||
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
@@ -16,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(Linux) && !os(Windows)
|
||||
/// NSUUID adopts DatabaseValueConvertible
|
||||
extension NSUUID: DatabaseValueConvertible {
|
||||
/// Returns a BLOB database value containing the uuid bytes.
|
||||
@@ -36,16 +35,22 @@ extension NSUUID: DatabaseValueConvertible {
|
||||
switch dbValue.storage {
|
||||
case .blob(let data) where data.count == 16:
|
||||
return data.withUnsafeBytes {
|
||||
self.init(uuidBytes: $0.bindMemory(to: UInt8.self).baseAddress)
|
||||
#if canImport(Darwin)
|
||||
self.init(uuidBytes: $0.bindMemory(to: UInt8.self).baseAddress)
|
||||
#else
|
||||
guard let uuidBytes = $0.bindMemory(to: UInt8.self).baseAddress else {
|
||||
return nil as Self?
|
||||
}
|
||||
return NSUUID(uuidBytes: uuidBytes) as? Self
|
||||
#endif
|
||||
}
|
||||
case .string(let string):
|
||||
return self.init(uuidString: string)
|
||||
return NSUUID(uuidString: string) as? Self
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// UUID adopts DatabaseValueConvertible
|
||||
extension UUID: DatabaseValueConvertible {
|
||||
@@ -91,8 +96,8 @@ extension UUID: StatementColumnConvertible {
|
||||
self.init(uuid: uuid.uuid)
|
||||
case SQLITE_BLOB:
|
||||
guard sqlite3_column_bytes(sqliteStatement, index) == 16,
|
||||
let blob = sqlite3_column_blob(sqliteStatement, index) else
|
||||
{
|
||||
let blob = sqlite3_column_blob(sqliteStatement, index)
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
self.init(uuid: blob.assumingMemoryBound(to: uuid_t.self).pointee)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -15,6 +15,8 @@ let darwinPlatforms: [Platform] = [
|
||||
var swiftSettings: [SwiftSetting] = [
|
||||
.define("SQLITE_ENABLE_FTS5"),
|
||||
.define("SQLITE_ENABLE_SNAPSHOT"),
|
||||
// Not all Linux distributions have support for WAL snapshots.
|
||||
.define("SQLITE_DISABLE_SNAPSHOT", .when(platforms: [.linux])),
|
||||
]
|
||||
var cSettings: [CSetting] = []
|
||||
var dependencies: [PackageDescription.Package.Dependency] = []
|
||||
@@ -36,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
|
||||
@@ -46,19 +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"]),
|
||||
],
|
||||
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: [
|
||||
// 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")],
|
||||
@@ -85,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,7 +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>
|
||||
|
||||
**Latest release**: December 13, 2025 • [version 7.9.0](https://github.com/groue/GRDB.swift/tree/v7.9.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+
|
||||
|
||||
@@ -100,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)
|
||||
@@ -199,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 }
|
||||
|
||||
@@ -1652,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)
|
||||
}
|
||||
@@ -2210,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.
|
||||
|
||||
@@ -2220,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.
|
||||
|
||||
@@ -2268,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
|
||||
|
||||
@@ -4589,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 *
|
||||
}
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>7.9.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" }
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import XCTest
|
||||
import CoreGraphics
|
||||
import GRDB
|
||||
|
||||
#if canImport(CoreGraphics)
|
||||
import CoreGraphics
|
||||
#elseif !canImport(Darwin)
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
class CGFloatTests: GRDBTestCase {
|
||||
|
||||
func testCGFLoat() throws {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -216,6 +216,9 @@ class DatabaseErrorTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
func testNSErrorBridging() throws {
|
||||
#if !canImport(Darwin)
|
||||
throw XCTSkip("NSError bridging not available on non-Darwin platforms")
|
||||
#else
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "parents") { $0.column("id", .integer).primaryKey() }
|
||||
@@ -229,5 +232,6 @@ class DatabaseErrorTests: GRDBTestCase {
|
||||
XCTAssertNotNil(error.localizedFailureReason)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,9 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
}
|
||||
|
||||
func testEmptyMigratorSync() throws {
|
||||
#if !canImport(Combine)
|
||||
throw XCTSkip("Combine not supported on this platform")
|
||||
#else
|
||||
func test(writer: some DatabaseWriter) throws {
|
||||
let migrator = DatabaseMigrator()
|
||||
try migrator.migrate(writer)
|
||||
@@ -18,9 +21,13 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
try Test(test).run { try DatabaseQueue() }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
|
||||
#endif
|
||||
}
|
||||
|
||||
func testEmptyMigratorAsync() throws {
|
||||
#if !canImport(Combine)
|
||||
throw XCTSkip("Combine not supported on this platform")
|
||||
#else
|
||||
func test(writer: some DatabaseWriter) throws {
|
||||
let expectation = self.expectation(description: "")
|
||||
let migrator = DatabaseMigrator()
|
||||
@@ -38,9 +45,13 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
try Test(test).run { try DatabaseQueue() }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
|
||||
#endif
|
||||
}
|
||||
|
||||
func testEmptyMigratorPublisher() throws {
|
||||
#if !canImport(Combine)
|
||||
throw XCTSkip("Combine not supported on this platform")
|
||||
#else
|
||||
func test(writer: some DatabaseWriter) throws {
|
||||
let migrator = DatabaseMigrator()
|
||||
let publisher = migrator.migratePublisher(writer)
|
||||
@@ -51,9 +62,13 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
try Test(test).run { try DatabaseQueue() }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
|
||||
#endif
|
||||
}
|
||||
|
||||
func testNonEmptyMigratorSync() throws {
|
||||
#if !canImport(Combine)
|
||||
throw XCTSkip("Combine not supported on this platform")
|
||||
#else
|
||||
func test(writer: some DatabaseWriter) throws {
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.registerMigration("createPersons") { db in
|
||||
@@ -95,9 +110,13 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
try Test(test).run { try DatabaseQueue() }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
|
||||
#endif
|
||||
}
|
||||
|
||||
func testNonEmptyMigratorAsync() throws {
|
||||
#if !canImport(Combine)
|
||||
throw XCTSkip("Combine not supported on this platform")
|
||||
#else
|
||||
func test(writer: some DatabaseWriter) throws {
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.registerMigration("createPersons") { db in
|
||||
@@ -146,9 +165,13 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
try Test(test).run { try DatabaseQueue() }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
|
||||
#endif
|
||||
}
|
||||
|
||||
func testNonEmptyMigratorPublisher() throws {
|
||||
#if !canImport(Combine)
|
||||
throw XCTSkip("Combine not supported on this platform")
|
||||
#else
|
||||
func test(writer: some DatabaseWriter) throws {
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.registerMigration("createPersons") { db in
|
||||
@@ -198,9 +221,13 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
try Test(test).run { try DatabaseQueue() }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
|
||||
#endif
|
||||
}
|
||||
|
||||
func testEmptyMigratorPublisherIsAsynchronous() throws {
|
||||
#if !canImport(Combine)
|
||||
throw XCTSkip("Combine not supported on this platform")
|
||||
#else
|
||||
func test(writer: some DatabaseWriter) throws {
|
||||
let migrator = DatabaseMigrator()
|
||||
let expectation = self.expectation(description: "")
|
||||
@@ -220,9 +247,13 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
try Test(test).run { try DatabaseQueue() }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
|
||||
#endif
|
||||
}
|
||||
|
||||
func testNonEmptyMigratorPublisherIsAsynchronous() throws {
|
||||
#if !canImport(Combine)
|
||||
throw XCTSkip("Combine not supported on this platform")
|
||||
#else
|
||||
func test(writer: some DatabaseWriter) throws {
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.registerMigration("first", migrate: { _ in })
|
||||
@@ -243,9 +274,13 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
try Test(test).run { try DatabaseQueue() }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
|
||||
#endif
|
||||
}
|
||||
|
||||
func testMigratorPublisherDefaultScheduler() throws {
|
||||
#if !canImport(Combine)
|
||||
throw XCTSkip("Combine not supported on this platform")
|
||||
#else
|
||||
func test<Writer: DatabaseWriter>(writer: Writer) {
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.registerMigration("first", migrate: { _ in })
|
||||
@@ -268,9 +303,13 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
try Test(test).run { try DatabaseQueue() }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
|
||||
#endif
|
||||
}
|
||||
|
||||
func testMigratorPublisherCustomScheduler() throws {
|
||||
#if !canImport(Combine)
|
||||
throw XCTSkip("Combine not supported on this platform")
|
||||
#else
|
||||
func test<Writer: DatabaseWriter>(writer: Writer) {
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.registerMigration("first", migrate: { _ in })
|
||||
@@ -294,9 +333,13 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
try Test(test).run { try DatabaseQueue() }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
|
||||
#endif
|
||||
}
|
||||
|
||||
func testMigrateUpTo() throws {
|
||||
#if !canImport(Combine)
|
||||
throw XCTSkip("Combine not supported on this platform")
|
||||
#else
|
||||
func test(writer: some DatabaseWriter) throws {
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.registerMigration("a") { db in
|
||||
@@ -345,6 +388,7 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
try Test(test).run { try DatabaseQueue() }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
|
||||
#endif
|
||||
}
|
||||
|
||||
func testMigrationFailureTriggersRollback() throws {
|
||||
|
||||
@@ -877,10 +877,12 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
XCTAssertEqual(db.configuration.label, nil)
|
||||
XCTAssertEqual(db.description, "GRDB.DatabasePool.writer")
|
||||
|
||||
#if canImport(Darwin)
|
||||
// This test CAN break in future releases: the dispatch queue labels
|
||||
// are documented to be a debug-only tool.
|
||||
let label = String(utf8String: __dispatch_queue_get_label(nil))
|
||||
XCTAssertEqual(label, "GRDB.DatabasePool.writer")
|
||||
#endif
|
||||
}
|
||||
|
||||
let s1 = DispatchSemaphore(value: 0)
|
||||
@@ -890,10 +892,12 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
XCTAssertEqual(db.configuration.label, nil)
|
||||
XCTAssertEqual(db.description, "GRDB.DatabasePool.reader.1")
|
||||
|
||||
#if canImport(Darwin)
|
||||
// This test CAN break in future releases: the dispatch queue labels
|
||||
// are documented to be a debug-only tool.
|
||||
let label = String(utf8String: __dispatch_queue_get_label(nil))
|
||||
XCTAssertEqual(label, "GRDB.DatabasePool.reader.1")
|
||||
#endif
|
||||
|
||||
_ = s1.signal()
|
||||
_ = s2.wait(timeout: .distantFuture)
|
||||
@@ -906,10 +910,12 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
XCTAssertEqual(db.configuration.label, nil)
|
||||
XCTAssertEqual(db.description, "GRDB.DatabasePool.reader.2")
|
||||
|
||||
#if canImport(Darwin)
|
||||
// This test CAN break in future releases: the dispatch queue labels
|
||||
// are documented to be a debug-only tool.
|
||||
let label = String(utf8String: __dispatch_queue_get_label(nil))
|
||||
XCTAssertEqual(label, "GRDB.DatabasePool.reader.2")
|
||||
#endif
|
||||
}
|
||||
}
|
||||
let blocks = [block1, block2]
|
||||
@@ -925,10 +931,12 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
XCTAssertEqual(db.configuration.label, "Toreador")
|
||||
XCTAssertEqual(db.description, "Toreador.writer")
|
||||
|
||||
#if canImport(Darwin)
|
||||
// This test CAN break in future releases: the dispatch queue labels
|
||||
// are documented to be a debug-only tool.
|
||||
let label = String(utf8String: __dispatch_queue_get_label(nil))
|
||||
XCTAssertEqual(label, "Toreador.writer")
|
||||
#endif
|
||||
}
|
||||
|
||||
let s1 = DispatchSemaphore(value: 0)
|
||||
@@ -938,10 +946,12 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
XCTAssertEqual(db.configuration.label, "Toreador")
|
||||
XCTAssertEqual(db.description, "Toreador.reader.1")
|
||||
|
||||
#if canImport(Darwin)
|
||||
// This test CAN break in future releases: the dispatch queue labels
|
||||
// are documented to be a debug-only tool.
|
||||
let label = String(utf8String: __dispatch_queue_get_label(nil))
|
||||
XCTAssertEqual(label, "Toreador.reader.1")
|
||||
#endif
|
||||
|
||||
_ = s1.signal()
|
||||
_ = s2.wait(timeout: .distantFuture)
|
||||
@@ -954,10 +964,12 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
XCTAssertEqual(db.configuration.label, "Toreador")
|
||||
XCTAssertEqual(db.description, "Toreador.reader.2")
|
||||
|
||||
#if canImport(Darwin)
|
||||
// This test CAN break in future releases: the dispatch queue labels
|
||||
// are documented to be a debug-only tool.
|
||||
let label = String(utf8String: __dispatch_queue_get_label(nil))
|
||||
XCTAssertEqual(label, "Toreador.reader.2")
|
||||
#endif
|
||||
}
|
||||
}
|
||||
let blocks = [block1, block2]
|
||||
@@ -1037,6 +1049,9 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
func testQoS() throws {
|
||||
#if !canImport(Darwin)
|
||||
throw XCTSkip("__dispatch_get_global_queue unavailable")
|
||||
#else
|
||||
func test(qos: DispatchQoS) throws {
|
||||
// https://forums.swift.org/t/what-is-the-default-target-queue-for-a-serial-queue/18094/5
|
||||
//
|
||||
@@ -1072,6 +1087,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
|
||||
try test(qos: .background)
|
||||
try test(qos: .userInitiated)
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - AsyncConcurrentRead
|
||||
@@ -1254,6 +1270,9 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
// MARK: - Concurrent opening
|
||||
|
||||
func testConcurrentOpening() throws {
|
||||
#if !canImport(Darwin)
|
||||
throw XCTSkip("NSFileCoordinator unavailable")
|
||||
#else
|
||||
for _ in 0..<50 {
|
||||
let dbDirectoryName = "DatabasePoolConcurrencyTests-\(ProcessInfo.processInfo.globallyUniqueString)"
|
||||
let directoryURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
|
||||
@@ -1277,6 +1296,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
XCTAssert(poolError ?? coordinatorError == nil)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - NSFileCoordinator sample code tests
|
||||
@@ -1284,6 +1304,9 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
// Test for sample code in Documentation.docc/DatabaseSharing.md.
|
||||
// This test passes if this method compiles
|
||||
private func openSharedDatabase(at databaseURL: URL) throws -> DatabasePool {
|
||||
#if !canImport(Darwin)
|
||||
throw XCTSkip("NSFileCoordinator unavailable")
|
||||
#else
|
||||
let coordinator = NSFileCoordinator(filePresenter: nil)
|
||||
var coordinatorError: NSError?
|
||||
var dbPool: DatabasePool?
|
||||
@@ -1299,6 +1322,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
throw error
|
||||
}
|
||||
return dbPool!
|
||||
#endif
|
||||
}
|
||||
|
||||
// Test for sample code in Documentation.docc/DatabaseSharing.md.
|
||||
@@ -1313,6 +1337,9 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
// Test for sample code in Documentation.docc/DatabaseSharing.md.
|
||||
// This test passes if this method compiles
|
||||
private func openSharedReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
|
||||
#if !canImport(Darwin)
|
||||
throw XCTSkip("NSFileCoordinator unavailable")
|
||||
#else
|
||||
let coordinator = NSFileCoordinator(filePresenter: nil)
|
||||
var coordinatorError: NSError?
|
||||
var dbPool: DatabasePool?
|
||||
@@ -1328,6 +1355,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
throw error
|
||||
}
|
||||
return dbPool
|
||||
#endif
|
||||
}
|
||||
|
||||
// Test for sample code in Documentation.docc/DatabaseSharing.md.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -129,10 +129,12 @@ class DatabaseQueueTests: GRDBTestCase {
|
||||
XCTAssertEqual(db.configuration.label, nil)
|
||||
XCTAssertEqual(db.description, "GRDB.DatabaseQueue")
|
||||
|
||||
#if canImport(Darwin)
|
||||
// This test CAN break in future releases: the dispatch queue labels
|
||||
// are documented to be a debug-only tool.
|
||||
let label = String(utf8String: __dispatch_queue_get_label(nil))
|
||||
XCTAssertEqual(label, "GRDB.DatabaseQueue")
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,10 +146,12 @@ class DatabaseQueueTests: GRDBTestCase {
|
||||
XCTAssertEqual(db.configuration.label, "Toreador")
|
||||
XCTAssertEqual(db.description, "Toreador")
|
||||
|
||||
#if canImport(Darwin)
|
||||
// This test CAN break in future releases: the dispatch queue labels
|
||||
// are documented to be a debug-only tool.
|
||||
let label = String(utf8String: __dispatch_queue_get_label(nil))
|
||||
XCTAssertEqual(label, "Toreador")
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,6 +225,9 @@ class DatabaseQueueTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
func testQoS() throws {
|
||||
#if !canImport(Darwin)
|
||||
throw XCTSkip("__dispatch_get_global_queue not available on non-Darwin platforms")
|
||||
#else
|
||||
func test(qos: DispatchQoS) throws {
|
||||
// https://forums.swift.org/t/what-is-the-default-target-queue-for-a-serial-queue/18094/5
|
||||
//
|
||||
@@ -256,6 +263,7 @@ class DatabaseQueueTests: GRDBTestCase {
|
||||
|
||||
try test(qos: .background)
|
||||
try test(qos: .userInitiated)
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - SQLITE_BUSY prevention
|
||||
|
||||
@@ -4,12 +4,14 @@ import GRDB
|
||||
class DatabaseRegionObservationTests: GRDBTestCase {
|
||||
// Test passes if it compiles.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1541>
|
||||
#if canImport(Combine)
|
||||
func testAnyDatabaseWriter(writer: any DatabaseWriter) throws {
|
||||
let observation = DatabaseRegionObservation(tracking: .fullDatabase)
|
||||
|
||||
_ = observation.start(in: writer, onError: { _ in }, onChange: { _ in })
|
||||
_ = observation.publisher(in: writer)
|
||||
}
|
||||
#endif
|
||||
|
||||
func testDatabaseRegionObservation_FullDatabase() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
@@ -230,10 +230,12 @@ class DatabaseSnapshotTests: GRDBTestCase {
|
||||
XCTAssertEqual(db.configuration.label, nil)
|
||||
XCTAssertEqual(db.description, "GRDB.DatabasePool.snapshot.1")
|
||||
|
||||
#if canImport(Darwin)
|
||||
// This test CAN break in future releases: the dispatch queue labels
|
||||
// are documented to be a debug-only tool.
|
||||
let label = String(utf8String: __dispatch_queue_get_label(nil))
|
||||
XCTAssertEqual(label, "GRDB.DatabasePool.snapshot.1")
|
||||
#endif
|
||||
}
|
||||
|
||||
let snapshot2 = try dbPool.makeSnapshot()
|
||||
@@ -241,10 +243,12 @@ class DatabaseSnapshotTests: GRDBTestCase {
|
||||
XCTAssertEqual(db.configuration.label, nil)
|
||||
XCTAssertEqual(db.description, "GRDB.DatabasePool.snapshot.2")
|
||||
|
||||
#if canImport(Darwin)
|
||||
// This test CAN break in future releases: the dispatch queue labels
|
||||
// are documented to be a debug-only tool.
|
||||
let label = String(utf8String: __dispatch_queue_get_label(nil))
|
||||
XCTAssertEqual(label, "GRDB.DatabasePool.snapshot.2")
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -257,10 +261,12 @@ class DatabaseSnapshotTests: GRDBTestCase {
|
||||
XCTAssertEqual(db.configuration.label, "Toreador")
|
||||
XCTAssertEqual(db.description, "Toreador.snapshot.1")
|
||||
|
||||
#if canImport(Darwin)
|
||||
// This test CAN break in future releases: the dispatch queue labels
|
||||
// are documented to be a debug-only tool.
|
||||
let label = String(utf8String: __dispatch_queue_get_label(nil))
|
||||
XCTAssertEqual(label, "Toreador.snapshot.1")
|
||||
#endif
|
||||
}
|
||||
|
||||
let snapshot2 = try dbPool.makeSnapshot()
|
||||
@@ -268,10 +274,12 @@ class DatabaseSnapshotTests: GRDBTestCase {
|
||||
XCTAssertEqual(db.configuration.label, "Toreador")
|
||||
XCTAssertEqual(db.description, "Toreador.snapshot.2")
|
||||
|
||||
#if canImport(Darwin)
|
||||
// This test CAN break in future releases: the dispatch queue labels
|
||||
// are documented to be a debug-only tool.
|
||||
let label = String(utf8String: __dispatch_queue_get_label(nil))
|
||||
XCTAssertEqual(label, "Toreador.snapshot.2")
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -1,3 +1,4 @@
|
||||
#if canImport(Darwin)
|
||||
// Inspired by https://github.com/groue/CombineExpectations
|
||||
import XCTest
|
||||
|
||||
@@ -207,3 +208,4 @@ class FailureTestCaseTests: FailureTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
#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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,3 +1,4 @@
|
||||
#if canImport(Darwin)
|
||||
import Dispatch
|
||||
import XCTest
|
||||
|
||||
@@ -781,3 +782,4 @@ class ValueObservationRecorderTests: FailureTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -926,6 +926,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
// MARK: - Async Await
|
||||
#if canImport(Combine)
|
||||
|
||||
func testAsyncAwait_values_prefix() async throws {
|
||||
func test(_ writer: some DatabaseWriter) async throws {
|
||||
@@ -1238,6 +1239,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
|
||||
}
|
||||
#endif
|
||||
|
||||
// Regression test for <https://github.com/groue/GRDB.swift/issues/1383>
|
||||
func testIssue1383() throws {
|
||||
|
||||
Binary file not shown.
Reference in new issue
Block a user