From 6444285ee28ad540d0df2b11b9fc685139b54223 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 21 Jan 2022 13:39:40 +0100 Subject: [PATCH 01/35] Failing test for including(all:) on limited request and composite primary keys --- .../AssociationPrefetchingSQLTests.swift | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) 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" + """]) + } } } From 301fb3470247513f54a8eaa12673213f91ed3775 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 21 Jan 2022 13:40:00 +0100 Subject: [PATCH 02/35] Fix failing test for including(all:) on limited request and composite primary keys --- CHANGELOG.md | 5 +++++ GRDB/QueryInterface/Request/QueryInterfaceRequest.swift | 2 +- GRDB/QueryInterface/SQL/SQLRelation.swift | 9 +++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cd2f6e21b..aed8e359f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -86,6 +86,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## Next Release + +- **Fixed**: Fixed a bug of `including(all:)` for composite foreign keys and limited requests. + + ## 5.19.0 Released January 19, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.18.0...v5.19.0) 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/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) From aacc69f4856040c2862e34fde3ddc8c774c556fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 21 Jan 2022 13:43:44 +0100 Subject: [PATCH 03/35] Fix typos --- GRDB/Core/StatementAuthorizer.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index 2391cf3ce..443f8c1e1 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -22,9 +22,9 @@ final class StatementCompilationAuthorizer: StatementAuthorizer { /// 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 From 9baa72cfd739f9b053f50526c5bdac9a75448c16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 21 Jan 2022 13:48:51 +0100 Subject: [PATCH 04/35] Mention association annotation methods in the main README --- README.md | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 6c5a29599..fb4a5a9ed 100644 --- a/README.md +++ b/README.md @@ -4440,18 +4440,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 +4450,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 From 3826003d938cdd121809ddfb247a76062cb6c008 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 23 Jan 2022 10:51:15 +0100 Subject: [PATCH 05/35] TODO --- TODO.md | 1 + 1 file changed, 1 insertion(+) 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. From 09922c34ff30a7dbc6f8ae7d34bef9a00d5754fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 23 Jan 2022 12:22:51 +0100 Subject: [PATCH 06/35] Code formatting --- GRDB/Core/Configuration.swift | 2 +- GRDB/Core/DatabasePool.swift | 2 +- GRDB/Core/DatabaseRegion.swift | 4 ++-- GRDB/Core/DatabaseRegionObservation.swift | 2 +- GRDB/Core/DatabaseWriter.swift | 8 ++++---- .../Support/StandardLibrary/StandardLibrary.swift | 2 +- GRDB/QueryInterface/SQL/SQLAssociation.swift | 4 ++-- GRDB/QueryInterface/SQL/SQLExpression.swift | 2 +- GRDB/Record/EncodableRecord.swift | 6 +++--- GRDB/Record/FetchableRecord.swift | 1 - GRDB/Utils/ReceiveValuesOn.swift | 2 +- GRDB/ValueObservation/ValueObservation.swift | 4 ++-- Scripts/swiftlint.yml | 1 + .../DatabaseWriterWritePublisherTests.swift | 4 ++-- Tests/GRDBTests/EncryptionTests.swift | 15 +++++++-------- Tests/GRDBTests/ValueObservationPrintTests.swift | 12 ++++++------ .../ValueObservationRegionRecordingTests.swift | 8 ++++---- 17 files changed, 39 insertions(+), 40 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index d995ac114..397c9f5e6 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 { diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 8008def5a..27cd7ec55 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 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..7387e8d12 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -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/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/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/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/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/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/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/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( From 9f0ba49c9362159ab2beb50d66043c48d2d9a400 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 27 Jan 2022 18:56:50 +0100 Subject: [PATCH 07/35] DatabaseError.description no longer contains statement arguments Use DatabaseError.expandedDescription in order to see statements arguments --- GRDB/Core/DatabaseError.swift | 33 +++++++++++++++++++++++- Tests/GRDBTests/DatabaseErrorTests.swift | 17 +++++++----- 2 files changed, 43 insertions(+), 7 deletions(-) diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index 35eb51ea7..b75bbb555 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -404,8 +404,39 @@ extension DatabaseError { // CustomStringConvertible extension DatabaseError { - /// :nodoc: + /// The error description. + /// + /// For example: + /// + /// SQLite error 19: FOREIGN KEY constraint failed - while executing + /// `INSERT INTO pets (masterId, name) VALUES (?, ?)` + /// + /// 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)`" + } + // TODO: consider including arguments depending on database configuration, + // for easy verbose debugging when the database does not contain sensitive information. + return description + } + + /// The error description, where bound parameters, if present, are visible. + /// + /// For example: + /// + /// SQLite error 19: FOREIGN KEY constraint failed - while executing + /// `INSERT INTO pets (masterId, name) VALUES (?, ?)` + /// with arguments [1, "Bobby"] + /// + /// 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 expandedDescription: String { var description = "SQLite error \(resultCode.rawValue)" if let message = message { description += ": \(message)" diff --git a/Tests/GRDBTests/DatabaseErrorTests.swift b/Tests/GRDBTests/DatabaseErrorTests.swift index 7f7155339..2a9ced44b 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,7 +60,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\"]") } } @@ -81,7 +82,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\"]") } } @@ -96,7 +98,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\"]") } } @@ -112,7 +115,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\"]") } } } @@ -133,6 +137,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')`") } } } From d3985c7ebf265edef8cc5ad2f4de96da6b07af05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 27 Jan 2022 19:29:38 +0100 Subject: [PATCH 08/35] TraceEvent.description no longer contains statement arguments Use TraceEvent.expandedDescription in order to see statements arguments --- GRDB/Core/Database.swift | 30 ++++++++++++++++++++++++ Tests/GRDBTests/DatabaseTraceTests.swift | 17 ++++++++++---- Tests/GRDBTests/GRDBTestCase.swift | 2 +- 3 files changed, 44 insertions(+), 5 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 515fd6fc1..ecc76071f 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1714,7 +1714,37 @@ extension Database { /// An event reported by `TracingOptions.profile`. case profile(statement: Statement, duration: TimeInterval) + /// The trace event description. + /// + /// For example: + /// + /// SELECT * FROM player WHERE id = ? + /// 0.1s SELECT * FROM player WHERE id = ? + /// + /// 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 { + // TODO: consider including arguments depending on database configuration, + // for easy verbose debugging when the database does not contain sensitive information. + switch self { + case let .statement(statement): + return statement.sql + case let .profile(statement: statement, duration: duration): + let durationString = String(format: "%.3f", duration) + return "\(durationString)s \(statement.sql)" + } + } + + /// The trace event description, where bound parameters are expanded. + /// + /// For example: + /// + /// SELECT * FROM player WHERE id = 1 + /// 0.1s SELECT * FROM player WHERE id = 1 + /// + /// 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 expandedDescription: String { switch self { case let .statement(statement): return statement.expandedSQL diff --git a/Tests/GRDBTests/DatabaseTraceTests.swift b/Tests/GRDBTests/DatabaseTraceTests.swift index 64712d9de..985192e05 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)")) } } @@ -132,7 +141,7 @@ class DatabaseTraceTests : GRDBTestCase { """, arguments: [1]) XCTAssertEqual(events.suffix(2), [ "SQL: CREATE table t(a)", - "SQL: INSERT INTO t (a) VALUES (1)"]) + "SQL: INSERT INTO t (a) VALUES (?)"]) } } 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 From fc5138ae9105caaa2a8959095fe70d79541667bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 28 Jan 2022 12:38:19 +0100 Subject: [PATCH 09/35] Configuration.publicStatementArguments This flags allows database errors and trace events to hide or show statement arguments by default. --- GRDB/Core/Configuration.swift | 59 +++++++++++++++++++++ GRDB/Core/Database+Statements.swift | 3 +- GRDB/Core/Database.swift | 31 +++++++---- GRDB/Core/DatabaseError.swift | 65 +++++++++++++++++++++--- Tests/GRDBTests/DatabaseErrorTests.swift | 62 +++++++++++++++++++++- Tests/GRDBTests/DatabaseTraceTests.swift | 21 ++++++++ 6 files changed, 223 insertions(+), 18 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 397c9f5e6..aab69a7f2 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -102,6 +102,65 @@ 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 not recommended to do so in + /// release builds: + /// + /// var config = Configuration() + /// #if DEBUG + /// 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) + /// } + /// + /// Regardless of this flag, you can explicitly ask to see the + /// statement arguments with the `expandedDescription` property of database + /// errors and trace events: + /// + /// // The expanded descriptions of trace events and errors always + /// // contain the sensitive information: + /// db.trace { event in + /// print(event.expandedDescription) + /// } + /// do { + /// let email = "..." + /// let player = try Player.filter(Column("email") == email).fetchOne(db) + /// } catch let error as DatabaseError { + /// print(error.expandedDescription) + /// } + public var publicStatementArguments = false + // MARK: - Managing SQLite Connections private var setups: [(Database) throws -> Void] = [] diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index cabe9073e..7a4119528 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -589,7 +589,8 @@ extension Database { resultCode: resultCode, message: lastErrorMessage, sql: statement.sql, - arguments: statement.arguments) + arguments: statement.arguments, + publicStatementArguments: configuration.publicStatementArguments) } } diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index ecc76071f..5e7e41d8b 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -713,7 +713,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 +723,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 +899,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 +933,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib resultCode: .SQLITE_ABORT, message: "Transaction was aborted", sql: sql(), - arguments: arguments()) + arguments: arguments(), + publicStatementArguments: configuration.publicStatementArguments) } } @@ -1650,7 +1654,10 @@ extension Database { unexpandedSQL: UnsafePointer?, sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer?) } - let impl: Impl + var impl: Impl + + /// See Configuration.publicStatementArguments + var publicStatementArguments: Bool #if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS) /// The executed SQL, where bound parameters are not expanded. @@ -1724,14 +1731,20 @@ extension Database { /// 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 { - // TODO: consider including arguments depending on database configuration, - // for easy verbose debugging when the database does not contain sensitive information. switch self { case let .statement(statement): - return statement.sql + if statement.publicStatementArguments { + return statement.expandedSQL + } else { + return statement.sql + } case let .profile(statement: statement, duration: duration): let durationString = String(format: "%.3f", duration) - return "\(durationString)s \(statement.sql)" + if statement.publicStatementArguments { + return "\(durationString)s \(statement.expandedSQL)" + } else { + return "\(durationString)s \(statement.sql)" + } } } diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index b75bbb555..f1fff6199 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -241,17 +241,46 @@ 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?, + publicStatementArguments: Bool = false) { self.extendedResultCode = resultCode self.message = message ?? resultCode.errorString self.sql = sql self.arguments = arguments + self.publicStatementArguments = publicStatementArguments + } + + /// 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. + public init( + resultCode: ResultCode = .SQLITE_ERROR, + message: String? = nil, + sql: String? = nil) + { + self.init(resultCode: resultCode, message: message, sql: sql, arguments: nil, publicStatementArguments: false) } /// Creates a Database Error with a raw CInt result code. @@ -259,10 +288,33 @@ 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 { DatabaseError(message: "no such table: \(tableName)") } @@ -421,8 +473,9 @@ extension DatabaseError { if let sql = sql { description += " - while executing `\(sql)`" } - // TODO: consider including arguments depending on database configuration, - // for easy verbose debugging when the database does not contain sensitive information. + if publicStatementArguments, let arguments = arguments, !arguments.isEmpty { + description += " with arguments \(arguments)" + } return description } diff --git a/Tests/GRDBTests/DatabaseErrorTests.swift b/Tests/GRDBTests/DatabaseErrorTests.swift index 2a9ced44b..50666a5b3 100644 --- a/Tests/GRDBTests/DatabaseErrorTests.swift +++ b/Tests/GRDBTests/DatabaseErrorTests.swift @@ -65,7 +65,7 @@ class DatabaseErrorTests: GRDBTestCase { } } - 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)") @@ -121,6 +121,65 @@ class DatabaseErrorTests: GRDBTestCase { } } + 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)") + 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 (?, ?)` 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\"]") + } + } + + // 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 (?, ?)` 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\"]") + } + } + + // 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 (?, ?)` 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\"]") + } + } + } + func testDatabaseErrorThrownByExecuteMultiStatementContainSQL() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -170,5 +229,4 @@ class DatabaseErrorTests: GRDBTestCase { } } } - } diff --git a/Tests/GRDBTests/DatabaseTraceTests.swift b/Tests/GRDBTests/DatabaseTraceTests.swift index 985192e05..478a7b15e 100644 --- a/Tests/GRDBTests/DatabaseTraceTests.swift +++ b/Tests/GRDBTests/DatabaseTraceTests.swift @@ -145,6 +145,27 @@ class DatabaseTraceTests : GRDBTestCase { } } + 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); + INSERT INTO t (a) VALUES (?) + """, arguments: [1]) + XCTAssertEqual(events.suffix(2), [ + "SQL: CREATE table t(a)", + "SQL: INSERT INTO t (a) VALUES (1)"]) + } + } + func testStopTrace() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in From bb8b39f7fdd510f439780919f74801b53a398f68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Jan 2022 14:37:02 +0100 Subject: [PATCH 10/35] Documentation for public statement arguments --- Documentation/Concurrency.md | 2 +- README.md | 119 ++++++++++++++++++++++++----------- 2 files changed, 82 insertions(+), 39 deletions(-) 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/README.md b/README.md index fb4a5a9ed..49c1b75dd 100644 --- a/README.md +++ b/README.md @@ -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,50 @@ 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. :warning: 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): +```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) +} +``` + +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.19/Structs/Configuration.html) for more details and configuration options. SQLite API @@ -7377,13 +7386,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 } ``` +By default, the `error.description` property does output the statement arguments. See [Database Configuration](#database-configuration) for a more verbose output. + **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: @@ -7829,13 +7840,15 @@ 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) // SQL: SELECT * FROM player WHERE email = ?, Arguments: ["O'Brien"] } ``` -Another option is to setup a tracing function that prints out the executed SQL requests. For example, provide a tracing function when you connect to the database: +> :warning: **Warning**: The description of prepared statements contains statement arguments. It is your responsibility to prevent sensitive information from leaking in unexpected locations: most apps should prefer tracing, described below. + +A tracing function prints out the executed SQL requests. For example, provide a tracing function when you connect to the database: ```swift // Prints all SQL statements @@ -7846,19 +7859,24 @@ 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' + let players = try Player.filter(Column("email") == "arthur@example.com").fetchAll(db) + // Prints "SELECT * FROM player WHERE email = ?" } ``` -If you want to hide values such as `'O''Brien'` from the logged statements, adapt the tracing function as below: +If you want to see statement arguments such as `'arthur@example.com'` in the logged statements, [make statement arguments public](#database-configuration), or adapt the tracing function as below (but mind that it is your responsibility to prevent sensitive information from leaking in unexpected locations): ```swift db.trace { event in - if case let .statement(statement) = event { - // Prints SELECT * FROM player WHERE name = ? - print(statement.sql) - } + #if DEBUG + // Protect sensitive information by enabling verbose output in DEBUG builds only + // Prints "SELECT * FROM player WHERE email = 'arthur@example.com'" + print(event.expandedDescription) + #else + // In release builds, never print statement arguments. + // Prints "SELECT * FROM player WHERE email = ?" + print(event) + #endif } ``` @@ -7892,8 +7910,32 @@ 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), or adapt the tracing function as below (but mind that it is your responsibility to prevent sensitive information from leaking in unexpected locations): + +```swift +db.trace(options: .profile) { event in + #if DEBUG + // Protect sensitive information by enabling verbose output in DEBUG builds only + // Prints "0.003s SELECT * FROM player WHERE email = 'arthur@example.com'" + print(event.expandedDescription) + if case let .profile(statement, duration) = event, duration > 0.5 { + // Prints "Slow query: SELECT * FROM player WHERE email = 'arthur@example.com'" + print("Slow query: \(statement.expandedSQL)") + } + #else + // In release builds, never print statement arguments. + // Prints "0.003s SELECT * FROM player WHERE email = ?" + print(event) + if case let .profile(statement, duration) = event, duration > 0.5 { + // Prints "Slow query: SELECT * FROM player WHERE email = ?" + print("Slow query: \(statement.sql)") + } + #endif } ``` @@ -8398,3 +8440,4 @@ This chapter was renamed to [Embedding SQL in Query Interface Requests]. [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 From 6e3a15ebed3cf6d7c9082d4795d815146fd8eace Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Jan 2022 14:57:18 +0100 Subject: [PATCH 11/35] Statement.description no longer contains statement arguments --- GRDB/Core/Statement.swift | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index fa9e75946..a8a0e109e 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -382,9 +382,7 @@ public typealias SelectStatement = Statement public typealias UpdateStatement = Statement extension Statement: CustomStringConvertible { - public var description: String { - "SQL: \(sql), Arguments: \(arguments)" - } + public var description: String { sql } } // MARK: - Select Statements From fd22fac5c0ec86af7b73e980e546c6077d30a15f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Jan 2022 15:12:41 +0100 Subject: [PATCH 12/35] Don't shed too much light on expandedSQL & expandedDescription properties --- GRDB/Core/Configuration.swift | 23 ++++------------ GRDB/Core/Database.swift | 26 ++++++++++++------- GRDB/Core/DatabaseError.swift | 14 ++++++---- README.md | 49 +++++------------------------------ 4 files changed, 37 insertions(+), 75 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index aab69a7f2..47aa724cd 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -124,11 +124,14 @@ public struct Configuration { /// 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 not recommended to do so in - /// release builds: + /// 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 /// @@ -143,22 +146,6 @@ public struct Configuration { /// } catch { /// print(error) /// } - /// - /// Regardless of this flag, you can explicitly ask to see the - /// statement arguments with the `expandedDescription` property of database - /// errors and trace events: - /// - /// // The expanded descriptions of trace events and errors always - /// // contain the sensitive information: - /// db.trace { event in - /// print(event.expandedDescription) - /// } - /// do { - /// let email = "..." - /// let player = try Player.filter(Column("email") == email).fetchOne(db) - /// } catch let error as DatabaseError { - /// print(error.expandedDescription) - /// } public var publicStatementArguments = false // MARK: - Managing SQLite Connections diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 5e7e41d8b..8aa5deee6 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1664,7 +1664,7 @@ extension Database { /// /// For example: /// - /// UPDATE player SET score = ? WHERE id = ? + /// SELECT * FROM player WHERE email = ? public var sql: String { _sql } #elseif os(Linux) #else @@ -1672,7 +1672,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 @@ -1680,8 +1680,8 @@ 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, _): if let unexpandedSQL = unexpandedSQL { @@ -1698,7 +1698,11 @@ 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): @@ -1725,8 +1729,8 @@ extension Database { /// /// For example: /// - /// SELECT * FROM player WHERE id = ? - /// 0.1s SELECT * FROM player WHERE id = ? + /// 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. @@ -1752,11 +1756,15 @@ extension Database { /// /// For example: /// - /// SELECT * FROM player WHERE id = 1 - /// 0.1s SELECT * FROM player WHERE id = 1 + /// 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): diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index f1fff6199..c0ff3a9c3 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -460,8 +460,8 @@ extension DatabaseError { /// /// For example: /// - /// SQLite error 19: FOREIGN KEY constraint failed - while executing - /// `INSERT INTO pets (masterId, name) VALUES (?, ?)` + /// 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. @@ -483,12 +483,16 @@ extension DatabaseError { /// /// For example: /// - /// SQLite error 19: FOREIGN KEY constraint failed - while executing - /// `INSERT INTO pets (masterId, name) VALUES (?, ?)` - /// with arguments [1, "Bobby"] + /// 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 { diff --git a/README.md b/README.md index 49c1b75dd..feafb538d 100644 --- a/README.md +++ b/README.md @@ -7842,13 +7842,12 @@ You can compile the request into a prepared statement: try dbQueue.read { db in let request = Player.filter(Column("email") == "arthur@example.com") let statement = try request.makePreparedRequest(db).statement - print(statement) // SQL: SELECT * FROM player WHERE email = ?, Arguments: ["O'Brien"] + print(statement) // SELECT * FROM player WHERE email = ? + print(statement.arguments) // ["arthur@example.com"] } ``` -> :warning: **Warning**: The description of prepared statements contains statement arguments. It is your responsibility to prevent sensitive information from leaking in unexpected locations: most apps should prefer tracing, described below. - -A tracing function prints out the executed SQL requests. For example, provide a tracing function when you connect to the database: +Another option is to setup a tracing function that prints out the executed SQL requests. For example, provide a tracing function when you connect to the database: ```swift // Prints all SQL statements @@ -7859,26 +7858,12 @@ config.prepareDatabase { db in let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) try dbQueue.read { db in + // Prints "SELECT * FROM player WHERE email = ?" let players = try Player.filter(Column("email") == "arthur@example.com").fetchAll(db) - // Prints "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), or adapt the tracing function as below (but mind that it is your responsibility to prevent sensitive information from leaking in unexpected locations): - -```swift -db.trace { event in - #if DEBUG - // Protect sensitive information by enabling verbose output in DEBUG builds only - // Prints "SELECT * FROM player WHERE email = 'arthur@example.com'" - print(event.expandedDescription) - #else - // In release builds, never print statement arguments. - // Prints "SELECT * FROM player WHERE email = ?" - print(event) - #endif -} -``` +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. @@ -7915,29 +7900,7 @@ try dbQueue.read { db in } ``` -If you want to see statement arguments such as `'arthur@example.com'` in the logged statements, [make statement arguments public](#database-configuration), or adapt the tracing function as below (but mind that it is your responsibility to prevent sensitive information from leaking in unexpected locations): - -```swift -db.trace(options: .profile) { event in - #if DEBUG - // Protect sensitive information by enabling verbose output in DEBUG builds only - // Prints "0.003s SELECT * FROM player WHERE email = 'arthur@example.com'" - print(event.expandedDescription) - if case let .profile(statement, duration) = event, duration > 0.5 { - // Prints "Slow query: SELECT * FROM player WHERE email = 'arthur@example.com'" - print("Slow query: \(statement.expandedSQL)") - } - #else - // In release builds, never print statement arguments. - // Prints "0.003s SELECT * FROM player WHERE email = ?" - print(event) - if case let .profile(statement, duration) = event, duration > 0.5 { - // Prints "Slow query: SELECT * FROM player WHERE email = ?" - print("Slow query: \(statement.sql)") - } - #endif -} -``` +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? From 99c596f77895c5f6ef73dbfeb52393d99cb9c10a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Jan 2022 15:21:44 +0100 Subject: [PATCH 13/35] Fix DatabaseError public initializer --- GRDB/Core/DatabaseError.swift | 19 ++----------------- 1 file changed, 2 insertions(+), 17 deletions(-) diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index c0ff3a9c3..0be99c18e 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -258,7 +258,7 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError { resultCode: ResultCode = .SQLITE_ERROR, message: String? = nil, sql: String? = nil, - arguments: StatementArguments?, + arguments: StatementArguments? = nil, publicStatementArguments: Bool = false) { self.extendedResultCode = resultCode @@ -267,22 +267,7 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError { self.arguments = arguments self.publicStatementArguments = publicStatementArguments } - - /// 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. - public init( - resultCode: ResultCode = .SQLITE_ERROR, - message: String? = nil, - sql: String? = nil) - { - self.init(resultCode: resultCode, message: message, sql: sql, arguments: nil, publicStatementArguments: false) - } - + /// Creates a Database Error with a raw CInt result code. /// /// This initializer is not public because library user is not supposed to From b5395a097c9a83cb6711cc44fc87eeb02e7b6946 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Jan 2022 15:27:40 +0100 Subject: [PATCH 14/35] Documentation --- GRDB/Core/DatabaseError.swift | 4 ++-- README.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index 0be99c18e..d17c4640b 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -267,7 +267,7 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError { self.arguments = arguments self.publicStatementArguments = publicStatementArguments } - + /// Creates a Database Error with a raw CInt result code. /// /// This initializer is not public because library user is not supposed to @@ -299,7 +299,7 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError { arguments: arguments, publicStatementArguments: publicStatementArguments) } - + static func noSuchTable(_ tableName: String) -> Self { DatabaseError(message: "no such table: \(tableName)") } diff --git a/README.md b/README.md index feafb538d..93a069c88 100644 --- a/README.md +++ b/README.md @@ -7393,7 +7393,7 @@ do { } ``` -By default, the `error.description` property does output the statement arguments. See [Database Configuration](#database-configuration) for a more verbose output. +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**. From 914bd14cd1e31e7c3b4e39f3059b17fc04086771 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Jan 2022 15:27:44 +0100 Subject: [PATCH 15/35] CHANGELOG --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index aed8e359f..40d143e2c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -89,6 +89,8 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Next Release - **Fixed**: Fixed a bug of `including(all:)` for composite foreign keys and limited requests. +- **New**: [#1160](https://github.com/groue/GRDB.swift/pull/1160) by [@groue](https://github.com/groue): Hide statement arguments by default. +- **Documentation Update**: The [Database Configuration](README.md#database-configuration), [] ## 5.19.0 From d69db0b9a1d3f79446bc0ad6f5c99cc473e6a324 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Jan 2022 15:32:21 +0100 Subject: [PATCH 16/35] CHANGELOG --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 40d143e2c..6994f82d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -90,7 +90,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Fixed**: Fixed a bug of `including(all:)` for composite foreign keys and limited requests. - **New**: [#1160](https://github.com/groue/GRDB.swift/pull/1160) by [@groue](https://github.com/groue): Hide statement arguments by default. -- **Documentation Update**: The [Database Configuration](README.md#database-configuration), [] +- **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 From 426044154c377d7a98a8a32ad57941637d6a0b0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Jan 2022 15:54:39 +0100 Subject: [PATCH 17/35] Fix public statement arguments for system SQLite --- GRDB/Core/Database.swift | 46 ++++++++++++++++++++++------------------ README.md | 6 +++++- 2 files changed, 30 insertions(+), 22 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 8aa5deee6..57892cb9f 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -713,8 +713,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), - publicStatementArguments: configuration.publicStatementArguments) + sqlite3_expanded_sql: sqlite3_expanded_sql, + publicStatementArguments: configuration.publicStatementArguments)) trace(TraceEvent.statement(statement)) } case SQLITE_TRACE_PROFILE: @@ -723,8 +723,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib impl: .trace_v2( sqliteStatement: OpaquePointer(sqliteStatement), unexpandedSQL: nil, - sqlite3_expanded_sql: sqlite3_expanded_sql), - publicStatementArguments: configuration.publicStatementArguments) + sqlite3_expanded_sql: sqlite3_expanded_sql, + publicStatementArguments: configuration.publicStatementArguments)) let duration = TimeInterval(durationP.pointee) / 1.0e9 #if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS) @@ -1646,19 +1646,17 @@ 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 } var impl: Impl - /// See Configuration.publicStatementArguments - var publicStatementArguments: Bool - #if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS) /// The executed SQL, where bound parameters are not expanded. /// @@ -1683,7 +1681,7 @@ extension Database { // 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) @@ -1708,7 +1706,7 @@ extension Database { 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 "" } @@ -1717,6 +1715,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`. @@ -1737,18 +1749,10 @@ extension Database { public var description: String { switch self { case let .statement(statement): - if statement.publicStatementArguments { - return statement.expandedSQL - } else { - return statement.sql - } + return statement.description case let .profile(statement: statement, duration: duration): let durationString = String(format: "%.3f", duration) - if statement.publicStatementArguments { - return "\(durationString)s \(statement.expandedSQL)" - } else { - return "\(durationString)s \(statement.sql)" - } + return "\(durationString)s \(statement)" } } diff --git a/README.md b/README.md index 93a069c88..8d951cf1b 100644 --- a/README.md +++ b/README.md @@ -580,7 +580,7 @@ let dbQueue = try DatabaseQueue( // or DatabasePool configuration: config) ``` -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. :warning: 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): +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 @@ -604,6 +604,10 @@ do { } ``` +> :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) output 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.19/Structs/Configuration.html) for more details and configuration options. From 29808e51ff4aa3e7527de6dc156969d0dcd7171e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Jan 2022 16:06:22 +0100 Subject: [PATCH 18/35] Fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8d951cf1b..bbc5d4b4b 100644 --- a/README.md +++ b/README.md @@ -606,7 +606,7 @@ do { > :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) output statement arguments in the [trace events](#how-do-i-print-a-request-as-sql), regardless of the `publicStatementArguments` flag. +> :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.19/Structs/Configuration.html) for more details and configuration options. From ed4471c5b99c0906f4eecefcb8f7b1b30cc84cb8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Jan 2022 17:31:00 +0100 Subject: [PATCH 19/35] Configuration.writeTargetQueue --- GRDB/Core/Configuration.swift | 32 ++++++++--- GRDB/Core/DatabasePool.swift | 8 +-- GRDB/Core/DatabaseWriter.swift | 2 +- GRDB/Core/SerializedDatabase.swift | 6 ++- GRDB/Migration/DatabaseMigrator.swift | 1 + .../DatabasePoolConcurrencyTests.swift | 54 +++++++++++++++++++ Tests/GRDBTests/DatabaseQueueTests.swift | 53 ++++++++++++++++++ 7 files changed, 143 insertions(+), 13 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 47aa724cd..746f969a6 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -248,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 @@ -287,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/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 27cd7ec55..a5aac279a 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -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 diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 7387e8d12..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() { 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/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/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") From 936fd3ed5f92638e9f0c4d96f3dcf06b5e7e3b09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Jan 2022 17:47:30 +0100 Subject: [PATCH 20/35] Test that DatabaseMigrator.eraseDatabaseOnSchemaChange does not deadlock on Configuration.writeTargetQueue --- Tests/GRDBTests/DatabaseMigratorTests.swift | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) 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() From 5dde1409adff08f9d1f39d13a4f221423fd76f51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Jan 2022 17:54:33 +0100 Subject: [PATCH 21/35] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6994f82d9..fa6fc4a0e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -90,6 +90,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Fixed**: Fixed a bug of `including(all:)` for composite foreign keys and limited requests. - **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. From 9dc6fbd7f9cc6c2e10dd2919eeef062fc62f1d9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 30 Jan 2022 12:27:19 +0100 Subject: [PATCH 22/35] Fix #1159 --- GRDB/Core/SchedulingWatchdog.swift | 8 +++++++- GRDB/Core/Statement.swift | 4 +++- 2 files changed, 10 insertions(+), 2 deletions(-) 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/Statement.swift b/GRDB/Core/Statement.swift index a8a0e109e..180da3f6b 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -382,7 +382,9 @@ public typealias SelectStatement = Statement public typealias UpdateStatement = Statement extension Statement: CustomStringConvertible { - public var description: String { sql } + public var description: String { + SchedulingWatchdog.allows(database) ? sql : "Statement" + } } // MARK: - Select Statements From c60b8cfc53a97b7a6944514e12dc773877eab01b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 30 Jan 2022 14:07:43 +0100 Subject: [PATCH 23/35] Refactor prevention of truncate optimization We now always use the same authorizer, which is always ready to prevent truncate optimization depending on the current transaction observers. --- GRDB/Core/Database+Statements.swift | 6 +- GRDB/Core/Database.swift | 32 ++----- GRDB/Core/Statement.swift | 126 ++++++++++++++-------------- GRDB/Core/StatementAuthorizer.swift | 65 ++++++-------- GRDB/Core/TransactionObserver.swift | 36 +++----- 5 files changed, 107 insertions(+), 158 deletions(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 7a4119528..5e9137ded 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -542,11 +542,9 @@ 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) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 57892cb9f..c5d8c4f17 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 @@ -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 { diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 180da3f6b..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") diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index 443f8c1e1..8f3cbbf00 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -2,20 +2,10 @@ 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() @@ -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/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index a66c13805..1ab7aae81 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -198,16 +198,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 +246,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 +265,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 +277,6 @@ class DatabaseObservationBroker { } transactionState = .none - - if observesRowDeletion { - return TruncateOptimizationBlocker() - } else { - return nil - } } /// May throw a cancelled commit error, if a transaction observer cancels From b2df255306f089c5bd47e2631ef9a34dde230a44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 30 Jan 2022 14:12:46 +0100 Subject: [PATCH 24/35] Failing test for cached statement which does not prevent the truncate optimization --- .../GRDBTests/TruncateOptimizationTests.swift | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/Tests/GRDBTests/TruncateOptimizationTests.swift b/Tests/GRDBTests/TruncateOptimizationTests.swift index a3e8b152f..6998eb4c3 100644 --- a/Tests/GRDBTests/TruncateOptimizationTests.swift +++ b/Tests/GRDBTests/TruncateOptimizationTests.swift @@ -111,6 +111,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 From b8c0e9d2c2c6150ee7de0c0fd0c2692508a102cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 30 Jan 2022 14:24:28 +0100 Subject: [PATCH 25/35] Fix failing test for cached statement which does not prevent the truncate optimization --- GRDB/Core/Database+Statements.swift | 4 ++++ GRDB/Core/TransactionObserver.swift | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 5e9137ded..48033e38f 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -638,4 +638,8 @@ struct StatementCache { mutating func remove(_ statement: Statement) { statements.removeFirst { $0.value === statement } } + + mutating func clear(where isDeleted: (Statement) -> Bool) { + statements = statements.filter { (_, statement) in !isDeleted(statement) } + } } diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 1ab7aae81..4481265c4 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, this the addition of an + // observer may change the need for truncate optimization prevention. + publicStatementCache.clear(where: { $0.databaseEventKinds.contains(where: \.isDelete) }) + internalStatementCache.clear(where: { $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, this the removal of an + // observer may change the need for truncate optimization prevention. + publicStatementCache.clear(where: { $0.databaseEventKinds.contains(where: \.isDelete) }) + internalStatementCache.clear(where: { $0.databaseEventKinds.contains(where: \.isDelete) }) + observationBroker.remove(transactionObserver: transactionObserver) } @@ -886,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 { From b82f92f7260bda719829f6a8c211aa6d7e5be7ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 30 Jan 2022 14:33:22 +0100 Subject: [PATCH 26/35] Test for cursor next() followed by forEach() --- Tests/GRDBTests/DatabaseCursorTests.swift | 46 +++++++++++++++++++++++ 1 file changed, 46 insertions(+) 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() From 4e65425c007288ea238194e8ab76d7128b2ac64c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 30 Jan 2022 14:41:29 +0100 Subject: [PATCH 27/35] Cleanup --- GRDB/Core/Database+Statements.swift | 4 ++-- GRDB/Core/TransactionObserver.swift | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 48033e38f..7a263d041 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -639,7 +639,7 @@ struct StatementCache { statements.removeFirst { $0.value === statement } } - mutating func clear(where isDeleted: (Statement) -> Bool) { - statements = statements.filter { (_, statement) in !isDeleted(statement) } + mutating func removeAll(where shouldBeRemoved: (Statement) -> Bool) { + statements = statements.filter { (_, statement) in !shouldBeRemoved(statement) } } } diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 4481265c4..f9a0d6cd8 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -17,8 +17,8 @@ extension Database { // Drop cached statements that delete, this the addition of an // observer may change the need for truncate optimization prevention. - publicStatementCache.clear(where: { $0.databaseEventKinds.contains(where: \.isDelete) }) - internalStatementCache.clear(where: { $0.databaseEventKinds.contains(where: \.isDelete) }) + publicStatementCache.removeAll { $0.databaseEventKinds.contains(where: \.isDelete) } + internalStatementCache.removeAll{ $0.databaseEventKinds.contains(where: \.isDelete) } observationBroker.add(transactionObserver: transactionObserver, extent: extent) } @@ -29,8 +29,8 @@ extension Database { // Drop cached statements that delete, this the removal of an // observer may change the need for truncate optimization prevention. - publicStatementCache.clear(where: { $0.databaseEventKinds.contains(where: \.isDelete) }) - internalStatementCache.clear(where: { $0.databaseEventKinds.contains(where: \.isDelete) }) + publicStatementCache.removeAll { $0.databaseEventKinds.contains(where: \.isDelete) } + internalStatementCache.removeAll { $0.databaseEventKinds.contains(where: \.isDelete) } observationBroker.remove(transactionObserver: transactionObserver) } From 2d6c2873e0d8add085ae8f84d5fbdffb1ae4b6b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 30 Jan 2022 14:42:22 +0100 Subject: [PATCH 28/35] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fa6fc4a0e..e910165fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -89,6 +89,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Next Release - **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. From 3d0b34590fb372316ed76430067992485ac94b49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 30 Jan 2022 14:49:31 +0100 Subject: [PATCH 29/35] Fix typo --- GRDB/Core/TransactionObserver.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index f9a0d6cd8..c9a0a0982 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -15,7 +15,7 @@ extension Database { { SchedulingWatchdog.preconditionValidQueue(self) - // Drop cached statements that delete, this the addition of an + // 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) } @@ -27,7 +27,7 @@ extension Database { public func remove(transactionObserver: TransactionObserver) { SchedulingWatchdog.preconditionValidQueue(self) - // Drop cached statements that delete, this the removal of an + // 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) } From fc7f24ef6eadc8bc31ba63f54a2dea8b38f8b707 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 30 Jan 2022 14:57:37 +0100 Subject: [PATCH 30/35] Test case insensitivity of truncation optimization prevention --- .../GRDBTests/TruncateOptimizationTests.swift | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/Tests/GRDBTests/TruncateOptimizationTests.swift b/Tests/GRDBTests/TruncateOptimizationTests.swift index 6998eb4c3..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() From 09f7d4d952b350c3eda4a471e78326040082cedc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 30 Jan 2022 15:27:11 +0100 Subject: [PATCH 31/35] Complete #1161 --- GRDB/Core/DatabasePool.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index a5aac279a..5213e85d3 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -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 } From 75f72472ff0afba335187806e5a5038b9d19b0a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 31 Jan 2022 08:37:57 +0100 Subject: [PATCH 32/35] Cleanup --- GRDB/Core/Database+Statements.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 7a263d041..8cd791dbc 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -550,11 +550,13 @@ extension Database { try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments) try checkForSuspensionViolation(from: statement) + // 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 From b5338650db3affb188d4425034b0d2601b82f24d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 31 Jan 2022 19:23:55 +0100 Subject: [PATCH 33/35] Bump performance comparison dependencies --- .../GRDBPerformance.xcodeproj/project.pbxproj | 28 +++++++++---------- .../xcshareddata/swiftpm/Package.resolved | 26 ++++++++--------- 2 files changed, 27 insertions(+), 27 deletions(-) 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" } } ] From 72e8dd2816674600111942c129d8d7a465baf95a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 31 Jan 2022 20:20:02 +0100 Subject: [PATCH 34/35] Cleanup --- GRDB/Core/Database+Statements.swift | 4 ++-- GRDB/Core/Database.swift | 22 +++++++++++----------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 8cd791dbc..c91d7fe3d 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -551,8 +551,8 @@ extension Database { try checkForSuspensionViolation(from: statement) // Database observation: record what the statement is looking at. - if _isRecordingSelectedRegion { - _selectedRegion.formUnion(statement.databaseRegion) + if isRecordingSelectedRegion { + selectedRegion.formUnion(statement.databaseRegion) } // Database observation: prepare transaction observers. diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index c5d8c4f17..ba0a63a87 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -161,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 @@ -585,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() From e5a8e130d7871345c0eda43f71d79604eb8ca4e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 1 Feb 2022 07:44:09 +0100 Subject: [PATCH 35/35] v5.20.0 --- CHANGELOG.md | 5 ++++- Documentation/FullTextSearch.md | 4 ++-- Documentation/Migrations.md | 2 +- GRDB.swift.podspec | 2 +- Makefile | 6 ++--- README.md | 40 ++++++++++++++++----------------- Support/Info.plist | 2 +- 7 files changed, 32 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e910165fb..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,7 +87,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- -## Next Release +## 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. 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/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 bbc5d4b4b..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 @@ -608,7 +608,7 @@ do { > > :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.19/Structs/Configuration.html) for more details and configuration options. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.20/Structs/Configuration.html) for more details and configuration options. SQLite API @@ -665,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. @@ -923,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 @@ -1002,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: @@ -1287,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 = ... @@ -1734,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 @@ -1846,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] @@ -1929,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 @@ -2672,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()`. @@ -3112,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 @@ -3134,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). @@ -4659,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) @@ -5565,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 @@ -6869,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 @@ -8209,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). @@ -8350,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 @@ -8403,7 +8403,7 @@ 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 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