Merge pull request #1160 from groue/dev/privacy

Hide statement arguments by default
This commit is contained in:
Gwendal Roué authored and GitHub committed 2022-01-29 16:29:58 +01:00
commit dd025a14e4
11 files changed
+353 -75

No files matched your search

+2
View File
@@ -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) chapter explains how to opt in for public statement arguments in DEBUG builds.
## 5.19.0
+1 -1
View File
@@ -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:
+46
View File
@@ -102,6 +102,52 @@ public struct Configuration {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public var observesSuspensionNotifications = false
/// If false (the default), statement arguments are not visible in the
/// description of database errors and trace events, preventing sensitive
/// information from leaking in unexpected places.
///
/// For example:
///
/// // Error: sensitive information is not printed when an error occurs:
/// do {
/// let email = "..." // sensitive information
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
/// } catch {
/// print(error)
/// }
///
/// // Trace: sensitive information is not printed when a statement is traced:
/// db.trace { event in
/// print(event)
/// }
/// let email = "..." // sensitive information
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
///
/// For debugging purpose, you can set this flag to true, and get more
/// precise database reports. It is your responsibility to prevent sensitive
/// information from leaking in unexpected locations, so you should not set
/// this flag in release builds (think about GDPR and other
/// privacy-related rules):
///
/// var config = Configuration()
/// #if DEBUG
/// // Protect sensitive information by enabling verbose debugging in DEBUG builds only
/// config.publicStatementArguments = true
/// #endif
///
/// // The descriptions of trace events and errors now contain the
/// // sensitive information:
/// db.trace { event in
/// print(event)
/// }
/// do {
/// let email = "..."
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
/// } catch {
/// print(error)
/// }
public var publicStatementArguments = false
// MARK: - Managing SQLite Connections
private var setups: [(Database) throws -> Void] = []
+2 -1
View File
@@ -589,7 +589,8 @@ extension Database {
resultCode: resultCode,
message: lastErrorMessage,
sql: statement.sql,
arguments: statement.arguments)
arguments: statement.arguments,
publicStatementArguments: configuration.publicStatementArguments)
}
}
+69 -14
View File
@@ -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)
}
}
@@ -1642,22 +1646,23 @@ extension Database {
public enum TraceEvent: CustomStringConvertible {
/// Information about a statement reported by `Database.trace(options:_:)`
public struct Statement {
public struct Statement: CustomStringConvertible {
enum Impl {
case trace_v1(String)
case trace_v2(
sqliteStatement: SQLiteStatement,
unexpandedSQL: UnsafePointer<CChar>?,
sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?,
publicStatementArguments: Bool) // See Configuration.publicStatementArguments
}
let impl: Impl
var impl: Impl
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
/// The executed SQL, where bound parameters are not expanded.
///
/// For example:
///
/// UPDATE player SET score = ? WHERE id = ?
/// SELECT * FROM player WHERE email = ?
public var sql: String { _sql }
#elseif os(Linux)
#else
@@ -1665,7 +1670,7 @@ extension Database {
///
/// For example:
///
/// UPDATE player SET score = ? WHERE id = ?
/// SELECT * FROM player WHERE email = ?
@available(OSX 10.12, tvOS 10.0, watchOS 3.0, *)
public var sql: String { _sql }
#endif
@@ -1673,10 +1678,10 @@ extension Database {
var _sql: String {
switch impl {
case .trace_v1:
// Likely a GRDB bug
fatalError("Not get statement SQL")
// Likely a GRDB bug: this api is not supposed to be available
fatalError("Unavailable statement SQL")
case let .trace_v2(sqliteStatement, unexpandedSQL, _):
case let .trace_v2(sqliteStatement, unexpandedSQL, _, _):
if let unexpandedSQL = unexpandedSQL {
return String(cString: unexpandedSQL)
.trimmingCharacters(in: .sqlStatementSeparators)
@@ -1691,13 +1696,17 @@ extension Database {
///
/// For example:
///
/// UPDATE player SET score = 1000 WHERE id = 1
/// SELECT * FROM player WHERE email = 'arthur@example.com'
///
/// - warning: It is your responsibility to prevent sensitive
/// information from leaking in unexpected locations, so use this
/// property with care.
public var expandedSQL: String {
switch impl {
case let .trace_v1(expandedSQL):
return expandedSQL
case let .trace_v2(sqliteStatement, _, sqlite3_expanded_sql):
case let .trace_v2(sqliteStatement, _, sqlite3_expanded_sql, _):
guard let cString = sqlite3_expanded_sql(sqliteStatement) else {
return ""
}
@@ -1706,6 +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`.
@@ -1714,7 +1737,39 @@ extension Database {
/// An event reported by `TracingOptions.profile`.
case profile(statement: Statement, duration: TimeInterval)
/// The trace event description.
///
/// For example:
///
/// SELECT * FROM player WHERE email = ?
/// 0.1s SELECT * FROM player WHERE email = ?
///
/// The format of the event description may change between GRDB releases,
/// without notice: don't have your application rely on any specific format.
public var description: String {
switch self {
case let .statement(statement):
return statement.description
case let .profile(statement: statement, duration: duration):
let durationString = String(format: "%.3f", duration)
return "\(durationString)s \(statement)"
}
}
/// The trace event description, where bound parameters are expanded.
///
/// For example:
///
/// SELECT * FROM player WHERE email = 'arthur@example.com'
/// 0.1s SELECT * FROM player WHERE email = 'arthur@example.com'
///
/// The format of the event description may change between GRDB releases,
/// without notice: don't have your application rely on any specific format.
///
/// - warning: It is your responsibility to prevent sensitive
/// information from leaking in unexpected locations, so use this
/// property with care.
public var expandedDescription: String {
switch self {
case let .statement(statement):
return statement.expandedSQL
+78 -5
View File
@@ -241,17 +241,31 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
/// The query arguments that yielded the error (if relevant).
public let arguments: StatementArguments?
/// Creates a Database Error
/// See Configuration.publicStatementArguments
var publicStatementArguments: Bool
/// Creates a DatabaseError.
///
/// - parameters:
/// - resultCode: A ResultCode (defaults to .SQLITE_ERROR).
/// - message: An eventual error message. If nil, the error message is
/// derived from the result code.
/// - sql: An eventual SQL string.
/// - arguments: Eventual Statement arguments.
/// - publicStatementArguments: If false (the default), statement
/// arguments are not visible in the error's `description` property.
public init(
resultCode: ResultCode = .SQLITE_ERROR,
message: String? = nil,
sql: String? = nil,
arguments: StatementArguments? = nil)
arguments: StatementArguments? = nil,
publicStatementArguments: Bool = false)
{
self.extendedResultCode = resultCode
self.message = message ?? resultCode.errorString
self.sql = sql
self.arguments = arguments
self.publicStatementArguments = publicStatementArguments
}
/// Creates a Database Error with a raw CInt result code.
@@ -259,8 +273,31 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
/// This initializer is not public because library user is not supposed to
/// be exposed to raw result codes.
@usableFromInline
init(resultCode: CInt, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
self.init(resultCode: ResultCode(rawValue: resultCode), message: message, sql: sql, arguments: arguments)
init(resultCode: CInt, message: String? = nil, sql: String? = nil) {
self.init(
resultCode: ResultCode(rawValue: resultCode),
message: message,
sql: sql)
}
/// Creates a Database Error with a raw CInt result code.
///
/// This initializer is not public because library user is not supposed to
/// be exposed to raw result codes.
@usableFromInline
init(
resultCode: CInt,
message: String? = nil,
sql: String? = nil,
arguments: StatementArguments?,
publicStatementArguments: Bool)
{
self.init(
resultCode: ResultCode(rawValue: resultCode),
message: message,
sql: sql,
arguments: arguments,
publicStatementArguments: publicStatementArguments)
}
static func noSuchTable(_ tableName: String) -> Self {
@@ -404,8 +441,44 @@ extension DatabaseError {
// CustomStringConvertible
extension DatabaseError {
/// :nodoc:
/// The error description.
///
/// For example:
///
/// SQLite error 19: NOT NULL constraint failed: player.score
/// - while executing `UPDATE player SET score = ? WHERE email = ?
///
/// The format of the error description may change between GRDB releases,
/// without notice: don't have your application rely on any specific format.
public var description: String {
var description = "SQLite error \(resultCode.rawValue)"
if let message = message {
description += ": \(message)"
}
if let sql = sql {
description += " - while executing `\(sql)`"
}
if publicStatementArguments, let arguments = arguments, !arguments.isEmpty {
description += " with arguments \(arguments)"
}
return description
}
/// The error description, where bound parameters, if present, are visible.
///
/// For example:
///
/// SQLite error 19: NOT NULL constraint failed: player.score
/// - while executing `UPDATE player SET score = ? WHERE email = ?
/// with arguments [nil, "arthur@example.com"]
///
/// The format of the error description may change between GRDB releases,
/// without notice: don't have your application rely on any specific format.
///
/// - warning: It is your responsibility to prevent sensitive
/// information from leaking in unexpected locations, so use this
/// property with care.
public var expandedDescription: String {
var description = "SQLite error \(resultCode.rawValue)"
if let message = message {
description += ": \(message)"
+1 -3
View File
@@ -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
+52 -42
View File
@@ -496,23 +496,9 @@ let newPlaceCount = try dbQueue.write { db -> Int in
**A database queue needs your application to follow rules in order to deliver its safety guarantees.** Please refer to the [Concurrency] guide.
> :bulb: **Tip**: see the [Demo Applications] for sample code that sets up a database queue on iOS.
See [Database Configuration] for DatabaseQueue options.
### DatabaseQueue Configuration
```swift
var config = Configuration()
config.readonly = true
config.foreignKeysEnabled = true // Default is already true
config.label = "MyDatabase" // Useful when your app opens multiple databases
let dbQueue = try DatabaseQueue(
path: "/path/to/database.sqlite",
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.19/Structs/Configuration.html) for more details.
> :bulb: **Tip**: see the [Demo Applications] for sample code.
## Database Pools
@@ -561,7 +547,7 @@ let newPlaceCount = try dbPool.write { db -> Int in
- When you don't need to modify the database, prefer the `read` method, because several threads can perform reads in parallel.
Reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be [configured](#databasepool-configuration).
Reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be [configured](#database-configuration).
- Reads are guaranteed an immutable view of the last committed state of the database, regardless of concurrent writes. This kind of isolation is called [snapshot isolation](https://sqlite.org/isolation.html).
@@ -575,27 +561,54 @@ let newPlaceCount = try dbPool.write { db -> Int in
**A database pool needs your application to follow rules in order to deliver its safety guarantees.** See the [Concurrency] guide for more details about database pools, how they differ from database queues, and advanced use cases.
> :bulb: **Tip**: see the [Demo Applications] for sample code that sets up a database queue on iOS, and just replace DatabaseQueue with DatabasePool.
See [Database Configuration] for DatabasePool options.
> :bulb: **Tip**: see the [Demo Applications] for sample code.
### DatabasePool Configuration
## Database Configuration
```swift
var config = Configuration()
config.readonly = true
config.foreignKeysEnabled = true // Default is already true
config.label = "MyDatabase" // Useful when your app opens multiple databases
config.maximumReaderCount = 10 // The default is 5
config.maximumReaderCount = 10 // (DatabasePool only) The default is 5
let dbPool = try DatabasePool(
let dbQueue = try DatabaseQueue( // or DatabasePool
path: "/path/to/database.sqlite",
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.19/Structs/Configuration.html) for more details.
In debug builds, you can increase the verbosity of [error descriptions](#databaseerror) and [trace events](#how-do-i-print-a-request-as-sql) if you opt in for public statement arguments:
```swift
#if DEBUG
// Protect sensitive information by enabling verbose debugging in DEBUG builds only
config.publicStatementArguments = true
#endif
Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information.
let dbQueue = try DatabaseQueue(path: ..., configuration: config)
do {
try dbQueue.write { db in
user.name = ...
user.location = ...
user.address = ...
user.phoneNumber = ...
try user.save(db)
}
} catch {
// Prints sensitive information in debug builds only
print(error)
}
```
> :warning: **Warning**: It is your responsibility to prevent sensitive information from leaking in unexpected locations, so you should not set the `publicStatementArguments` flag in release builds (think about GDPR and other privacy-related rules).
>
> :warning: **Warning**: The SQLite version that ships with old operating systems (prior to OSX 10.12, tvOS 10.0, and watchOS 3.0) outputs statement arguments in the [trace events](#how-do-i-print-a-request-as-sql), regardless of the `publicStatementArguments` flag.
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.19/Structs/Configuration.html) for more details and configuration options.
SQLite API
@@ -7377,13 +7390,15 @@ do {
// [1, "Bobby"]
error.arguments
// Full error description:
// "SQLite error 19 with statement `INSERT INTO pet (masterId, name)
// VALUES (?, ?)` arguments [1, "Bobby"]: FOREIGN KEY constraint failed""
// Full error description
// > SQLite error 19: FOREIGN KEY constraint failed -
// > while executing `INSERT INTO pet (masterId, name) VALUES (?, ?)`
error.description
}
```
If you want to see statement arguments in the error description, [make statement arguments public](#database-configuration).
**SQLite uses [results codes](https://www.sqlite.org/rescode.html) to distinguish between various errors**.
You can catch a DatabaseError and match on result codes:
@@ -7829,9 +7844,10 @@ You can compile the request into a prepared statement:
```swift
try dbQueue.read { db in
let request = Player.filter(Column("name") == "O'Brien")
let request = Player.filter(Column("email") == "arthur@example.com")
let statement = try request.makePreparedRequest(db).statement
print(statement) // SQL: SELECT * FROM player WHERE name = ?, Arguments: ["O'Brien"]
print(statement) // SELECT * FROM player WHERE email = ?
print(statement.arguments) // ["arthur@example.com"]
}
```
@@ -7846,21 +7862,12 @@ config.prepareDatabase { db in
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
try dbQueue.read { db in
let players = try Player.filter(Column("name") == "O'Brien").fetchAll(db)
// Prints SELECT * FROM player WHERE name = 'O''Brien'
// Prints "SELECT * FROM player WHERE email = ?"
let players = try Player.filter(Column("email") == "arthur@example.com").fetchAll(db)
}
```
If you want to hide values such as `'O''Brien'` from the logged statements, adapt the tracing function as below:
```swift
db.trace { event in
if case let .statement(statement) = event {
// Prints SELECT * FROM player WHERE name = ?
print(statement.sql)
}
}
```
If you want to see statement arguments such as `'arthur@example.com'` in the logged statements, [make statement arguments public](#database-configuration).
> :point_up: **Note**: the generated SQL may change between GRDB releases, without notice: don't have your application rely on any specific SQL output.
@@ -7892,11 +7899,13 @@ config.prepareDatabase { db in
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
try dbQueue.read { db in
let players = try Player.filter(Column("name") == "O'Brien").fetchAll(db)
// Prints "0.003s SELECT * FROM player WHERE name = 'O''Brien'"
let players = try Player.filter(Column("email") == "arthur@example.com").fetchAll(db)
// Prints "0.003s SELECT * FROM player WHERE email = ?"
}
```
If you want to see statement arguments such as `'arthur@example.com'` in the logged statements, [make statement arguments public](#database-configuration).
### What Are Experimental Features?
Since GRDB 1.0, all backwards compatibility guarantees of [semantic versioning](http://semver.org) apply: no breaking change will happen until the next major version of the library.
@@ -8398,3 +8407,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
+68 -5
View File
@@ -27,8 +27,8 @@ class DatabaseErrorTests: GRDBTestCase {
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)`")
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
XCTAssertEqual(sqlQueries.count, 2)
XCTAssertEqual(sqlQueries[0], "INSERT INTO pets (masterId, name) VALUES (1, 'Bobby')")
XCTAssertEqual(sqlQueries[1], "ROLLBACK TRANSACTION")
@@ -60,11 +60,71 @@ class DatabaseErrorTests: GRDBTestCase {
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)`")
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
}
}
func testDatabaseErrorThrownByUpdateStatementContainSQLAndArguments() throws {
func testDatabaseErrorThrownByUpdateStatementContainSQLAndNoPrivateArguments() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT)")
}
// db.execute(sql, arguments)
try dbQueue.inDatabase { db in
do {
try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [1, "Bobby"])
XCTFail()
} catch let error as DatabaseError {
XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)`")
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
}
}
// statement.execute(arguments)
try dbQueue.inDatabase { db in
do {
let statement = try db.makeStatement(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)")
try statement.execute(arguments: [1, "Bobby"])
XCTFail()
} catch let error as DatabaseError {
XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)`")
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
}
}
// statement.execute()
try dbQueue.inDatabase { db in
do {
let statement = try db.makeStatement(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)")
statement.arguments = [1, "Bobby"]
try statement.execute()
XCTFail()
} catch let error as DatabaseError {
XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)`")
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
}
}
}
func testDatabaseErrorThrownByUpdateStatementContainSQLAndPublicArguments() throws {
// Opt in for public statement arguments
dbConfiguration.publicStatementArguments = true
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY)")
@@ -82,6 +142,7 @@ class DatabaseErrorTests: GRDBTestCase {
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
}
}
@@ -97,6 +158,7 @@ class DatabaseErrorTests: GRDBTestCase {
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
}
}
@@ -113,6 +175,7 @@ class DatabaseErrorTests: GRDBTestCase {
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
}
}
}
@@ -133,6 +196,7 @@ class DatabaseErrorTests: GRDBTestCase {
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (1, 'Bobby')")
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (1, 'bobby')`")
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (1, 'bobby')`")
}
}
}
@@ -165,5 +229,4 @@ class DatabaseErrorTests: GRDBTestCase {
}
}
}
}
+33 -3
View File
@@ -31,8 +31,10 @@ class DatabaseTraceTests : GRDBTestCase {
try dbQueue.inDatabase { db in
var lastSQL: String?
var lastDescription: String?
var lastExpandedDescription: String?
db.trace(options: .statement) { event in
lastDescription = event.description
lastExpandedDescription = event.expandedDescription
switch event {
case let .statement(statement):
lastSQL = statement.sql
@@ -43,10 +45,12 @@ class DatabaseTraceTests : GRDBTestCase {
try db.execute(sql: "CREATE table t(a);")
XCTAssertEqual(lastSQL, "CREATE table t(a)")
XCTAssertEqual(lastDescription, "CREATE table t(a)")
XCTAssertEqual(lastExpandedDescription, "CREATE table t(a)")
try db.execute(sql: "INSERT INTO t (a) VALUES (?)", arguments: [1])
XCTAssertEqual(lastSQL, "INSERT INTO t (a) VALUES (?)")
XCTAssertEqual(lastDescription, "INSERT INTO t (a) VALUES (1)")
XCTAssertEqual(lastDescription, "INSERT INTO t (a) VALUES (?)")
XCTAssertEqual(lastExpandedDescription, "INSERT INTO t (a) VALUES (1)")
}
}
@@ -61,8 +65,10 @@ class DatabaseTraceTests : GRDBTestCase {
var lastExpandedSQL: String?
var lastDuration: TimeInterval?
var lastDescription: String?
var lastExpandedDescription: String?
db.trace(options: .profile) { event in
lastDescription = event.description
lastExpandedDescription = event.expandedDescription
switch event {
case let .profile(statement: statement, duration: duration):
lastSQL = statement.sql
@@ -77,12 +83,14 @@ class DatabaseTraceTests : GRDBTestCase {
XCTAssertEqual(lastExpandedSQL, "CREATE table t(a)")
XCTAssertTrue(lastDuration! >= 0)
XCTAssert(lastDescription!.hasSuffix("s CREATE table t(a)"))
XCTAssert(lastExpandedDescription!.hasSuffix("s CREATE table t(a)"))
try db.execute(sql: "INSERT INTO t (a) VALUES (?)", arguments: [1])
XCTAssertEqual(lastSQL, "INSERT INTO t (a) VALUES (?)")
XCTAssertEqual(lastExpandedSQL, "INSERT INTO t (a) VALUES (1)")
XCTAssertTrue(lastDuration! >= 0)
XCTAssert(lastDescription!.hasSuffix("s INSERT INTO t (a) VALUES (1)"))
XCTAssert(lastDescription!.hasSuffix("s INSERT INTO t (a) VALUES (?)"))
XCTAssert(lastExpandedDescription!.hasSuffix("s INSERT INTO t (a) VALUES (1)"))
db.add(function: DatabaseFunction("wait", argumentCount: 1, pure: true, function: { dbValues in
if let delay = TimeInterval.fromDatabaseValue(dbValues[0]) {
@@ -96,7 +104,8 @@ class DatabaseTraceTests : GRDBTestCase {
XCTAssertEqual(lastExpandedSQL, "SELECT wait(0.5)")
XCTAssertGreaterThan(lastDuration!, 0.4)
XCTAssertLessThan(lastDuration!, 2) // Travis can be so slow
XCTAssert(lastDescription!.hasSuffix("s SELECT wait(0.5)"))
XCTAssert(lastDescription!.hasSuffix("s SELECT wait(?)"))
XCTAssert(lastExpandedDescription!.hasSuffix("s SELECT wait(0.5)"))
}
}
@@ -125,6 +134,27 @@ class DatabaseTraceTests : GRDBTestCase {
}
}
let dbQueue = try makeDatabaseQueue(configuration: configuration)
try dbQueue.inDatabase { db in
try db.execute(sql: """
CREATE table t(a);
INSERT INTO t (a) VALUES (?)
""", arguments: [1])
XCTAssertEqual(events.suffix(2), [
"SQL: CREATE table t(a)",
"SQL: INSERT INTO t (a) VALUES (?)"])
}
}
func testTraceFromConfigurationWithPublicStatementArguments() throws {
var events: [String] = []
var configuration = Configuration()
configuration.publicStatementArguments = true
configuration.prepareDatabase { db in
db.trace { event in
events.append("SQL: \(event)")
}
}
let dbQueue = try makeDatabaseQueue(configuration: configuration)
try dbQueue.inDatabase { db in
try db.execute(sql: """
CREATE table t(a);
+1 -1
View File
@@ -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