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 01/12] 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 02/12] 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 03/12] 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 04/12] 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 05/12] 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 06/12] 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 07/12] 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 08/12] 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 09/12] 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 10/12] 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 11/12] 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 12/12] 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.