diff --git a/CHANGELOG.md b/CHANGELOG.md index cd2f6e21b..3f5f781e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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) diff --git a/Documentation/Concurrency.md b/Documentation/Concurrency.md index fac7c9fe7..79ddf380b 100644 --- a/Documentation/Concurrency.md +++ b/Documentation/Concurrency.md @@ -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: diff --git a/Documentation/FullTextSearch.md b/Documentation/FullTextSearch.md index 9d49b00c9..0ea3a273b 100644 --- a/Documentation/FullTextSearch.md +++ b/Documentation/FullTextSearch.md @@ -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, diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index 568c85829..504a50fcd 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -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 diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index be0a415ca..f8a2419a3 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -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.' diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index d995ac114..746f969a6 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -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 { diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index cabe9073e..c91d7fe3d 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -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) } + } } diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 515fd6fc1..ba0a63a87 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -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.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 + .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(_ 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(_ 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?, - sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer?) + sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer?, + 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 diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index 35eb51ea7..d17c4640b 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -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)" diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 8008def5a..5213e85d3 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -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 } diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index d3e54392e..0b2109089 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -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: ",") } } diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index 153809d54..2abf47706 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -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 diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index a4c68fecd..481ea3d05 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -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 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 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) diff --git a/GRDB/Core/SchedulingWatchdog.swift b/GRDB/Core/SchedulingWatchdog.swift index 1f836b841..28f3ede1d 100644 --- a/GRDB/Core/SchedulingWatchdog.swift +++ b/GRDB/Core/SchedulingWatchdog.swift @@ -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? { diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index d3a66f20c..bda271c83 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -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 { diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index fa9e75946..5d6a2558b 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -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(_ 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(_ 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" } } diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index 2391cf3ce..8f3cbbf00 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -2,29 +2,19 @@ import Glibc #endif -/// A protocol around sqlite3_set_authorizer -@usableFromInline -protocol StatementAuthorizer: AnyObject { - func authorize( - _ actionCode: Int32, - _ cString1: UnsafePointer?, - _ cString2: UnsafePointer?, - _ cString3: UnsafePointer?, - _ cString4: UnsafePointer?) - -> 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?, @@ -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?, - _ cString2: UnsafePointer?, - _ cString3: UnsafePointer?, - _ cString4: UnsafePointer?) - -> 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 diff --git a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift index 06c458829..f2163cd75 100644 --- a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift +++ b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift @@ -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 diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index a66c13805..c9a0a0982 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -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 { diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 099c75c21..fd704b9a8 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -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 diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index ae557f96b..83f22d3a3 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -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( diff --git a/GRDB/QueryInterface/SQL/SQLAssociation.swift b/GRDB/QueryInterface/SQL/SQLAssociation.swift index f756bc22d..84c75974f 100644 --- a/GRDB/QueryInterface/SQL/SQLAssociation.swift +++ b/GRDB/QueryInterface/SQL/SQLAssociation.swift @@ -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) diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index b6b65c9e0..a0fb30551 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -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 diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index a5cd00f91..0bf05666d 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -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) diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 47c0c466f..1a02fe384 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -554,9 +554,9 @@ public enum DatabaseColumnEncodingStrategy { searchRange = lowerCaseRange.upperBound..(on scheduler: S, options: S.SchedulerOptions? = nil) -> ReceiveValuesOn { - return ReceiveValuesOn(upstream: self, context: scheduler, options: options) + ReceiveValuesOn(upstream: self, context: scheduler, options: options) } } #endif diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 49d6318f9..b5d1a2be2 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -187,7 +187,7 @@ extension ValueObservation: Refinable { -> ValueObservation> { 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) diff --git a/Makefile b/Makefile index ae660cc90..e7313095e 100644 --- a/Makefile +++ b/Makefile @@ -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 diff --git a/README.md b/README.md index 6c5a29599..92ad92533 100644 --- a/README.md +++ b/README.md @@ -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 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 \ No newline at end of file diff --git a/Scripts/swiftlint.yml b/Scripts/swiftlint.yml index c1d25a25c..24ef59c58 100644 --- a/Scripts/swiftlint.yml +++ b/Scripts/swiftlint.yml @@ -56,6 +56,7 @@ opt_in_rules: - reduce_into - redundant_type_annotation - sorted_first_last + - sorted_imports - toggle_bool - unused_declaration - unused_import diff --git a/Support/Info.plist b/Support/Info.plist index 0563152d4..2775cdbed 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 5.19.0 + 5.20.0 CFBundleSignature ???? CFBundleVersion diff --git a/TODO.md b/TODO.md index 4645ef84e..912f556a3 100644 --- a/TODO.md +++ b/TODO.md @@ -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. diff --git a/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift b/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift index 242d620de..2a9ef1f85 100644 --- a/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift +++ b/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift @@ -411,12 +411,12 @@ class DatabaseWriterWritePublisherTests : XCTestCase { // print(iteration) let scoreSubject = PassthroughSubject() 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() diff --git a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift index 6666ed177..6ac24fd6b 100644 --- a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift @@ -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" + """]) + } } } diff --git a/Tests/GRDBTests/DatabaseCursorTests.swift b/Tests/GRDBTests/DatabaseCursorTests.swift index 0eec5784c..8000ee6ef 100644 --- a/Tests/GRDBTests/DatabaseCursorTests.swift +++ b/Tests/GRDBTests/DatabaseCursorTests.swift @@ -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() diff --git a/Tests/GRDBTests/DatabaseErrorTests.swift b/Tests/GRDBTests/DatabaseErrorTests.swift index 7f7155339..50666a5b3 100644 --- a/Tests/GRDBTests/DatabaseErrorTests.swift +++ b/Tests/GRDBTests/DatabaseErrorTests.swift @@ -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 { } } } - } diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index 6e141869f..f25b6d4c6 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -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() diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index b69ee0311..87ce7c2e0 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -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") diff --git a/Tests/GRDBTests/DatabaseQueueTests.swift b/Tests/GRDBTests/DatabaseQueueTests.swift index 027496ca3..2e0331844 100644 --- a/Tests/GRDBTests/DatabaseQueueTests.swift +++ b/Tests/GRDBTests/DatabaseQueueTests.swift @@ -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") diff --git a/Tests/GRDBTests/DatabaseTraceTests.swift b/Tests/GRDBTests/DatabaseTraceTests.swift index 64712d9de..478a7b15e 100644 --- a/Tests/GRDBTests/DatabaseTraceTests.swift +++ b/Tests/GRDBTests/DatabaseTraceTests.swift @@ -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); diff --git a/Tests/GRDBTests/EncryptionTests.swift b/Tests/GRDBTests/EncryptionTests.swift index 0b7a62d9d..d1ade3f7f 100644 --- a/Tests/GRDBTests/EncryptionTests.swift +++ b/Tests/GRDBTests/EncryptionTests.swift @@ -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 { diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 7b4fea5b6..f93e8ab7c 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -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 diff --git a/Tests/GRDBTests/TruncateOptimizationTests.swift b/Tests/GRDBTests/TruncateOptimizationTests.swift index a3e8b152f..d0700bb2f 100644 --- a/Tests/GRDBTests/TruncateOptimizationTests.swift +++ b/Tests/GRDBTests/TruncateOptimizationTests.swift @@ -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 diff --git a/Tests/GRDBTests/ValueObservationPrintTests.swift b/Tests/GRDBTests/ValueObservationPrintTests.swift index 41f98be64..3d1809096 100644 --- a/Tests/GRDBTests/ValueObservationPrintTests.swift +++ b/Tests/GRDBTests/ValueObservationPrintTests.swift @@ -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) diff --git a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift index 49ce4df04..30a10f22b 100644 --- a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift +++ b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift @@ -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( diff --git a/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.pbxproj b/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.pbxproj index 94644bf5e..3b8fa0f53 100755 --- a/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.pbxproj +++ b/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.pbxproj @@ -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 */ diff --git a/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 79f78821c..1eff6b9bf 100644 --- a/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -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" } } ]