mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-30 04:28:44 +00:00
Merge branch 'development'
This commit is contained in:
commit
98ca653c6a
48 files changed
+940
-371
No files matched your search
@@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 5.x Releases
|
||||
|
||||
- `5.20.x` Releases - [5.20.0](#5200)
|
||||
- `5.19.x` Releases - [5.19.0](#5190)
|
||||
- `5.18.x` Releases - [5.18.0](#5180)
|
||||
- `5.17.x` Releases - [5.17.0](#5170)
|
||||
@@ -86,6 +87,17 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 5.20.0
|
||||
|
||||
Released February 1, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.19.0...v5.20.0)
|
||||
|
||||
- **Fixed**: Fixed a bug of `including(all:)` for composite foreign keys and limited requests.
|
||||
- **Fixed**: [#1162](https://github.com/groue/GRDB.swift/pull/1162) by [@groue](https://github.com/groue): Fix truncate optimization handling.
|
||||
- **New**: [#1160](https://github.com/groue/GRDB.swift/pull/1160) by [@groue](https://github.com/groue): Hide statement arguments by default.
|
||||
- **New**: [#1161](https://github.com/groue/GRDB.swift/pull/1160) by [@groue](https://github.com/groue): Target DispatchQueue for non-read-only database connections.
|
||||
- **Documentation Update**: The [Database Configuration](README.md#database-configuration) chapter explains how to opt in for public statement arguments in DEBUG builds.
|
||||
|
||||
|
||||
## 5.19.0
|
||||
|
||||
Released January 19, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.18.0...v5.19.0)
|
||||
|
||||
@@ -469,7 +469,7 @@ In the illustration below, the striped band shows the delay needed for the readi
|
||||
let snapshot = try dbPool.makeSnapshot()
|
||||
```
|
||||
|
||||
You can create as many snapshots as you need, regardless of the [maximum number of readers](../README.md#databasepool-configuration) in the pool. A snapshot database connection is closed when the snapshot is deinitialized.
|
||||
You can create as many snapshots as you need, regardless of the [maximum number of readers](../README.md#database-configuration) in the pool. A snapshot database connection is closed when the snapshot is deinitialized.
|
||||
|
||||
**A snapshot can be used from any thread.** It has the same [synchronous and asynchronous reading methods](#synchronous-and-asynchronous-database-accesses) as database queues and pools:
|
||||
|
||||
|
||||
@@ -304,7 +304,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.19/Structs/StatementArguments.html):
|
||||
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.20/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -587,7 +587,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.19/Structs/StatementArguments.html):
|
||||
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.20/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
|
||||
@@ -77,7 +77,7 @@ try dbQueue.read { db in
|
||||
}
|
||||
```
|
||||
|
||||
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.19/Structs/DatabaseMigrator.html) for more migrator methods.
|
||||
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.20/Structs/DatabaseMigrator.html) for more migrator methods.
|
||||
|
||||
|
||||
## The `eraseDatabaseOnSchemaChange` Option
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '5.19.0'
|
||||
s.version = '5.20.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import Foundation
|
||||
import Dispatch
|
||||
import Foundation
|
||||
|
||||
/// Configuration for a DatabaseQueue or DatabasePool.
|
||||
public struct Configuration {
|
||||
@@ -102,6 +102,52 @@ public struct Configuration {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public var observesSuspensionNotifications = false
|
||||
|
||||
/// If false (the default), statement arguments are not visible in the
|
||||
/// description of database errors and trace events, preventing sensitive
|
||||
/// information from leaking in unexpected places.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // Error: sensitive information is not printed when an error occurs:
|
||||
/// do {
|
||||
/// let email = "..." // sensitive information
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// print(error)
|
||||
/// }
|
||||
///
|
||||
/// // Trace: sensitive information is not printed when a statement is traced:
|
||||
/// db.trace { event in
|
||||
/// print(event)
|
||||
/// }
|
||||
/// let email = "..." // sensitive information
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
///
|
||||
/// For debugging purpose, you can set this flag to true, and get more
|
||||
/// precise database reports. It is your responsibility to prevent sensitive
|
||||
/// information from leaking in unexpected locations, so you should not set
|
||||
/// this flag in release builds (think about GDPR and other
|
||||
/// privacy-related rules):
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// #if DEBUG
|
||||
/// // Protect sensitive information by enabling verbose debugging in DEBUG builds only
|
||||
/// config.publicStatementArguments = true
|
||||
/// #endif
|
||||
///
|
||||
/// // The descriptions of trace events and errors now contain the
|
||||
/// // sensitive information:
|
||||
/// db.trace { event in
|
||||
/// print(event)
|
||||
/// }
|
||||
/// do {
|
||||
/// let email = "..."
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// print(error)
|
||||
/// }
|
||||
public var publicStatementArguments = false
|
||||
|
||||
// MARK: - Managing SQLite Connections
|
||||
|
||||
private var setups: [(Database) throws -> Void] = []
|
||||
@@ -202,19 +248,29 @@ public struct Configuration {
|
||||
/// Default: .default
|
||||
public var qos: DispatchQoS = .default
|
||||
|
||||
/// The target queue for all database accesses.
|
||||
/// A target queue for database accesses.
|
||||
///
|
||||
/// When you use a database pool, make sure the queue is concurrent. If
|
||||
/// it is serial, no concurrent database access can happen, and you may
|
||||
/// experience deadlocks.
|
||||
/// Database connections which are not read-only will prefer
|
||||
/// `writeTargetQueue` instead, if it is not nil.
|
||||
///
|
||||
/// When you use a database pool, make sure this queue is concurrent. This
|
||||
/// is because in a serial dispatch queue, no concurrent database access can
|
||||
/// happen, and you may experience deadlocks.
|
||||
///
|
||||
/// If the queue is nil, all database accesses happen in unspecified
|
||||
/// dispatch queues whose quality of service and label are determined by the
|
||||
/// `qos` and `label` Configuration properties.
|
||||
/// dispatch queues whose quality of service is determined by the
|
||||
/// `qos` property.
|
||||
///
|
||||
/// Default: nil
|
||||
public var targetQueue: DispatchQueue? = nil
|
||||
|
||||
/// The target queue for database connections which are not read-only.
|
||||
///
|
||||
/// If this queue is nil, writer connections are controlled by `targetQueue`.
|
||||
///
|
||||
/// Default: nil
|
||||
public var writeTargetQueue: DispatchQueue? = nil
|
||||
|
||||
// MARK: - Factory Configuration
|
||||
|
||||
/// Creates a factory configuration
|
||||
@@ -241,7 +297,15 @@ public struct Configuration {
|
||||
(self.label ?? defaultLabel) + (purpose.map { "." + $0 } ?? "")
|
||||
}
|
||||
|
||||
func makeDispatchQueue(label: String) -> DispatchQueue {
|
||||
func makeWriterDispatchQueue(label: String) -> DispatchQueue {
|
||||
if let targetQueue = writeTargetQueue ?? targetQueue {
|
||||
return DispatchQueue(label: label, target: targetQueue)
|
||||
} else {
|
||||
return DispatchQueue(label: label, qos: qos)
|
||||
}
|
||||
}
|
||||
|
||||
func makeReaderDispatchQueue(label: String) -> DispatchQueue {
|
||||
if let targetQueue = targetQueue {
|
||||
return DispatchQueue(label: label, target: targetQueue)
|
||||
} else {
|
||||
|
||||
@@ -542,21 +542,21 @@ public class SQLStatementCursor: Cursor {
|
||||
}
|
||||
|
||||
extension Database {
|
||||
/// Returns the authorizer that should be used during statement execution
|
||||
/// (this allows preventing the truncate optimization when there exists a
|
||||
/// transaction observer for row deletion).
|
||||
/// Makes sure statement can be executed, and prepares database observation.
|
||||
@usableFromInline
|
||||
func statementWillExecute(_ statement: Statement) throws -> StatementAuthorizer? {
|
||||
func statementWillExecute(_ statement: Statement) throws {
|
||||
// Two things must prevent the statement from executing: aborted
|
||||
// transactions, and database suspension.
|
||||
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
|
||||
try checkForSuspensionViolation(from: statement)
|
||||
|
||||
if _isRecordingSelectedRegion {
|
||||
_selectedRegion.formUnion(statement.databaseRegion)
|
||||
// Database observation: record what the statement is looking at.
|
||||
if isRecordingSelectedRegion {
|
||||
selectedRegion.formUnion(statement.databaseRegion)
|
||||
}
|
||||
|
||||
return observationBroker.statementWillExecute(statement)
|
||||
// Database observation: prepare transaction observers.
|
||||
observationBroker.statementWillExecute(statement)
|
||||
}
|
||||
|
||||
/// May throw a cancelled commit error, if a transaction observer cancels
|
||||
@@ -589,7 +589,8 @@ extension Database {
|
||||
resultCode: resultCode,
|
||||
message: lastErrorMessage,
|
||||
sql: statement.sql,
|
||||
arguments: statement.arguments)
|
||||
arguments: statement.arguments,
|
||||
publicStatementArguments: configuration.publicStatementArguments)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -639,4 +640,8 @@ struct StatementCache {
|
||||
mutating func remove(_ statement: Statement) {
|
||||
statements.removeFirst { $0.value === statement }
|
||||
}
|
||||
|
||||
mutating func removeAll(where shouldBeRemoved: (Statement) -> Bool) {
|
||||
statements = statements.filter { (_, statement) in !shouldBeRemoved(statement) }
|
||||
}
|
||||
}
|
||||
+89
-48
@@ -150,10 +150,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
lazy var internalStatementCache = StatementCache(database: self)
|
||||
lazy var publicStatementCache = StatementCache(database: self)
|
||||
|
||||
/// Statement authorizer. Use withAuthorizer(_:_:).
|
||||
fileprivate var _authorizer: StatementAuthorizer?
|
||||
|
||||
// Transaction observers management
|
||||
// Database observation
|
||||
lazy var authorizer = StatementAuthorizer(self)
|
||||
lazy var observationBroker = DatabaseObservationBroker(self)
|
||||
|
||||
/// The list of compile options used when building SQLite
|
||||
@@ -163,8 +161,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// If true, select statement execution is recorded.
|
||||
/// Use recordingSelectedRegion(_:), see `statementWillExecute(_:)`
|
||||
var _isRecordingSelectedRegion = false
|
||||
var _selectedRegion = DatabaseRegion()
|
||||
var isRecordingSelectedRegion = false
|
||||
var selectedRegion = DatabaseRegion()
|
||||
|
||||
/// Support for checkForAbortedTransaction()
|
||||
var isInsideTransactionBlock = false
|
||||
@@ -318,17 +316,16 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
//
|
||||
// - DatabaseCursorTests.testIssue583()
|
||||
// - http://sqlite.1065341.n5.nabble.com/Issue-report-sqlite3-set-authorizer-triggers-error-4-516-SQLITE-ABORT-ROLLBACK-during-statement-itern-td107972.html
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
let authorizerP = Unmanaged.passUnretained(authorizer).toOpaque()
|
||||
sqlite3_set_authorizer(
|
||||
sqliteConnection,
|
||||
{ (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer.unsafelyUnwrapped).takeUnretainedValue()
|
||||
guard let authorizer = db._authorizer else {
|
||||
return SQLITE_OK
|
||||
}
|
||||
return authorizer.authorize(actionCode, cString1, cString2, cString3, cString4)
|
||||
{ (authorizerP, actionCode, cString1, cString2, cString3, cString4) -> Int32 in
|
||||
Unmanaged<StatementAuthorizer>
|
||||
.fromOpaque(authorizerP.unsafelyUnwrapped)
|
||||
.takeUnretainedValue()
|
||||
.authorize(actionCode, cString1, cString2, cString3, cString4)
|
||||
},
|
||||
dbPointer)
|
||||
authorizerP)
|
||||
}
|
||||
|
||||
|
||||
@@ -581,17 +578,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Authorizer
|
||||
|
||||
@usableFromInline
|
||||
func withAuthorizer<T>(_ authorizer: StatementAuthorizer?, _ block: () throws -> T) rethrows -> T {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
let old = self._authorizer
|
||||
self._authorizer = authorizer
|
||||
defer { self._authorizer = old }
|
||||
return try block()
|
||||
}
|
||||
|
||||
// MARK: - Recording of the selected region
|
||||
|
||||
func recordingSelection<T>(_ region: inout DatabaseRegion, _ block: () throws -> T) rethrows -> T {
|
||||
@@ -599,17 +585,17 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
return try block()
|
||||
}
|
||||
|
||||
let oldFlag = self._isRecordingSelectedRegion
|
||||
let oldRegion = self._selectedRegion
|
||||
_isRecordingSelectedRegion = true
|
||||
_selectedRegion = DatabaseRegion()
|
||||
let oldFlag = self.isRecordingSelectedRegion
|
||||
let oldRegion = self.selectedRegion
|
||||
isRecordingSelectedRegion = true
|
||||
selectedRegion = DatabaseRegion()
|
||||
defer {
|
||||
region.formUnion(_selectedRegion)
|
||||
_isRecordingSelectedRegion = oldFlag
|
||||
if _isRecordingSelectedRegion {
|
||||
_selectedRegion = oldRegion.union(_selectedRegion)
|
||||
region.formUnion(selectedRegion)
|
||||
isRecordingSelectedRegion = oldFlag
|
||||
if isRecordingSelectedRegion {
|
||||
selectedRegion = oldRegion.union(selectedRegion)
|
||||
} else {
|
||||
_selectedRegion = oldRegion
|
||||
selectedRegion = oldRegion
|
||||
}
|
||||
}
|
||||
return try block()
|
||||
@@ -713,7 +699,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
impl: .trace_v2(
|
||||
sqliteStatement: OpaquePointer(sqliteStatement),
|
||||
unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)),
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql))
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql,
|
||||
publicStatementArguments: configuration.publicStatementArguments))
|
||||
trace(TraceEvent.statement(statement))
|
||||
}
|
||||
case SQLITE_TRACE_PROFILE:
|
||||
@@ -722,7 +709,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
impl: .trace_v2(
|
||||
sqliteStatement: OpaquePointer(sqliteStatement),
|
||||
unexpandedSQL: nil,
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql))
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql,
|
||||
publicStatementArguments: configuration.publicStatementArguments))
|
||||
let duration = TimeInterval(durationP.pointee) / 1.0e9
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
|
||||
@@ -897,7 +885,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
resultCode: .SQLITE_ABORT,
|
||||
message: "Database is suspended",
|
||||
sql: statement.sql,
|
||||
arguments: statement.arguments)
|
||||
arguments: statement.arguments,
|
||||
publicStatementArguments: configuration.publicStatementArguments)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -930,7 +919,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
resultCode: .SQLITE_ABORT,
|
||||
message: "Transaction was aborted",
|
||||
sql: sql(),
|
||||
arguments: arguments())
|
||||
arguments: arguments(),
|
||||
publicStatementArguments: configuration.publicStatementArguments)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1642,22 +1632,23 @@ extension Database {
|
||||
public enum TraceEvent: CustomStringConvertible {
|
||||
|
||||
/// Information about a statement reported by `Database.trace(options:_:)`
|
||||
public struct Statement {
|
||||
public struct Statement: CustomStringConvertible {
|
||||
enum Impl {
|
||||
case trace_v1(String)
|
||||
case trace_v2(
|
||||
sqliteStatement: SQLiteStatement,
|
||||
unexpandedSQL: UnsafePointer<CChar>?,
|
||||
sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
|
||||
sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?,
|
||||
publicStatementArguments: Bool) // See Configuration.publicStatementArguments
|
||||
}
|
||||
let impl: Impl
|
||||
var impl: Impl
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
|
||||
/// The executed SQL, where bound parameters are not expanded.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// UPDATE player SET score = ? WHERE id = ?
|
||||
/// SELECT * FROM player WHERE email = ?
|
||||
public var sql: String { _sql }
|
||||
#elseif os(Linux)
|
||||
#else
|
||||
@@ -1665,7 +1656,7 @@ extension Database {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// UPDATE player SET score = ? WHERE id = ?
|
||||
/// SELECT * FROM player WHERE email = ?
|
||||
@available(OSX 10.12, tvOS 10.0, watchOS 3.0, *)
|
||||
public var sql: String { _sql }
|
||||
#endif
|
||||
@@ -1673,10 +1664,10 @@ extension Database {
|
||||
var _sql: String {
|
||||
switch impl {
|
||||
case .trace_v1:
|
||||
// Likely a GRDB bug
|
||||
fatalError("Not get statement SQL")
|
||||
// Likely a GRDB bug: this api is not supposed to be available
|
||||
fatalError("Unavailable statement SQL")
|
||||
|
||||
case let .trace_v2(sqliteStatement, unexpandedSQL, _):
|
||||
case let .trace_v2(sqliteStatement, unexpandedSQL, _, _):
|
||||
if let unexpandedSQL = unexpandedSQL {
|
||||
return String(cString: unexpandedSQL)
|
||||
.trimmingCharacters(in: .sqlStatementSeparators)
|
||||
@@ -1691,13 +1682,17 @@ extension Database {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// UPDATE player SET score = 1000 WHERE id = 1
|
||||
/// SELECT * FROM player WHERE email = 'arthur@example.com'
|
||||
///
|
||||
/// - warning: It is your responsibility to prevent sensitive
|
||||
/// information from leaking in unexpected locations, so use this
|
||||
/// property with care.
|
||||
public var expandedSQL: String {
|
||||
switch impl {
|
||||
case let .trace_v1(expandedSQL):
|
||||
return expandedSQL
|
||||
|
||||
case let .trace_v2(sqliteStatement, _, sqlite3_expanded_sql):
|
||||
case let .trace_v2(sqliteStatement, _, sqlite3_expanded_sql, _):
|
||||
guard let cString = sqlite3_expanded_sql(sqliteStatement) else {
|
||||
return ""
|
||||
}
|
||||
@@ -1706,6 +1701,20 @@ extension Database {
|
||||
.trimmingCharacters(in: .sqlStatementSeparators)
|
||||
}
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
switch impl {
|
||||
case let .trace_v1(expandedSQL):
|
||||
return expandedSQL
|
||||
|
||||
case let .trace_v2(_, _, _, publicStatementArguments):
|
||||
if publicStatementArguments {
|
||||
return expandedSQL
|
||||
} else {
|
||||
return _sql
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An event reported by `TracingOptions.statement`.
|
||||
@@ -1714,7 +1723,39 @@ extension Database {
|
||||
/// An event reported by `TracingOptions.profile`.
|
||||
case profile(statement: Statement, duration: TimeInterval)
|
||||
|
||||
/// The trace event description.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// SELECT * FROM player WHERE email = ?
|
||||
/// 0.1s SELECT * FROM player WHERE email = ?
|
||||
///
|
||||
/// The format of the event description may change between GRDB releases,
|
||||
/// without notice: don't have your application rely on any specific format.
|
||||
public var description: String {
|
||||
switch self {
|
||||
case let .statement(statement):
|
||||
return statement.description
|
||||
case let .profile(statement: statement, duration: duration):
|
||||
let durationString = String(format: "%.3f", duration)
|
||||
return "\(durationString)s \(statement)"
|
||||
}
|
||||
}
|
||||
|
||||
/// The trace event description, where bound parameters are expanded.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// SELECT * FROM player WHERE email = 'arthur@example.com'
|
||||
/// 0.1s SELECT * FROM player WHERE email = 'arthur@example.com'
|
||||
///
|
||||
/// The format of the event description may change between GRDB releases,
|
||||
/// without notice: don't have your application rely on any specific format.
|
||||
///
|
||||
/// - warning: It is your responsibility to prevent sensitive
|
||||
/// information from leaking in unexpected locations, so use this
|
||||
/// property with care.
|
||||
public var expandedDescription: String {
|
||||
switch self {
|
||||
case let .statement(statement):
|
||||
return statement.expandedSQL
|
||||
|
||||
@@ -241,17 +241,31 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
/// The query arguments that yielded the error (if relevant).
|
||||
public let arguments: StatementArguments?
|
||||
|
||||
/// Creates a Database Error
|
||||
/// See Configuration.publicStatementArguments
|
||||
var publicStatementArguments: Bool
|
||||
|
||||
/// Creates a DatabaseError.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - resultCode: A ResultCode (defaults to .SQLITE_ERROR).
|
||||
/// - message: An eventual error message. If nil, the error message is
|
||||
/// derived from the result code.
|
||||
/// - sql: An eventual SQL string.
|
||||
/// - arguments: Eventual Statement arguments.
|
||||
/// - publicStatementArguments: If false (the default), statement
|
||||
/// arguments are not visible in the error's `description` property.
|
||||
public init(
|
||||
resultCode: ResultCode = .SQLITE_ERROR,
|
||||
message: String? = nil,
|
||||
sql: String? = nil,
|
||||
arguments: StatementArguments? = nil)
|
||||
arguments: StatementArguments? = nil,
|
||||
publicStatementArguments: Bool = false)
|
||||
{
|
||||
self.extendedResultCode = resultCode
|
||||
self.message = message ?? resultCode.errorString
|
||||
self.sql = sql
|
||||
self.arguments = arguments
|
||||
self.publicStatementArguments = publicStatementArguments
|
||||
}
|
||||
|
||||
/// Creates a Database Error with a raw CInt result code.
|
||||
@@ -259,8 +273,31 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
/// This initializer is not public because library user is not supposed to
|
||||
/// be exposed to raw result codes.
|
||||
@usableFromInline
|
||||
init(resultCode: CInt, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
|
||||
self.init(resultCode: ResultCode(rawValue: resultCode), message: message, sql: sql, arguments: arguments)
|
||||
init(resultCode: CInt, message: String? = nil, sql: String? = nil) {
|
||||
self.init(
|
||||
resultCode: ResultCode(rawValue: resultCode),
|
||||
message: message,
|
||||
sql: sql)
|
||||
}
|
||||
|
||||
/// Creates a Database Error with a raw CInt result code.
|
||||
///
|
||||
/// This initializer is not public because library user is not supposed to
|
||||
/// be exposed to raw result codes.
|
||||
@usableFromInline
|
||||
init(
|
||||
resultCode: CInt,
|
||||
message: String? = nil,
|
||||
sql: String? = nil,
|
||||
arguments: StatementArguments?,
|
||||
publicStatementArguments: Bool)
|
||||
{
|
||||
self.init(
|
||||
resultCode: ResultCode(rawValue: resultCode),
|
||||
message: message,
|
||||
sql: sql,
|
||||
arguments: arguments,
|
||||
publicStatementArguments: publicStatementArguments)
|
||||
}
|
||||
|
||||
static func noSuchTable(_ tableName: String) -> Self {
|
||||
@@ -404,8 +441,44 @@ extension DatabaseError {
|
||||
|
||||
// CustomStringConvertible
|
||||
extension DatabaseError {
|
||||
/// :nodoc:
|
||||
/// The error description.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// SQLite error 19: NOT NULL constraint failed: player.score
|
||||
/// - while executing `UPDATE player SET score = ? WHERE email = ?
|
||||
///
|
||||
/// The format of the error description may change between GRDB releases,
|
||||
/// without notice: don't have your application rely on any specific format.
|
||||
public var description: String {
|
||||
var description = "SQLite error \(resultCode.rawValue)"
|
||||
if let message = message {
|
||||
description += ": \(message)"
|
||||
}
|
||||
if let sql = sql {
|
||||
description += " - while executing `\(sql)`"
|
||||
}
|
||||
if publicStatementArguments, let arguments = arguments, !arguments.isEmpty {
|
||||
description += " with arguments \(arguments)"
|
||||
}
|
||||
return description
|
||||
}
|
||||
|
||||
/// The error description, where bound parameters, if present, are visible.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// SQLite error 19: NOT NULL constraint failed: player.score
|
||||
/// - while executing `UPDATE player SET score = ? WHERE email = ?
|
||||
/// with arguments [nil, "arthur@example.com"]
|
||||
///
|
||||
/// The format of the error description may change between GRDB releases,
|
||||
/// without notice: don't have your application rely on any specific format.
|
||||
///
|
||||
/// - warning: It is your responsibility to prevent sensitive
|
||||
/// information from leaking in unexpected locations, so use this
|
||||
/// property with care.
|
||||
public var expandedDescription: String {
|
||||
var description = "SQLite error \(resultCode.rawValue)"
|
||||
if let message = message {
|
||||
description += ": \(message)"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import Foundation
|
||||
import Dispatch
|
||||
import Foundation
|
||||
#if os(iOS)
|
||||
import UIKit
|
||||
#endif
|
||||
@@ -336,7 +336,7 @@ extension DatabasePool: DatabaseReader {
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "asyncRead")
|
||||
configuration
|
||||
.makeDispatchQueue(label: label)
|
||||
.makeReaderDispatchQueue(label: label)
|
||||
.async {
|
||||
do {
|
||||
guard let readerPool = self.readerPool else {
|
||||
@@ -374,7 +374,7 @@ extension DatabasePool: DatabaseReader {
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "asyncRead")
|
||||
configuration
|
||||
.makeDispatchQueue(label: label)
|
||||
.makeReaderDispatchQueue(label: label)
|
||||
.async { [weak self] in
|
||||
guard let self = self else {
|
||||
value(nil)
|
||||
@@ -435,7 +435,7 @@ extension DatabasePool: DatabaseReader {
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "asyncUnsafeRead")
|
||||
configuration
|
||||
.makeDispatchQueue(label: label)
|
||||
.makeReaderDispatchQueue(label: label)
|
||||
.async {
|
||||
do {
|
||||
guard let readerPool = self.readerPool else {
|
||||
@@ -802,7 +802,7 @@ extension DatabasePool: DatabaseReader {
|
||||
observation: observation,
|
||||
writer: self,
|
||||
scheduler: scheduler,
|
||||
reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel),
|
||||
reduceQueue: configuration.makeReaderDispatchQueue(label: reduceQueueLabel),
|
||||
onChange: onChange)
|
||||
|
||||
// Starting a concurrent observation means that we'll fetch the initial
|
||||
@@ -857,7 +857,7 @@ extension DatabasePool: DatabaseReader {
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "ValueObservation")
|
||||
configuration
|
||||
.makeDispatchQueue(label: label)
|
||||
.makeReaderDispatchQueue(label: label)
|
||||
.async { [weak self] in
|
||||
guard let self = self else { return }
|
||||
if observer.isCompleted { return }
|
||||
|
||||
@@ -269,7 +269,7 @@ extension DatabaseRegion {
|
||||
}
|
||||
return tableRegions
|
||||
.sorted(by: { (l, r) in l.key.rawValue < r.key.rawValue })
|
||||
.map({ (table, tableRegion) in
|
||||
.map { (table, tableRegion) in
|
||||
var desc = table.rawValue
|
||||
if let columns = tableRegion.columns {
|
||||
desc += "(" + columns.map(\.rawValue).sorted().joined(separator: ",") + ")"
|
||||
@@ -280,7 +280,7 @@ extension DatabaseRegion {
|
||||
desc += "[" + rowIds.sorted().map { "\($0)" }.joined(separator: ",") + "]"
|
||||
}
|
||||
return desc
|
||||
})
|
||||
}
|
||||
.joined(separator: ",")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ extension DatabaseRegionObservation {
|
||||
/// on subscription.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func publisher(in writer: DatabaseWriter) -> DatabasePublishers.DatabaseRegion {
|
||||
return DatabasePublishers.DatabaseRegion(self, in: writer)
|
||||
DatabasePublishers.DatabaseRegion(self, in: writer)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -382,7 +382,7 @@ extension DatabaseWriter {
|
||||
observation: observation,
|
||||
writer: self,
|
||||
scheduler: scheduler,
|
||||
reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel),
|
||||
reduceQueue: configuration.makeWriterDispatchQueue(label: reduceQueueLabel),
|
||||
onChange: onChange)
|
||||
|
||||
if scheduler.immediateInitialValue() {
|
||||
@@ -576,11 +576,11 @@ extension DatabaseWriter {
|
||||
-> DatabasePublishers.Write<Output>
|
||||
where S: Scheduler
|
||||
{
|
||||
OnDemandFuture({ fulfill in
|
||||
OnDemandFuture { fulfill in
|
||||
self.asyncWrite(updates, completion: { _, result in
|
||||
fulfill(result)
|
||||
})
|
||||
})
|
||||
}
|
||||
// We don't want users to process emitted values on a
|
||||
// database dispatch queue.
|
||||
.receiveValues(on: scheduler)
|
||||
@@ -629,7 +629,7 @@ extension DatabaseWriter {
|
||||
-> DatabasePublishers.Write<Output>
|
||||
where S: Scheduler
|
||||
{
|
||||
OnDemandFuture({ fulfill in
|
||||
OnDemandFuture { fulfill in
|
||||
self.asyncWriteWithoutTransaction { db in
|
||||
var updatesValue: T?
|
||||
do {
|
||||
@@ -645,7 +645,7 @@ extension DatabaseWriter {
|
||||
fulfill(dbResult.flatMap { db in Result { try value(db, updatesValue!) } })
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
// We don't want users to process emitted values on a
|
||||
// database dispatch queue.
|
||||
.receiveValues(on: scheduler)
|
||||
|
||||
@@ -49,7 +49,13 @@ final class SchedulingWatchdog {
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
{
|
||||
GRDBPrecondition(current?.allows(db) ?? false, message(), file: file, line: line)
|
||||
GRDBPrecondition(allows(db), message(), file: file, line: line)
|
||||
}
|
||||
|
||||
/// Returns true iff the database argument can be used in the current
|
||||
/// dispatch queue.
|
||||
static func allows(_ db: Database) -> Bool {
|
||||
current?.allows(db) ?? false
|
||||
}
|
||||
|
||||
static var current: SchedulingWatchdog? {
|
||||
|
||||
@@ -47,7 +47,11 @@ final class SerializedDatabase {
|
||||
path: path,
|
||||
description: identifier,
|
||||
configuration: config)
|
||||
self.queue = configuration.makeDispatchQueue(label: identifier)
|
||||
if config.readonly {
|
||||
self.queue = configuration.makeReaderDispatchQueue(label: identifier)
|
||||
} else {
|
||||
self.queue = configuration.makeWriterDispatchQueue(label: identifier)
|
||||
}
|
||||
SchedulingWatchdog.allowDatabase(db, onQueue: queue)
|
||||
try queue.sync {
|
||||
do {
|
||||
|
||||
+62
-66
@@ -87,24 +87,26 @@ public final class Statement {
|
||||
{
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
|
||||
let authorizer = StatementCompilationAuthorizer()
|
||||
// Reset authorizer before preparing the statement
|
||||
let authorizer = database.authorizer
|
||||
authorizer.reset()
|
||||
|
||||
var sqliteStatement: SQLiteStatement? = nil
|
||||
let code: Int32 = database.withAuthorizer(authorizer) {
|
||||
// sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
return sqlite3_prepare_v3(
|
||||
let code: Int32
|
||||
// sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
code = sqlite3_prepare_v3(
|
||||
database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags),
|
||||
&sqliteStatement, statementEnd)
|
||||
#else
|
||||
if #available(iOS 12.0, OSX 10.14, tvOS 12.0, watchOS 5.0, *) {
|
||||
code = sqlite3_prepare_v3(
|
||||
database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags),
|
||||
&sqliteStatement, statementEnd)
|
||||
#else
|
||||
if #available(iOS 12.0, OSX 10.14, tvOS 12.0, watchOS 5.0, *) {
|
||||
return sqlite3_prepare_v3(
|
||||
database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags),
|
||||
&sqliteStatement, statementEnd)
|
||||
} else {
|
||||
return sqlite3_prepare_v2(database.sqliteConnection, statementStart, -1, &sqliteStatement, statementEnd)
|
||||
}
|
||||
#endif
|
||||
} else {
|
||||
code = sqlite3_prepare_v2(database.sqliteConnection, statementStart, -1, &sqliteStatement, statementEnd)
|
||||
}
|
||||
#endif
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(
|
||||
@@ -296,43 +298,19 @@ public final class Statement {
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func execute(arguments: StatementArguments? = nil) throws {
|
||||
try reset(withArguments: arguments)
|
||||
try database.withAuthorizer(database.statementWillExecute(self)) {
|
||||
// Iterate all rows, since they may execute side effects.
|
||||
while true {
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
try database.statementDidExecute(self)
|
||||
return
|
||||
case SQLITE_ROW:
|
||||
break
|
||||
case let code:
|
||||
try database.statementDidFail(self, withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls the given closure after one successful call to `sqlite3_step()`.
|
||||
///
|
||||
/// This method is unable to deal with statements that need a specific
|
||||
/// authorizer. See `forEachStep(_:)`.
|
||||
@usableFromInline
|
||||
func step<Element>(_ body: (SQLiteStatement) throws -> Element) throws -> Element? {
|
||||
// This check takes 0 time when profiled. It is, practically speaking, free.
|
||||
if sqlite3_stmt_busy(sqliteStatement) == 0 {
|
||||
guard try database.statementWillExecute(self) == nil else {
|
||||
fatalError("Can't execute step by step a statement that requires a customized authorizer.")
|
||||
}
|
||||
}
|
||||
try database.statementWillExecute(self)
|
||||
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
try database.statementDidExecute(self)
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return try body(sqliteStatement)
|
||||
case let code:
|
||||
try database.statementDidFail(self, withResultCode: code)
|
||||
// Iterate all rows, since they may execute side effects.
|
||||
while true {
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
try database.statementDidExecute(self)
|
||||
return
|
||||
case SQLITE_ROW:
|
||||
break
|
||||
case let code:
|
||||
try database.statementDidFail(self, withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -355,24 +333,42 @@ public final class Statement {
|
||||
@usableFromInline
|
||||
func forEachStep(_ body: (SQLiteStatement) throws -> Void) throws {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
guard sqlite3_stmt_busy(sqliteStatement) == 0 else {
|
||||
// We can't deal with possible authorizer
|
||||
fatalError("Statement is busy")
|
||||
}
|
||||
try database.withAuthorizer(database.statementWillExecute(self)) {
|
||||
while true {
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
try database.statementDidExecute(self)
|
||||
return
|
||||
case SQLITE_ROW:
|
||||
try body(sqliteStatement)
|
||||
case let code:
|
||||
try database.statementDidFail(self, withResultCode: code)
|
||||
}
|
||||
try database.statementWillExecute(self)
|
||||
|
||||
while true {
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
try database.statementDidExecute(self)
|
||||
return
|
||||
case SQLITE_ROW:
|
||||
try body(sqliteStatement)
|
||||
case let code:
|
||||
try database.statementDidFail(self, withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls the given closure after one successful call to `sqlite3_step()`.
|
||||
///
|
||||
/// This method is unable to deal with statements that need a specific
|
||||
/// authorizer. See `forEachStep(_:)`.
|
||||
@usableFromInline
|
||||
func step<Element>(_ body: (SQLiteStatement) throws -> Element) throws -> Element? {
|
||||
// This check takes 0 time when profiled. It is, practically speaking, free.
|
||||
if sqlite3_stmt_busy(sqliteStatement) == 0 {
|
||||
try database.statementWillExecute(self)
|
||||
}
|
||||
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
try database.statementDidExecute(self)
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return try body(sqliteStatement)
|
||||
case let code:
|
||||
try database.statementDidFail(self, withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "Statement")
|
||||
@@ -383,7 +379,7 @@ public typealias UpdateStatement = Statement
|
||||
|
||||
extension Statement: CustomStringConvertible {
|
||||
public var description: String {
|
||||
"SQL: \(sql), Arguments: \(arguments)"
|
||||
SchedulingWatchdog.allows(database) ? sql : "Statement"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,29 +2,19 @@
|
||||
import Glibc
|
||||
#endif
|
||||
|
||||
/// A protocol around sqlite3_set_authorizer
|
||||
@usableFromInline
|
||||
protocol StatementAuthorizer: AnyObject {
|
||||
func authorize(
|
||||
_ actionCode: Int32,
|
||||
_ cString1: UnsafePointer<Int8>?,
|
||||
_ cString2: UnsafePointer<Int8>?,
|
||||
_ cString3: UnsafePointer<Int8>?,
|
||||
_ cString4: UnsafePointer<Int8>?)
|
||||
-> Int32
|
||||
}
|
||||
|
||||
/// A class that gathers information about one statement during its compilation.
|
||||
final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
final class StatementAuthorizer {
|
||||
private unowned var database: Database
|
||||
|
||||
/// What this statements reads
|
||||
var selectedRegion = DatabaseRegion()
|
||||
|
||||
/// What this statements writes
|
||||
var databaseEventKinds: [DatabaseEventKind] = []
|
||||
|
||||
/// True if a statement alter the schema in a way that required schema cache
|
||||
/// invalidation. For example, adding a column to a table invalidates the
|
||||
/// schema cache, but not creating a table.
|
||||
/// True if a statement alters the schema in a way that requires
|
||||
/// invalidation of the schema cache. For example, adding a column to a
|
||||
/// table invalidates the schema cache.
|
||||
var invalidatesDatabaseSchemaCache = false
|
||||
|
||||
/// Not nil if a statement is a BEGIN/COMMIT/ROLLBACK/RELEASE transaction or
|
||||
@@ -33,6 +23,19 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
|
||||
private var isDropStatement = false
|
||||
|
||||
init(_ database: Database) {
|
||||
self.database = database
|
||||
}
|
||||
|
||||
/// Reset before compiling a new statement
|
||||
func reset() {
|
||||
selectedRegion = DatabaseRegion()
|
||||
databaseEventKinds = []
|
||||
invalidatesDatabaseSchemaCache = false
|
||||
transactionEffect = nil
|
||||
isDropStatement = false
|
||||
}
|
||||
|
||||
func authorize(
|
||||
_ actionCode: Int32,
|
||||
_ cString1: UnsafePointer<Int8>?,
|
||||
@@ -43,7 +46,7 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
{
|
||||
// Uncomment when debugging
|
||||
// print("""
|
||||
// StatementCompilationAuthorizer: \
|
||||
// StatementAuthorizer: \
|
||||
// \(AuthorizerActionCode(rawValue: actionCode)) \
|
||||
// \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) }.joined(separator: ", "))
|
||||
// """)
|
||||
@@ -94,10 +97,16 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
guard strcmp(cString1, "sqlite_master") != 0 else { return SQLITE_OK }
|
||||
guard strcmp(cString1, "sqlite_temp_master") != 0 else { return SQLITE_OK }
|
||||
|
||||
let tableName = String(cString: cString1)
|
||||
databaseEventKinds.append(.delete(tableName: tableName))
|
||||
|
||||
// Now we prevent the truncate optimization so that transaction
|
||||
// observers are notified of individual row deletions.
|
||||
databaseEventKinds.append(.delete(tableName: String(cString: cString1)))
|
||||
return SQLITE_IGNORE
|
||||
if database.observationBroker.observesDeletions(on: tableName) {
|
||||
return SQLITE_IGNORE
|
||||
} else {
|
||||
return SQLITE_OK
|
||||
}
|
||||
|
||||
case SQLITE_UPDATE:
|
||||
guard let tableName = cString1.map(String.init) else { return SQLITE_OK }
|
||||
@@ -176,30 +185,6 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
}
|
||||
}
|
||||
|
||||
/// This authorizer prevents the [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
|
||||
/// which makes transaction observers unable to observe individual deletions
|
||||
/// when user runs `DELETE FROM t` statements.
|
||||
//
|
||||
/// Warning: to perform well, this authorizer must be used during statement
|
||||
/// execution, not during statement compilation.
|
||||
final class TruncateOptimizationBlocker: StatementAuthorizer {
|
||||
func authorize(
|
||||
_ actionCode: Int32,
|
||||
_ cString1: UnsafePointer<Int8>?,
|
||||
_ cString2: UnsafePointer<Int8>?,
|
||||
_ cString3: UnsafePointer<Int8>?,
|
||||
_ cString4: UnsafePointer<Int8>?)
|
||||
-> Int32
|
||||
{
|
||||
// print("""
|
||||
// TruncateOptimizationBlocker: \
|
||||
// \(AuthorizerActionCode(rawValue: actionCode)) \
|
||||
// \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) })
|
||||
// """)
|
||||
return (actionCode == SQLITE_DELETE) ? SQLITE_IGNORE : SQLITE_OK
|
||||
}
|
||||
}
|
||||
|
||||
private struct AuthorizerActionCode: RawRepresentable, CustomStringConvertible {
|
||||
let rawValue: Int32
|
||||
|
||||
|
||||
@@ -708,7 +708,7 @@ extension DatabaseCollation {
|
||||
/// """)
|
||||
public static let localizedCaseInsensitiveCompare =
|
||||
DatabaseCollation("swiftLocalizedCaseInsensitiveCompare") { (lhs, rhs) in
|
||||
return lhs.localizedCaseInsensitiveCompare(rhs)
|
||||
lhs.localizedCaseInsensitiveCompare(rhs)
|
||||
}
|
||||
|
||||
/// A collation, or SQL string comparison function, that compares strings
|
||||
|
||||
@@ -14,12 +14,24 @@ extension Database {
|
||||
extent: TransactionObservationExtent = .observerLifetime)
|
||||
{
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
|
||||
// Drop cached statements that delete, because the addition of an
|
||||
// observer may change the need for truncate optimization prevention.
|
||||
publicStatementCache.removeAll { $0.databaseEventKinds.contains(where: \.isDelete) }
|
||||
internalStatementCache.removeAll{ $0.databaseEventKinds.contains(where: \.isDelete) }
|
||||
|
||||
observationBroker.add(transactionObserver: transactionObserver, extent: extent)
|
||||
}
|
||||
|
||||
/// Remove a transaction observer.
|
||||
public func remove(transactionObserver: TransactionObserver) {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
|
||||
// Drop cached statements that delete, because the removal of an
|
||||
// observer may change the need for truncate optimization prevention.
|
||||
publicStatementCache.removeAll { $0.databaseEventKinds.contains(where: \.isDelete) }
|
||||
internalStatementCache.removeAll { $0.databaseEventKinds.contains(where: \.isDelete) }
|
||||
|
||||
observationBroker.remove(transactionObserver: transactionObserver)
|
||||
}
|
||||
|
||||
@@ -198,16 +210,17 @@ class DatabaseObservationBroker {
|
||||
|
||||
// MARK: - Statement execution
|
||||
|
||||
/// Setups observation of changes that are about to be performed by the
|
||||
/// statement, and returns the authorizer that should be used during
|
||||
/// statement execution (this allows preventing the truncate optimization
|
||||
/// when there exists a transaction observer for row deletion).
|
||||
func statementWillExecute(_ statement: Statement) -> StatementAuthorizer? {
|
||||
/// Returns true if there exists some transaction observers interested in
|
||||
/// deletions in the given table.
|
||||
func observesDeletions(on table: String) -> Bool {
|
||||
transactionObservations.contains { observation in
|
||||
observation.observes(eventsOfKind: .delete(tableName: table))
|
||||
}
|
||||
}
|
||||
|
||||
/// Prepares observation of changes that are about to be performed by the statement.
|
||||
func statementWillExecute(_ statement: Statement) {
|
||||
// If any observer observes row deletions, we'll have to disable
|
||||
// [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
|
||||
// so that observers are notified.
|
||||
var observesRowDeletion = false
|
||||
|
||||
if transactionObservations.isEmpty == false {
|
||||
// As statement executes, it may trigger database changes that will
|
||||
// be notified to transaction observers. As a consequence, observers
|
||||
@@ -245,10 +258,6 @@ class DatabaseObservationBroker {
|
||||
return nil
|
||||
}
|
||||
|
||||
if case .delete = eventKind {
|
||||
observesRowDeletion = true
|
||||
}
|
||||
|
||||
// observation will be notified of all individual events
|
||||
return (observation, DatabaseEventPredicate.true)
|
||||
}
|
||||
@@ -268,13 +277,6 @@ class DatabaseObservationBroker {
|
||||
return nil
|
||||
}
|
||||
|
||||
for eventKind in observedKinds {
|
||||
if case .delete = eventKind {
|
||||
observesRowDeletion = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// observation will only be notified of individual events that
|
||||
// match one of the observed kinds.
|
||||
return (
|
||||
@@ -287,12 +289,6 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
|
||||
transactionState = .none
|
||||
|
||||
if observesRowDeletion {
|
||||
return TruncateOptimizationBlocker()
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// May throw a cancelled commit error, if a transaction observer cancels
|
||||
@@ -902,6 +898,15 @@ public enum DatabaseEventKind {
|
||||
return DatabaseRegion(table: tableName, columns: updatedColumnNames)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true iff this is a delete event.
|
||||
var isDelete: Bool {
|
||||
if case .delete = self {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseEventKind {
|
||||
|
||||
@@ -432,6 +432,7 @@ public struct DatabaseMigrator {
|
||||
// just as the migrated database
|
||||
var tmpConfig = db.configuration
|
||||
tmpConfig.targetQueue = nil // Avoid deadlocks
|
||||
tmpConfig.writeTargetQueue = nil // Avoid deadlocks
|
||||
tmpConfig.label = "GRDB.DatabaseMigrator.temporary"
|
||||
|
||||
// Create the temporary database on disk, just in
|
||||
|
||||
@@ -686,7 +686,7 @@ private func prefetch(
|
||||
// In the CTE, ordering and including(all:) children are
|
||||
// useless, and we only need to select pivot columns:
|
||||
let originRelation = originRelation
|
||||
.unordered()
|
||||
.unorderedUnlessLimited() // only preserve ordering in the CTE if limited
|
||||
.removingChildrenForPrefetchedAssociations()
|
||||
.selectOnly(leftColumns.map { SQLExpression.column($0).sqlSelection })
|
||||
let originCTE = CommonTableExpression(
|
||||
|
||||
@@ -120,7 +120,7 @@ public struct _SQLAssociation {
|
||||
// via: Pivot.belongsTo(Destination.self))
|
||||
// Origin(id: 1).request(for: association)
|
||||
let reversedSteps = zip(steps, steps.dropFirst())
|
||||
.map({ (step, nextStep) -> SQLAssociationStep in
|
||||
.map { (step, nextStep) -> SQLAssociationStep in
|
||||
// Intermediate steps are not selected, and including(all:)
|
||||
// children are useless:
|
||||
let relation = step.relation
|
||||
@@ -137,7 +137,7 @@ public struct _SQLAssociation {
|
||||
condition: nextStep.condition.reversed(to: step.relation.source.tableName),
|
||||
relation: relation,
|
||||
cardinality: .toOne)
|
||||
})
|
||||
}
|
||||
.reversed()
|
||||
let reversedAssociation = _SQLAssociation(steps: Array(reversedSteps))
|
||||
return destination.relation.appendingChild(for: reversedAssociation, kind: .oneRequired)
|
||||
|
||||
@@ -325,7 +325,7 @@ public struct SQLExpression {
|
||||
/// let operator = BinaryOperator("LIKE", negated: "NOT LIKE")
|
||||
/// operator.negated!.sql // NOT LIKE
|
||||
var negated: EscapableBinaryOperator {
|
||||
return EscapableBinaryOperator(negatedSQL, negated: sql)
|
||||
EscapableBinaryOperator(negatedSQL, negated: sql)
|
||||
}
|
||||
|
||||
/// The `LIKE` escapable binary operator
|
||||
|
||||
@@ -274,6 +274,15 @@ extension SQLRelation: Refinable {
|
||||
}
|
||||
}
|
||||
|
||||
// Remove ordering iff relation has no LIMIT clause
|
||||
func unorderedUnlessLimited() -> Self {
|
||||
if limit != nil {
|
||||
return self
|
||||
} else {
|
||||
return unordered()
|
||||
}
|
||||
}
|
||||
|
||||
func group(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self {
|
||||
with {
|
||||
$0.groupPromise = DatabasePromise(expressions)
|
||||
|
||||
@@ -554,9 +554,9 @@ public enum DatabaseColumnEncodingStrategy {
|
||||
searchRange = lowerCaseRange.upperBound..<searchRange.upperBound
|
||||
}
|
||||
words.append(wordStart..<searchRange.upperBound)
|
||||
let result = words.map({ (range) in
|
||||
return stringKey[range].lowercased()
|
||||
}).joined(separator: "_")
|
||||
let result = words
|
||||
.map { (range) in stringKey[range].lowercased() }
|
||||
.joined(separator: "_")
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -691,5 +691,4 @@ public enum DatabaseColumnDecodingStrategy {
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
}
|
||||
@@ -218,7 +218,7 @@ extension Publisher {
|
||||
/// The difference with the stock `receive(on:options:)` Combine method is
|
||||
/// that only values and completion are re-scheduled. Subscriptions are not.
|
||||
func receiveValues<S: Scheduler>(on scheduler: S, options: S.SchedulerOptions? = nil) -> ReceiveValuesOn<Self, S> {
|
||||
return ReceiveValuesOn(upstream: self, context: scheduler, options: options)
|
||||
ReceiveValuesOn(upstream: self, context: scheduler, options: options)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -187,7 +187,7 @@ extension ValueObservation: Refinable {
|
||||
-> ValueObservation<ValueReducers.Trace<Reducer>>
|
||||
{
|
||||
self
|
||||
.mapReducer({ reducer in
|
||||
.mapReducer { reducer in
|
||||
ValueReducers.Trace(
|
||||
base: reducer,
|
||||
// Adding the willFetch handler to the reducer is handy: we
|
||||
@@ -196,7 +196,7 @@ extension ValueObservation: Refinable {
|
||||
// Adding the didReceiveValue handler to the reducer is necessary:
|
||||
// the type of the value may change with the `map` operator.
|
||||
didReceiveValue: didReceiveValue ?? { _ in })
|
||||
})
|
||||
}
|
||||
.with {
|
||||
$0.events.willStart = concat($0.events.willStart, willStart)
|
||||
$0.events.willTrackRegion = concat($0.events.willTrackRegion, willTrackRegion)
|
||||
|
||||
@@ -520,10 +520,10 @@ ifdef JAZZY
|
||||
--author 'Gwendal Roué' \
|
||||
--author_url https://github.com/groue \
|
||||
--github_url https://github.com/groue/GRDB.swift \
|
||||
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.19.0 \
|
||||
--module-version 5.19.0 \
|
||||
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.20.0 \
|
||||
--module-version 5.20.0 \
|
||||
--module GRDB \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/5.19/ \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/5.20/ \
|
||||
--output Documentation/Reference \
|
||||
--xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS
|
||||
else
|
||||
|
||||
@@ -11,13 +11,13 @@
|
||||
|
||||
---
|
||||
|
||||
**Latest release**: January 19, 2022 • [version 5.19.0](https://github.com/groue/GRDB.swift/tree/v5.19.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
|
||||
**Latest release**: February 1, 2022 • [version 5.20.0](https://github.com/groue/GRDB.swift/tree/v5.20.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
|
||||
|
||||
**Requirements**: iOS 11.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ • SQLite 3.8.5+ • Swift 5.3+ / Xcode 12+
|
||||
|
||||
| Swift version | GRDB version |
|
||||
| -------------- | ----------------------------------------------------------- |
|
||||
| **Swift 5.3+** | **v5.19.0** |
|
||||
| **Swift 5.3+** | **v5.20.0** |
|
||||
| Swift 5.2 | [v5.12.0](https://github.com/groue/GRDB.swift/tree/v5.12.0) |
|
||||
| Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
|
||||
| Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
|
||||
@@ -318,7 +318,7 @@ Documentation
|
||||
|
||||
#### Reference
|
||||
|
||||
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.19/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
|
||||
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.20/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
|
||||
|
||||
#### Getting Started
|
||||
|
||||
@@ -496,23 +496,9 @@ let newPlaceCount = try dbQueue.write { db -> Int in
|
||||
|
||||
**A database queue needs your application to follow rules in order to deliver its safety guarantees.** Please refer to the [Concurrency] guide.
|
||||
|
||||
> :bulb: **Tip**: see the [Demo Applications] for sample code that sets up a database queue on iOS.
|
||||
See [Database Configuration] for DatabaseQueue options.
|
||||
|
||||
|
||||
### DatabaseQueue Configuration
|
||||
|
||||
```swift
|
||||
var config = Configuration()
|
||||
config.readonly = true
|
||||
config.foreignKeysEnabled = true // Default is already true
|
||||
config.label = "MyDatabase" // Useful when your app opens multiple databases
|
||||
|
||||
let dbQueue = try DatabaseQueue(
|
||||
path: "/path/to/database.sqlite",
|
||||
configuration: config)
|
||||
```
|
||||
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.19/Structs/Configuration.html) for more details.
|
||||
> :bulb: **Tip**: see the [Demo Applications] for sample code.
|
||||
|
||||
|
||||
## Database Pools
|
||||
@@ -561,7 +547,7 @@ let newPlaceCount = try dbPool.write { db -> Int in
|
||||
|
||||
- When you don't need to modify the database, prefer the `read` method, because several threads can perform reads in parallel.
|
||||
|
||||
Reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be [configured](#databasepool-configuration).
|
||||
Reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be [configured](#database-configuration).
|
||||
|
||||
- Reads are guaranteed an immutable view of the last committed state of the database, regardless of concurrent writes. This kind of isolation is called [snapshot isolation](https://sqlite.org/isolation.html).
|
||||
|
||||
@@ -575,27 +561,54 @@ let newPlaceCount = try dbPool.write { db -> Int in
|
||||
|
||||
**A database pool needs your application to follow rules in order to deliver its safety guarantees.** See the [Concurrency] guide for more details about database pools, how they differ from database queues, and advanced use cases.
|
||||
|
||||
> :bulb: **Tip**: see the [Demo Applications] for sample code that sets up a database queue on iOS, and just replace DatabaseQueue with DatabasePool.
|
||||
See [Database Configuration] for DatabasePool options.
|
||||
|
||||
> :bulb: **Tip**: see the [Demo Applications] for sample code.
|
||||
|
||||
|
||||
### DatabasePool Configuration
|
||||
## Database Configuration
|
||||
|
||||
```swift
|
||||
var config = Configuration()
|
||||
config.readonly = true
|
||||
config.foreignKeysEnabled = true // Default is already true
|
||||
config.label = "MyDatabase" // Useful when your app opens multiple databases
|
||||
config.maximumReaderCount = 10 // The default is 5
|
||||
config.maximumReaderCount = 10 // (DatabasePool only) The default is 5
|
||||
|
||||
let dbPool = try DatabasePool(
|
||||
let dbQueue = try DatabaseQueue( // or DatabasePool
|
||||
path: "/path/to/database.sqlite",
|
||||
configuration: config)
|
||||
```
|
||||
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.19/Structs/Configuration.html) for more details.
|
||||
In debug builds, you can increase the verbosity of [error descriptions](#databaseerror) and [trace events](#how-do-i-print-a-request-as-sql) if you opt in for public statement arguments:
|
||||
|
||||
```swift
|
||||
#if DEBUG
|
||||
// Protect sensitive information by enabling verbose debugging in DEBUG builds only
|
||||
config.publicStatementArguments = true
|
||||
#endif
|
||||
|
||||
Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information.
|
||||
let dbQueue = try DatabaseQueue(path: ..., configuration: config)
|
||||
|
||||
do {
|
||||
try dbQueue.write { db in
|
||||
user.name = ...
|
||||
user.location = ...
|
||||
user.address = ...
|
||||
user.phoneNumber = ...
|
||||
try user.save(db)
|
||||
}
|
||||
} catch {
|
||||
// Prints sensitive information in debug builds only
|
||||
print(error)
|
||||
}
|
||||
```
|
||||
|
||||
> :warning: **Warning**: It is your responsibility to prevent sensitive information from leaking in unexpected locations, so you should not set the `publicStatementArguments` flag in release builds (think about GDPR and other privacy-related rules).
|
||||
>
|
||||
> :warning: **Warning**: The SQLite version that ships with old operating systems (prior to OSX 10.12, tvOS 10.0, and watchOS 3.0) outputs statement arguments in the [trace events](#how-do-i-print-a-request-as-sql), regardless of the `publicStatementArguments` flag.
|
||||
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.20/Structs/Configuration.html) for more details and configuration options.
|
||||
|
||||
|
||||
SQLite API
|
||||
@@ -652,7 +665,7 @@ try dbQueue.write { db in
|
||||
}
|
||||
```
|
||||
|
||||
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.19/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
|
||||
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.20/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
|
||||
|
||||
You can also embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details.
|
||||
|
||||
@@ -910,7 +923,7 @@ try dbQueue.read { db in
|
||||
let dictionary = try Dictionary(uniqueKeysWithValues: cursor)
|
||||
```
|
||||
|
||||
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.19/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
|
||||
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.20/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
|
||||
|
||||
```swift
|
||||
// Prints all Github links
|
||||
@@ -989,7 +1002,7 @@ let rows = try Row.fetchAll(db,
|
||||
arguments: ["name": "Arthur"])
|
||||
```
|
||||
|
||||
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.19/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
|
||||
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.20/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
|
||||
|
||||
Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care:
|
||||
|
||||
@@ -1274,7 +1287,7 @@ GRDB ships with built-in support for the following value types:
|
||||
|
||||
- Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol.
|
||||
|
||||
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.19/Structs/StatementArguments.html):
|
||||
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.20/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let url: URL = ...
|
||||
@@ -1721,7 +1734,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction
|
||||
}
|
||||
```
|
||||
|
||||
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.19/Structs/Configuration.html) configuration flag:
|
||||
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.20/Structs/Configuration.html) configuration flag:
|
||||
|
||||
```swift
|
||||
// fatal error: A transaction has been left opened at the end of a database access
|
||||
@@ -1833,7 +1846,7 @@ try dbQueue.write { db in
|
||||
}
|
||||
```
|
||||
|
||||
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.19/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
|
||||
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.20/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
|
||||
|
||||
```swift
|
||||
insertStatement.arguments = ["name": "Arthur", "score": 1000]
|
||||
@@ -1916,7 +1929,7 @@ See also `Database.execute(sql:)` in the [Executing Updates](#executing-updates)
|
||||
|
||||
> :point_up: **Note**: it is a programmer error to reuse a prepared statement that has failed: GRDB may crash if you do so.
|
||||
|
||||
For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.19/Classes/Statement.html).
|
||||
For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.20/Classes/Statement.html).
|
||||
|
||||
|
||||
### Prepared Statements Cache
|
||||
@@ -2659,7 +2672,7 @@ try Place.fetchSet(db, sql: "SELECT ...", arguments:...) // Set<Place>
|
||||
try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place?
|
||||
```
|
||||
|
||||
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.19/Structs/StatementArguments.html) for more information about the query arguments.
|
||||
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.20/Structs/StatementArguments.html) for more information about the query arguments.
|
||||
|
||||
> :point_up: **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`.
|
||||
|
||||
@@ -3099,7 +3112,7 @@ protocol EncodableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.19/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.19/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies.
|
||||
See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.20/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.20/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies.
|
||||
|
||||
|
||||
### Date and UUID Coding Strategies
|
||||
@@ -3121,7 +3134,7 @@ protocol EncodableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.19/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.19/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.19/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
|
||||
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.20/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.20/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.20/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
|
||||
|
||||
There is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs and uuid strings, both uppercase and lowercase).
|
||||
|
||||
@@ -4440,18 +4453,6 @@ You can now build requests with the following methods: `all`, `none`, `select`,
|
||||
Player.annotated(with: (scoreColumn + bonusColumn).forKey("total"))
|
||||
```
|
||||
|
||||
Such annotations can help using [Associations]:
|
||||
|
||||
```swift
|
||||
// SELECT player.*, team.name
|
||||
// FROM player
|
||||
// JOIN team ON team.id = player.teamId
|
||||
let teamAlias = TableAlias()
|
||||
let request = Player
|
||||
.annotated(with: teamAlias[nameColumn])
|
||||
.joining(required: Player.team.aliased(teamAlias))
|
||||
```
|
||||
|
||||
- `annotated(with: aggregate)` extends the selection with [association aggregates](Documentation/AssociationsBasics.md#association-aggregates).
|
||||
|
||||
```swift
|
||||
@@ -4462,6 +4463,15 @@ You can now build requests with the following methods: `all`, `none`, `select`,
|
||||
Team.annotated(with: Team.players.count)
|
||||
```
|
||||
|
||||
- `annotated(withRequired: association)` and `annotated(withOptional: association)` extends the selection with [Associations].
|
||||
|
||||
```swift
|
||||
// SELECT player.*, team.color
|
||||
// FROM player
|
||||
// JOIN team ON team.id = player.teamId
|
||||
Player.annotated(withRequired: Player.team.select(colorColumn))
|
||||
```
|
||||
|
||||
- `distinct()` performs uniquing.
|
||||
|
||||
```swift
|
||||
@@ -4649,7 +4659,7 @@ Player // SELECT * FROM player
|
||||
```
|
||||
|
||||
|
||||
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.19/Structs/StatementArguments.html):
|
||||
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.20/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate)
|
||||
@@ -5555,7 +5565,7 @@ try Player.customRequest().fetchAll(db) // [Player]
|
||||
|
||||
- The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method.
|
||||
|
||||
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.19/Structs/AnyFetchRequest.html): a type-erased request.
|
||||
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.20/Structs/AnyFetchRequest.html): a type-erased request.
|
||||
|
||||
|
||||
## Joined Queries Support
|
||||
@@ -6859,7 +6869,7 @@ DatabaseRegion helps [ValueObservation] and [DatabaseRegionObservation] track ch
|
||||
|
||||
For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table.
|
||||
|
||||
For more details, see the [reference](https://groue.github.io/GRDB.swift/docs/5.19/Structs/DatabaseRegion.html).
|
||||
For more details, see the [reference](https://groue.github.io/GRDB.swift/docs/5.20/Structs/DatabaseRegion.html).
|
||||
|
||||
|
||||
#### The DatabaseRegionConvertible Protocol
|
||||
@@ -7380,13 +7390,15 @@ do {
|
||||
// [1, "Bobby"]
|
||||
error.arguments
|
||||
|
||||
// Full error description:
|
||||
// "SQLite error 19 with statement `INSERT INTO pet (masterId, name)
|
||||
// VALUES (?, ?)` arguments [1, "Bobby"]: FOREIGN KEY constraint failed""
|
||||
// Full error description
|
||||
// > SQLite error 19: FOREIGN KEY constraint failed -
|
||||
// > while executing `INSERT INTO pet (masterId, name) VALUES (?, ?)`
|
||||
error.description
|
||||
}
|
||||
```
|
||||
|
||||
If you want to see statement arguments in the error description, [make statement arguments public](#database-configuration).
|
||||
|
||||
**SQLite uses [results codes](https://www.sqlite.org/rescode.html) to distinguish between various errors**.
|
||||
|
||||
You can catch a DatabaseError and match on result codes:
|
||||
@@ -7832,9 +7844,10 @@ You can compile the request into a prepared statement:
|
||||
|
||||
```swift
|
||||
try dbQueue.read { db in
|
||||
let request = Player.filter(Column("name") == "O'Brien")
|
||||
let request = Player.filter(Column("email") == "arthur@example.com")
|
||||
let statement = try request.makePreparedRequest(db).statement
|
||||
print(statement) // SQL: SELECT * FROM player WHERE name = ?, Arguments: ["O'Brien"]
|
||||
print(statement) // SELECT * FROM player WHERE email = ?
|
||||
print(statement.arguments) // ["arthur@example.com"]
|
||||
}
|
||||
```
|
||||
|
||||
@@ -7849,21 +7862,12 @@ config.prepareDatabase { db in
|
||||
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
|
||||
|
||||
try dbQueue.read { db in
|
||||
let players = try Player.filter(Column("name") == "O'Brien").fetchAll(db)
|
||||
// Prints SELECT * FROM player WHERE name = 'O''Brien'
|
||||
// Prints "SELECT * FROM player WHERE email = ?"
|
||||
let players = try Player.filter(Column("email") == "arthur@example.com").fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
If you want to hide values such as `'O''Brien'` from the logged statements, adapt the tracing function as below:
|
||||
|
||||
```swift
|
||||
db.trace { event in
|
||||
if case let .statement(statement) = event {
|
||||
// Prints SELECT * FROM player WHERE name = ?
|
||||
print(statement.sql)
|
||||
}
|
||||
}
|
||||
```
|
||||
If you want to see statement arguments such as `'arthur@example.com'` in the logged statements, [make statement arguments public](#database-configuration).
|
||||
|
||||
> :point_up: **Note**: the generated SQL may change between GRDB releases, without notice: don't have your application rely on any specific SQL output.
|
||||
|
||||
@@ -7895,11 +7899,13 @@ config.prepareDatabase { db in
|
||||
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
|
||||
|
||||
try dbQueue.read { db in
|
||||
let players = try Player.filter(Column("name") == "O'Brien").fetchAll(db)
|
||||
// Prints "0.003s SELECT * FROM player WHERE name = 'O''Brien'"
|
||||
let players = try Player.filter(Column("email") == "arthur@example.com").fetchAll(db)
|
||||
// Prints "0.003s SELECT * FROM player WHERE email = ?"
|
||||
}
|
||||
```
|
||||
|
||||
If you want to see statement arguments such as `'arthur@example.com'` in the logged statements, [make statement arguments public](#database-configuration).
|
||||
|
||||
### What Are Experimental Features?
|
||||
|
||||
Since GRDB 1.0, all backwards compatibility guarantees of [semantic versioning](http://semver.org) apply: no breaking change will happen until the next major version of the library.
|
||||
@@ -8203,7 +8209,7 @@ When this is the case, there are two possible explanations:
|
||||
try db.execute(sql: "UPDATE player SET name = ?", arguments: [name])
|
||||
```
|
||||
|
||||
For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.19/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp).
|
||||
For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.20/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp).
|
||||
|
||||
|
||||
|
||||
@@ -8344,7 +8350,7 @@ This chapter has [moved](Documentation/Concurrency.md#database-snapshots).
|
||||
|
||||
#### DatabaseWriter and DatabaseReader Protocols
|
||||
|
||||
This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.19/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.19/Protocols/DatabaseWriter.html).
|
||||
This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.20/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.20/Protocols/DatabaseWriter.html).
|
||||
|
||||
#### Asynchronous APIs
|
||||
|
||||
@@ -8397,7 +8403,8 @@ This chapter was renamed to [Embedding SQL in Query Interface Requests].
|
||||
[Sharing a Database]: Documentation/SharingADatabase.md
|
||||
[FAQ]: #faq
|
||||
[Database Observation]: #database-changes-observation
|
||||
[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.19/Structs/SQLRequest.html
|
||||
[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.20/Structs/SQLRequest.html
|
||||
[SQL literal]: Documentation/SQLInterpolation.md#sql-literal
|
||||
[Identifiable]: https://developer.apple.com/documentation/swift/identifiable
|
||||
[Query Interface Organization]: Documentation/QueryInterfaceOrganization.md
|
||||
[Database Configuration]: #database-configuration
|
||||
@@ -56,6 +56,7 @@ opt_in_rules:
|
||||
- reduce_into
|
||||
- redundant_type_annotation
|
||||
- sorted_first_last
|
||||
- sorted_imports
|
||||
- toggle_bool
|
||||
- unused_declaration
|
||||
- unused_import
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>5.19.0</string>
|
||||
<string>5.20.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
- [ ] GRDB 6: UPSERT
|
||||
- [ ] GRDB 6: support for RETURNING
|
||||
- [ ] GRDB 6: allow mutating `update` (for timestamps)
|
||||
- [ ] GRDB 6: choose persistence table
|
||||
- [ ] Long run edition. Use case: user edits the database (CRUD) but the application wants to commit and the end of the editing session.
|
||||
* Create an edition SQLite connection with an open transaction (a new kind of DatabaseWriter with a save() method)
|
||||
* All other writes will fail with SQLITE_BUSY. Unless they are schedules in a target dispatch queue which is paused during the edition.
|
||||
|
||||
@@ -411,12 +411,12 @@ class DatabaseWriterWritePublisherTests : XCTestCase {
|
||||
// print(iteration)
|
||||
let scoreSubject = PassthroughSubject<Int, Error>()
|
||||
let publisher = scoreSubject
|
||||
.map({ score in
|
||||
.map { score in
|
||||
writer.writePublisher { db -> Int in
|
||||
try Player(id: 1, name: "Arthur", score: score).insert(db)
|
||||
return try Player.fetchCount(db)
|
||||
}
|
||||
})
|
||||
}
|
||||
.switchToLatest()
|
||||
.prefix(1)
|
||||
let recorder = publisher.record()
|
||||
|
||||
@@ -278,6 +278,29 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
|
||||
WHERE ("name" = 'foo') AND (("pA", "pB") IN "grdb_base")
|
||||
"""])
|
||||
}
|
||||
|
||||
// Limited ordered request (preserve both ordering and limit in the CTE)
|
||||
do {
|
||||
let request = Parent
|
||||
.including(all: Parent.hasMany(Child.self))
|
||||
.orderByPrimaryKey()
|
||||
.limit(1)
|
||||
|
||||
sqlQueries.removeAll()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "parent" ORDER BY "parentA", "parentB" LIMIT 1
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent" ORDER BY "parentA", "parentB" LIMIT 1) \
|
||||
SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB" \
|
||||
FROM "child" \
|
||||
WHERE ("pA", "pB") IN "grdb_base"
|
||||
"""])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,52 @@ class DatabaseCursorTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: this test should be duplicated for all cursor types
|
||||
func testNextFollowedByForEach() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
let cursor = try Int.fetchCursor(db, sql: "SELECT 1")
|
||||
XCTAssertEqual(try cursor.next()!, 1)
|
||||
try cursor.forEach { _ in
|
||||
XCTFail("Cursor iteration should have ended")
|
||||
}
|
||||
XCTAssert(try cursor.next() == nil) // end
|
||||
}
|
||||
do {
|
||||
let cursor = try Int.fetchCursor(db, sql: "SELECT 1 UNION SELECT 2")
|
||||
XCTAssertEqual(try cursor.next()!, 1)
|
||||
try cursor.forEach { i in
|
||||
XCTAssertEqual(i, 2)
|
||||
}
|
||||
XCTAssert(try cursor.next() == nil) // end
|
||||
}
|
||||
do {
|
||||
let cursor = try Int.fetchCursor(db, sql: "SELECT 1 UNION SELECT 2 UNION SELECT 3")
|
||||
XCTAssertEqual(try cursor.next()!, 1)
|
||||
try XCTAssertEqual(Array(cursor), [2, 3])
|
||||
XCTAssert(try cursor.next() == nil) // end
|
||||
}
|
||||
do {
|
||||
struct Break: Error { }
|
||||
let cursor = try Int.fetchCursor(db, sql: "SELECT 1 UNION SELECT 2 UNION SELECT 3")
|
||||
try? cursor.forEach { i in
|
||||
XCTAssertEqual(i, 1)
|
||||
throw Break()
|
||||
}
|
||||
try? cursor.forEach { i in
|
||||
XCTAssertEqual(i, 2)
|
||||
throw Break()
|
||||
}
|
||||
try? cursor.forEach { i in
|
||||
XCTAssertEqual(i, 3)
|
||||
throw Break()
|
||||
}
|
||||
XCTAssert(try cursor.next() == nil) // end
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: this test should be duplicated for all cursor types
|
||||
func testStepError() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
@@ -27,8 +27,8 @@ class DatabaseErrorTests: GRDBTestCase {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
|
||||
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
|
||||
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
|
||||
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
|
||||
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)`")
|
||||
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
XCTAssertEqual(sqlQueries.count, 2)
|
||||
XCTAssertEqual(sqlQueries[0], "INSERT INTO pets (masterId, name) VALUES (1, 'Bobby')")
|
||||
XCTAssertEqual(sqlQueries[1], "ROLLBACK TRANSACTION")
|
||||
@@ -60,11 +60,71 @@ class DatabaseErrorTests: GRDBTestCase {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
|
||||
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
|
||||
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
|
||||
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)`")
|
||||
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabaseErrorThrownByUpdateStatementContainSQLAndArguments() throws {
|
||||
func testDatabaseErrorThrownByUpdateStatementContainSQLAndNoPrivateArguments() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY)")
|
||||
try db.execute(sql: "CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT)")
|
||||
}
|
||||
|
||||
// db.execute(sql, arguments)
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [1, "Bobby"])
|
||||
XCTFail()
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
|
||||
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
|
||||
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
|
||||
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)`")
|
||||
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
}
|
||||
}
|
||||
|
||||
// statement.execute(arguments)
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
let statement = try db.makeStatement(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)")
|
||||
try statement.execute(arguments: [1, "Bobby"])
|
||||
XCTFail()
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
|
||||
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
|
||||
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
|
||||
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)`")
|
||||
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
}
|
||||
}
|
||||
|
||||
// statement.execute()
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
let statement = try db.makeStatement(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)")
|
||||
statement.arguments = [1, "Bobby"]
|
||||
try statement.execute()
|
||||
XCTFail()
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
|
||||
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
|
||||
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
|
||||
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)`")
|
||||
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabaseErrorThrownByUpdateStatementContainSQLAndPublicArguments() throws {
|
||||
// Opt in for public statement arguments
|
||||
dbConfiguration.publicStatementArguments = true
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY)")
|
||||
@@ -82,6 +142,7 @@ class DatabaseErrorTests: GRDBTestCase {
|
||||
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
|
||||
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
|
||||
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,6 +158,7 @@ class DatabaseErrorTests: GRDBTestCase {
|
||||
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
|
||||
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
|
||||
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,6 +175,7 @@ class DatabaseErrorTests: GRDBTestCase {
|
||||
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
|
||||
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
|
||||
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -133,6 +196,7 @@ class DatabaseErrorTests: GRDBTestCase {
|
||||
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
|
||||
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (1, 'Bobby')")
|
||||
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (1, 'bobby')`")
|
||||
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (1, 'bobby')`")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -165,5 +229,4 @@ class DatabaseErrorTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -772,7 +772,7 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
}
|
||||
|
||||
// Regression test for https://github.com/groue/GRDB.swift/issues/741
|
||||
func testEraseDatabaseOnSchemaChangeDoesNotDeadLock() throws {
|
||||
func testEraseDatabaseOnSchemaChangeDoesNotDeadLockOnTargetQueue() throws {
|
||||
dbConfiguration.targetQueue = DispatchQueue(label: "target")
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
@@ -785,6 +785,20 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
try migrator.migrate(dbQueue)
|
||||
}
|
||||
|
||||
// Regression test for https://github.com/groue/GRDB.swift/issues/741
|
||||
func testEraseDatabaseOnSchemaChangeDoesNotDeadLockOnWriteTargetQueue() throws {
|
||||
dbConfiguration.writeTargetQueue = DispatchQueue(label: "writerTarget")
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
migrator.registerMigration("1", migrate: { _ in })
|
||||
try migrator.migrate(dbQueue)
|
||||
|
||||
migrator.registerMigration("2", migrate: { _ in })
|
||||
try migrator.migrate(dbQueue)
|
||||
}
|
||||
|
||||
func testEraseDatabaseOnSchemaChange() throws {
|
||||
// 1st version of the migrator
|
||||
var migrator1 = DatabaseMigrator()
|
||||
|
||||
@@ -994,6 +994,60 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
waitForExpectations(timeout: 2, handler: nil)
|
||||
}
|
||||
|
||||
func testWriteTargetQueue() throws {
|
||||
guard #available(OSX 10.12, tvOS 10.0, *) else {
|
||||
throw XCTSkip("dispatchPrecondition(condition:) is not available")
|
||||
}
|
||||
|
||||
func test(targetQueue: DispatchQueue, writeTargetQueue: DispatchQueue) throws {
|
||||
dbConfiguration.targetQueue = targetQueue
|
||||
dbConfiguration.writeTargetQueue = writeTargetQueue
|
||||
let dbPool = try makeDatabasePool()
|
||||
try dbPool.write { _ in
|
||||
dispatchPrecondition(condition: .onQueue(writeTargetQueue))
|
||||
}
|
||||
try dbPool.read { _ in
|
||||
dispatchPrecondition(condition: .onQueue(targetQueue))
|
||||
}
|
||||
}
|
||||
|
||||
// background queue
|
||||
try test(targetQueue: .global(qos: .background), writeTargetQueue: DispatchQueue(label: "writer"))
|
||||
|
||||
// main queue
|
||||
let expectation = self.expectation(description: "main")
|
||||
DispatchQueue.global(qos: .default).async {
|
||||
try! test(targetQueue: .main, writeTargetQueue: .main)
|
||||
expectation.fulfill()
|
||||
}
|
||||
waitForExpectations(timeout: 2, handler: nil)
|
||||
}
|
||||
|
||||
func testWriteTargetQueueReadOnly() throws {
|
||||
guard #available(OSX 10.12, tvOS 10.0, *) else {
|
||||
throw XCTSkip("dispatchPrecondition(condition:) is not available")
|
||||
}
|
||||
|
||||
// Create a database before we perform read-only accesses
|
||||
_ = try makeDatabasePool(filename: "test")
|
||||
|
||||
func test(targetQueue: DispatchQueue, writeTargetQueue: DispatchQueue) throws {
|
||||
dbConfiguration.readonly = true
|
||||
dbConfiguration.targetQueue = targetQueue
|
||||
dbConfiguration.writeTargetQueue = writeTargetQueue // unused
|
||||
let dbPool = try makeDatabasePool(filename: "test")
|
||||
try dbPool.write { _ in
|
||||
// Not on writeTargetQueue because read-only
|
||||
dispatchPrecondition(condition: .onQueue(targetQueue))
|
||||
}
|
||||
try dbPool.read { _ in
|
||||
dispatchPrecondition(condition: .onQueue(targetQueue))
|
||||
}
|
||||
}
|
||||
|
||||
try test(targetQueue: .global(qos: .background), writeTargetQueue: DispatchQueue(label: "writer"))
|
||||
}
|
||||
|
||||
func testQoS() throws {
|
||||
guard #available(OSX 10.12, tvOS 10.0, *) else {
|
||||
throw XCTSkip("dispatchPrecondition(condition:) is not available")
|
||||
|
||||
@@ -152,6 +152,59 @@ class DatabaseQueueTests: GRDBTestCase {
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
}
|
||||
|
||||
func testWriteTargetQueue() throws {
|
||||
guard #available(OSX 10.12, tvOS 10.0, *) else {
|
||||
throw XCTSkip("dispatchPrecondition(condition:) is not available")
|
||||
}
|
||||
|
||||
func test(targetQueue: DispatchQueue, writeTargetQueue: DispatchQueue) throws {
|
||||
dbConfiguration.targetQueue = targetQueue // unused
|
||||
dbConfiguration.writeTargetQueue = writeTargetQueue
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { _ in
|
||||
dispatchPrecondition(condition: .onQueue(writeTargetQueue))
|
||||
}
|
||||
try dbQueue.read { _ in
|
||||
dispatchPrecondition(condition: .onQueue(writeTargetQueue))
|
||||
}
|
||||
}
|
||||
|
||||
// background queue
|
||||
try test(targetQueue: .global(qos: .background), writeTargetQueue: DispatchQueue(label: "writer"))
|
||||
|
||||
// main queue
|
||||
let expectation = self.expectation(description: "main")
|
||||
DispatchQueue.global(qos: .default).async {
|
||||
try! test(targetQueue: .main, writeTargetQueue: .main)
|
||||
expectation.fulfill()
|
||||
}
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
}
|
||||
|
||||
func testWriteTargetQueueReadOnly() throws {
|
||||
guard #available(OSX 10.12, tvOS 10.0, *) else {
|
||||
throw XCTSkip("dispatchPrecondition(condition:) is not available")
|
||||
}
|
||||
|
||||
// Create a database before we perform read-only accesses
|
||||
_ = try makeDatabaseQueue(filename: "test")
|
||||
|
||||
func test(targetQueue: DispatchQueue, writeTargetQueue: DispatchQueue) throws {
|
||||
dbConfiguration.readonly = true
|
||||
dbConfiguration.targetQueue = targetQueue
|
||||
dbConfiguration.writeTargetQueue = writeTargetQueue // unused
|
||||
let dbQueue = try makeDatabaseQueue(filename: "test")
|
||||
try dbQueue.write { _ in
|
||||
dispatchPrecondition(condition: .onQueue(targetQueue))
|
||||
}
|
||||
try dbQueue.read { _ in
|
||||
dispatchPrecondition(condition: .onQueue(targetQueue))
|
||||
}
|
||||
}
|
||||
|
||||
try test(targetQueue: .global(qos: .background), writeTargetQueue: DispatchQueue(label: "writer"))
|
||||
}
|
||||
|
||||
func testQoS() throws {
|
||||
guard #available(OSX 10.12, tvOS 10.0, *) else {
|
||||
throw XCTSkip("dispatchPrecondition(condition:) is not available")
|
||||
|
||||
@@ -31,8 +31,10 @@ class DatabaseTraceTests : GRDBTestCase {
|
||||
try dbQueue.inDatabase { db in
|
||||
var lastSQL: String?
|
||||
var lastDescription: String?
|
||||
var lastExpandedDescription: String?
|
||||
db.trace(options: .statement) { event in
|
||||
lastDescription = event.description
|
||||
lastExpandedDescription = event.expandedDescription
|
||||
switch event {
|
||||
case let .statement(statement):
|
||||
lastSQL = statement.sql
|
||||
@@ -43,10 +45,12 @@ class DatabaseTraceTests : GRDBTestCase {
|
||||
try db.execute(sql: "CREATE table t(a);")
|
||||
XCTAssertEqual(lastSQL, "CREATE table t(a)")
|
||||
XCTAssertEqual(lastDescription, "CREATE table t(a)")
|
||||
XCTAssertEqual(lastExpandedDescription, "CREATE table t(a)")
|
||||
|
||||
try db.execute(sql: "INSERT INTO t (a) VALUES (?)", arguments: [1])
|
||||
XCTAssertEqual(lastSQL, "INSERT INTO t (a) VALUES (?)")
|
||||
XCTAssertEqual(lastDescription, "INSERT INTO t (a) VALUES (1)")
|
||||
XCTAssertEqual(lastDescription, "INSERT INTO t (a) VALUES (?)")
|
||||
XCTAssertEqual(lastExpandedDescription, "INSERT INTO t (a) VALUES (1)")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,8 +65,10 @@ class DatabaseTraceTests : GRDBTestCase {
|
||||
var lastExpandedSQL: String?
|
||||
var lastDuration: TimeInterval?
|
||||
var lastDescription: String?
|
||||
var lastExpandedDescription: String?
|
||||
db.trace(options: .profile) { event in
|
||||
lastDescription = event.description
|
||||
lastExpandedDescription = event.expandedDescription
|
||||
switch event {
|
||||
case let .profile(statement: statement, duration: duration):
|
||||
lastSQL = statement.sql
|
||||
@@ -77,12 +83,14 @@ class DatabaseTraceTests : GRDBTestCase {
|
||||
XCTAssertEqual(lastExpandedSQL, "CREATE table t(a)")
|
||||
XCTAssertTrue(lastDuration! >= 0)
|
||||
XCTAssert(lastDescription!.hasSuffix("s CREATE table t(a)"))
|
||||
XCTAssert(lastExpandedDescription!.hasSuffix("s CREATE table t(a)"))
|
||||
|
||||
try db.execute(sql: "INSERT INTO t (a) VALUES (?)", arguments: [1])
|
||||
XCTAssertEqual(lastSQL, "INSERT INTO t (a) VALUES (?)")
|
||||
XCTAssertEqual(lastExpandedSQL, "INSERT INTO t (a) VALUES (1)")
|
||||
XCTAssertTrue(lastDuration! >= 0)
|
||||
XCTAssert(lastDescription!.hasSuffix("s INSERT INTO t (a) VALUES (1)"))
|
||||
XCTAssert(lastDescription!.hasSuffix("s INSERT INTO t (a) VALUES (?)"))
|
||||
XCTAssert(lastExpandedDescription!.hasSuffix("s INSERT INTO t (a) VALUES (1)"))
|
||||
|
||||
db.add(function: DatabaseFunction("wait", argumentCount: 1, pure: true, function: { dbValues in
|
||||
if let delay = TimeInterval.fromDatabaseValue(dbValues[0]) {
|
||||
@@ -96,7 +104,8 @@ class DatabaseTraceTests : GRDBTestCase {
|
||||
XCTAssertEqual(lastExpandedSQL, "SELECT wait(0.5)")
|
||||
XCTAssertGreaterThan(lastDuration!, 0.4)
|
||||
XCTAssertLessThan(lastDuration!, 2) // Travis can be so slow
|
||||
XCTAssert(lastDescription!.hasSuffix("s SELECT wait(0.5)"))
|
||||
XCTAssert(lastDescription!.hasSuffix("s SELECT wait(?)"))
|
||||
XCTAssert(lastExpandedDescription!.hasSuffix("s SELECT wait(0.5)"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,6 +134,27 @@ class DatabaseTraceTests : GRDBTestCase {
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue(configuration: configuration)
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: """
|
||||
CREATE table t(a);
|
||||
INSERT INTO t (a) VALUES (?)
|
||||
""", arguments: [1])
|
||||
XCTAssertEqual(events.suffix(2), [
|
||||
"SQL: CREATE table t(a)",
|
||||
"SQL: INSERT INTO t (a) VALUES (?)"])
|
||||
}
|
||||
}
|
||||
|
||||
func testTraceFromConfigurationWithPublicStatementArguments() throws {
|
||||
var events: [String] = []
|
||||
var configuration = Configuration()
|
||||
configuration.publicStatementArguments = true
|
||||
configuration.prepareDatabase { db in
|
||||
db.trace { event in
|
||||
events.append("SQL: \(event)")
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue(configuration: configuration)
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: """
|
||||
CREATE table t(a);
|
||||
|
||||
@@ -534,9 +534,9 @@ class EncryptionTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
|
||||
try dbQueue.inDatabase({ db in
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertEqual(try Int.fetchOne(db, sql: "PRAGMA cipher_page_size")!, 8192)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
@@ -547,16 +547,15 @@ class EncryptionTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
let dbPool = try makeDatabasePool(filename: "testpool.sqlite", configuration: config)
|
||||
try dbPool.write({ db in
|
||||
try dbPool.write { db in
|
||||
XCTAssertEqual(try Int.fetchOne(db, sql: "PRAGMA cipher_page_size")!, 4096)
|
||||
try db.execute(sql: "CREATE TABLE data(value INTEGER)")
|
||||
try db.execute(sql: "INSERT INTO data(value) VALUES(1)")
|
||||
})
|
||||
try dbPool.read({ db in
|
||||
}
|
||||
try dbPool.read { db in
|
||||
XCTAssertEqual(try Int.fetchOne(db, sql: "PRAGMA cipher_page_size")!, 4096)
|
||||
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT value FROM data"), 1)
|
||||
})
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -684,7 +683,7 @@ class EncryptionTests: GRDBTestCase {
|
||||
guard let cipherMajorVersion = try DatabaseQueue()
|
||||
.read({ try String.fetchOne($0, sql: "PRAGMA cipher_version") })
|
||||
.flatMap({ $0.split(separator: ".").first })
|
||||
.flatMap({ Int($0 )})
|
||||
.flatMap({ Int($0) })
|
||||
else { XCTFail("Unknown SQLCipher version"); return }
|
||||
|
||||
if cipherMajorVersion >= 4 {
|
||||
|
||||
@@ -105,7 +105,7 @@ class GRDBTestCase: XCTestCase {
|
||||
|
||||
dbConfiguration.prepareDatabase { db in
|
||||
db.trace { event in
|
||||
self.sqlQueries.append(event.description)
|
||||
self.sqlQueries.append(event.expandedDescription)
|
||||
}
|
||||
|
||||
#if GRDBCIPHER_USE_ENCRYPTION
|
||||
|
||||
@@ -85,6 +85,53 @@ class TruncateOptimizationTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testExecuteDeleteCaseSensitivity() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
class DeletionObserver : TransactionObserver {
|
||||
var deletionCount = 0
|
||||
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
if case .delete(tableName: "pLaYeR") = eventKind {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
if case .delete = event.kind {
|
||||
deletionCount += 1
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidCommit(_ db: Database) { }
|
||||
func databaseDidRollback(_ db: Database) { }
|
||||
}
|
||||
|
||||
let observer = DeletionObserver()
|
||||
dbQueue.add(transactionObserver: observer, extent: .databaseLifetime)
|
||||
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
observer.deletionCount = 0
|
||||
try db.execute(sql: "CREATE TABLE pLaYeR(a)")
|
||||
try db.execute(sql: "INSERT INTO pLaYeR VALUES (NULL)")
|
||||
try db.execute(sql: "INSERT INTO pLaYeR VALUES (NULL)")
|
||||
try db.execute(sql: "DELETE FROM pLaYeR")
|
||||
XCTAssertEqual(observer.deletionCount, 2)
|
||||
|
||||
observer.deletionCount = 0
|
||||
try db.execute(sql: "INSERT INTO pLaYeR VALUES (NULL)")
|
||||
try db.execute(sql: "DELETE FROM PLAYER")
|
||||
XCTAssertEqual(observer.deletionCount, 1)
|
||||
|
||||
observer.deletionCount = 0
|
||||
try db.execute(sql: "INSERT INTO pLaYeR VALUES (NULL)")
|
||||
try db.execute(sql: "DELETE FROM player")
|
||||
XCTAssertEqual(observer.deletionCount, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func testExecuteDeleteWithPreparedStatement() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
@@ -111,6 +158,37 @@ class TruncateOptimizationTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testExecuteDeleteWithCachedPreparedStatement() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
var deletionEvents: [[String: Int]] = []
|
||||
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
try db.execute(sql: "CREATE TABLE t(a)")
|
||||
try db.cachedStatement(sql: "DELETE FROM t").execute()
|
||||
|
||||
// Start observing after statement has been cached: it does not
|
||||
// prevent the truncate optimization.
|
||||
let observer = DeletionObserver { deletionEvents.append($0) }
|
||||
db.add(transactionObserver: observer, extent: .databaseLifetime)
|
||||
|
||||
try db.execute(sql: "INSERT INTO t VALUES (NULL)")
|
||||
try db.execute(sql: "INSERT INTO t VALUES (NULL)")
|
||||
deletionEvents = []
|
||||
// This must be a recompiled statement, so that the truncate
|
||||
// optimization is prevented.
|
||||
try db.cachedStatement(sql: "DELETE FROM t").execute()
|
||||
XCTAssertEqual(deletionEvents.count, 1)
|
||||
XCTAssertEqual(deletionEvents[0], ["t": 2])
|
||||
|
||||
try db.execute(sql: "INSERT INTO t VALUES (NULL)")
|
||||
deletionEvents = []
|
||||
try db.cachedStatement(sql: "DELETE FROM t").execute()
|
||||
XCTAssertEqual(deletionEvents.count, 1)
|
||||
XCTAssertEqual(deletionEvents[0], ["t": 1])
|
||||
}
|
||||
}
|
||||
|
||||
func testDropTable() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
|
||||
@@ -394,7 +394,7 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
// transaction observer, some write did happen.
|
||||
var needsChange = true
|
||||
let observation = ValueObservation
|
||||
.trackingConstantRegion({ db -> Int? in
|
||||
.trackingConstantRegion { db -> Int? in
|
||||
if needsChange {
|
||||
needsChange = false
|
||||
try dbPool.write { db in
|
||||
@@ -405,7 +405,7 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
return try Int.fetchOne(db, sql: "SELECT MAX(id) FROM player")
|
||||
})
|
||||
}
|
||||
.print(to: logger)
|
||||
|
||||
let expectedRegion = try region(sql: "SELECT MAX(id) FROM player", in: dbPool)
|
||||
@@ -441,7 +441,7 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
// transaction observer, some write did happen.
|
||||
var needsChange = true
|
||||
let observation = ValueObservation
|
||||
.trackingConstantRegion({ db -> Int? in
|
||||
.trackingConstantRegion { db -> Int? in
|
||||
if needsChange {
|
||||
needsChange = false
|
||||
try dbPool.write { db in
|
||||
@@ -452,7 +452,7 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
return try Int.fetchOne(db, sql: "SELECT MAX(id) FROM player")
|
||||
})
|
||||
}
|
||||
.print(to: logger)
|
||||
|
||||
let expectedRegion = try region(sql: "SELECT MAX(id) FROM player", in: dbPool)
|
||||
@@ -491,10 +491,10 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
|
||||
let logger = TestStream()
|
||||
let observation = ValueObservation
|
||||
.tracking({ db -> Int? in
|
||||
.tracking { db -> Int? in
|
||||
let table = try String.fetchOne(db, sql: "SELECT t FROM choice")!
|
||||
return try Int.fetchOne(db, sql: "SELECT MAX(id) FROM \(table)")
|
||||
})
|
||||
}
|
||||
.print(to: logger)
|
||||
|
||||
let expectedRegionA = try region(sql: "SELECT MAX(id) FROM a", in: dbQueue)
|
||||
|
||||
@@ -137,10 +137,10 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
|
||||
|
||||
var regions: [DatabaseRegion] = []
|
||||
let observation = ValueObservation
|
||||
.tracking({ db -> Int in
|
||||
.tracking { db -> Int in
|
||||
let table = try String.fetchOne(db, sql: "SELECT name FROM source")!
|
||||
return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")!
|
||||
})
|
||||
}
|
||||
.handleEvents(willTrackRegion: { regions.append($0) })
|
||||
|
||||
let observer = observation.start(
|
||||
@@ -188,10 +188,10 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
|
||||
|
||||
var regions: [DatabaseRegion] = []
|
||||
let observation = ValueObservation
|
||||
.tracking({ db -> Int in
|
||||
.tracking { db -> Int in
|
||||
let table = try String.fetchOne(db, sql: "SELECT name FROM source")!
|
||||
return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")!
|
||||
})
|
||||
}
|
||||
.handleEvents(willTrackRegion: { regions.append($0) })
|
||||
|
||||
let observer = observation.start(
|
||||
|
||||
@@ -11,8 +11,6 @@
|
||||
560C98241C0E23BB00BF8471 /* PerformanceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CA22211BB41565009A04C5 /* PerformanceTests.swift */; };
|
||||
561C25912439C92D001227F2 /* SQLite in Frameworks */ = {isa = PBXBuildFile; productRef = 561C25902439C92D001227F2 /* SQLite */; };
|
||||
561C25942439C942001227F2 /* FMDB in Frameworks */ = {isa = PBXBuildFile; productRef = 561C25932439C942001227F2 /* FMDB */; };
|
||||
561C25972439CBC0001227F2 /* Realm in Frameworks */ = {isa = PBXBuildFile; productRef = 561C25962439CBC0001227F2 /* Realm */; };
|
||||
561C25992439CBC0001227F2 /* RealmSwift in Frameworks */ = {isa = PBXBuildFile; productRef = 561C25982439CBC0001227F2 /* RealmSwift */; };
|
||||
56439B341F4CA1DC0066043F /* InsertRecordClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB86121BA9886D001F9168 /* InsertRecordClassTests.swift */; };
|
||||
56439B361F4CA1DC0066043F /* FetchRecordClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B2B1C41311900861EB8 /* FetchRecordClassTests.swift */; };
|
||||
56439B381F4CA1DC0066043F /* FetchNamedValuesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B271C41302500861EB8 /* FetchNamedValuesTests.swift */; };
|
||||
@@ -31,6 +29,8 @@
|
||||
5690AFD92120589A001530EA /* InsertRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFD72120589A001530EA /* InsertRecordEncodableTests.swift */; };
|
||||
5690AFDB212058CB001530EA /* FetchRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFDA212058CB001530EA /* FetchRecordDecodableTests.swift */; };
|
||||
5690AFDC212058CB001530EA /* FetchRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFDA212058CB001530EA /* FetchRecordDecodableTests.swift */; };
|
||||
56A3FEA827A85F4800B0292E /* Realm in Frameworks */ = {isa = PBXBuildFile; productRef = 56A3FEA727A85F4800B0292E /* Realm */; };
|
||||
56A3FEAA27A85F4800B0292E /* RealmSwift in Frameworks */ = {isa = PBXBuildFile; productRef = 56A3FEA927A85F4800B0292E /* RealmSwift */; };
|
||||
56B6D0E52618BF78003CC455 /* FetchRecordOptimizedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D0E42618BF78003CC455 /* FetchRecordOptimizedTests.swift */; };
|
||||
56B6D0E62618BF78003CC455 /* FetchRecordOptimizedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D0E42618BF78003CC455 /* FetchRecordOptimizedTests.swift */; };
|
||||
56B6D0EA2618C00C003CC455 /* InsertRecordOptimizedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D0E92618C00C003CC455 /* InsertRecordOptimizedTests.swift */; };
|
||||
@@ -169,12 +169,12 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
561C25992439CBC0001227F2 /* RealmSwift in Frameworks */,
|
||||
56A3FEAA27A85F4800B0292E /* RealmSwift in Frameworks */,
|
||||
561C25912439C92D001227F2 /* SQLite in Frameworks */,
|
||||
561C25942439C942001227F2 /* FMDB in Frameworks */,
|
||||
5679870523A37A790076902D /* GRDB.framework in Frameworks */,
|
||||
56439B431F4CA1DC0066043F /* CoreData.framework in Frameworks */,
|
||||
561C25972439CBC0001227F2 /* Realm in Frameworks */,
|
||||
56A3FEA827A85F4800B0292E /* Realm in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -300,8 +300,8 @@
|
||||
packageProductDependencies = (
|
||||
561C25902439C92D001227F2 /* SQLite */,
|
||||
561C25932439C942001227F2 /* FMDB */,
|
||||
561C25962439CBC0001227F2 /* Realm */,
|
||||
561C25982439CBC0001227F2 /* RealmSwift */,
|
||||
56A3FEA727A85F4800B0292E /* Realm */,
|
||||
56A3FEA927A85F4800B0292E /* RealmSwift */,
|
||||
);
|
||||
productName = GRDBOSXTests;
|
||||
productReference = 56439B501F4CA1DC0066043F /* GRDBOSXPerformanceComparisonTests.xctest */;
|
||||
@@ -329,7 +329,7 @@
|
||||
packageReferences = (
|
||||
561C258F2439C92D001227F2 /* XCRemoteSwiftPackageReference "SQLite.swift" */,
|
||||
561C25922439C942001227F2 /* XCRemoteSwiftPackageReference "fmdb" */,
|
||||
561C25952439CBC0001227F2 /* XCRemoteSwiftPackageReference "realm-cocoa" */,
|
||||
56A3FEA627A85F4800B0292E /* XCRemoteSwiftPackageReference "realm-swift" */,
|
||||
);
|
||||
productRefGroup = DC3773F419C8CBB3004FCF85 /* Products */;
|
||||
projectDirPath = "";
|
||||
@@ -733,12 +733,12 @@
|
||||
minimumVersion = 2.7.0;
|
||||
};
|
||||
};
|
||||
561C25952439CBC0001227F2 /* XCRemoteSwiftPackageReference "realm-cocoa" */ = {
|
||||
56A3FEA627A85F4800B0292E /* XCRemoteSwiftPackageReference "realm-swift" */ = {
|
||||
isa = XCRemoteSwiftPackageReference;
|
||||
repositoryURL = "https://github.com/realm/realm-cocoa.git";
|
||||
repositoryURL = "https://github.com/realm/realm-swift.git";
|
||||
requirement = {
|
||||
kind = upToNextMajorVersion;
|
||||
minimumVersion = 10.5.0;
|
||||
minimumVersion = 10.22.0;
|
||||
};
|
||||
};
|
||||
/* End XCRemoteSwiftPackageReference section */
|
||||
@@ -754,14 +754,14 @@
|
||||
package = 561C25922439C942001227F2 /* XCRemoteSwiftPackageReference "fmdb" */;
|
||||
productName = FMDB;
|
||||
};
|
||||
561C25962439CBC0001227F2 /* Realm */ = {
|
||||
56A3FEA727A85F4800B0292E /* Realm */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = 561C25952439CBC0001227F2 /* XCRemoteSwiftPackageReference "realm-cocoa" */;
|
||||
package = 56A3FEA627A85F4800B0292E /* XCRemoteSwiftPackageReference "realm-swift" */;
|
||||
productName = Realm;
|
||||
};
|
||||
561C25982439CBC0001227F2 /* RealmSwift */ = {
|
||||
56A3FEA927A85F4800B0292E /* RealmSwift */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = 561C25952439CBC0001227F2 /* XCRemoteSwiftPackageReference "realm-cocoa" */;
|
||||
package = 56A3FEA627A85F4800B0292E /* XCRemoteSwiftPackageReference "realm-swift" */;
|
||||
productName = RealmSwift;
|
||||
};
|
||||
/* End XCSwiftPackageProductDependency section */
|
||||
|
||||
+13
-13
@@ -10,22 +10,22 @@
|
||||
"version": "2.7.7"
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "Realm",
|
||||
"repositoryURL": "https://github.com/realm/realm-cocoa.git",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "f483fa0a52f6d49897d133a827510a35e21183c1",
|
||||
"version": "10.20.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "RealmDatabase",
|
||||
"repositoryURL": "https://github.com/realm/realm-core",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "c3c11a841642ac93c27bd1edd61f989fc0bfb809",
|
||||
"version": "11.6.1"
|
||||
"revision": "6b81f1a7a2d421f9e0b9e7f04e76bcf736a54409",
|
||||
"version": "11.9.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "Realm",
|
||||
"repositoryURL": "https://github.com/realm/realm-swift.git",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "9dff9f2862240d521ad6ad599541269177ddb993",
|
||||
"version": "10.22.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -33,8 +33,8 @@
|
||||
"repositoryURL": "https://github.com/stephencelis/SQLite.swift.git",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "60a65015f6402b7c34b9a924f755ca0a73afeeaa",
|
||||
"version": "0.13.1"
|
||||
"revision": "5f5ad81ac0d0a0f3e56e39e646e8423c617df523",
|
||||
"version": "0.13.2"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
Reference in new issue
Block a user