Merge pull request #791 from groue/dev/trace

Extend tracing of statement execution
This commit is contained in:
Gwendal Roué authored and GitHub committed 2020-06-01 20:14:35 +02:00
commit 578fa162f1
20 files changed
+545 -275

No files matched your search

+1
View File
@@ -3,6 +3,7 @@ included:
disabled_rules:
- cyclomatic_complexity
- duplicate_enum_cases
- file_length
- force_cast
- force_try
+19 -85
View File
@@ -30,179 +30,113 @@ jobs:
###########################################
## Test GRDB Xcode 11.4
- stage: Test GRDB Xcode 11.4
- name: "Test GRDB Xcode 11.4 - GRDBOSX"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBOSX (Swift 5.2, macOS)
script: make test_framework_GRDBOSX_maxSwift
# - stage: Test GRDB Xcode 11.4
# gemfile: .ci/gemfiles/Gemfile.travis
# osx_image: xcode11.4
# env:
# - TID=GRDBOSX (Swift 5.2, macOS)
# script: make test_framework_GRDBOSX_minSwift
- stage: Test GRDB Xcode 11.4
- name: "Test GRDB Xcode 11.4 - GRDBWatchOS"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBWatchOS (watchOS)
script: make test_framework_GRDBWatchOS
- stage: Test GRDB Xcode 11.4
- name: "Test GRDB Xcode 11.4 - GRDBiOS iOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 5.2, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget_maxSwift
# - stage: Test GRDB Xcode 11.4
# gemfile: .ci/gemfiles/Gemfile.travis
# osx_image: xcode11.4
# env:
# - TID=GRDBiOS (Swift 5.2, iOS <MAX>)
# script: make test_framework_GRDBiOS_maxTarget_minSwift
- stage: Test GRDB Xcode 11.4
- name: "Test GRDB Xcode 11.4 - GRDBiOS iOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 5.2, iOS <MIN>)
script: make test_framework_GRDBiOS_minTarget
- stage: Test GRDB Xcode 11.4
- name: "Test GRDB Xcode 11.4 - GRDBtvOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBtvOS (Swift 5.2, tvOS <MAX>)
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
# - stage: Test GRDB Xcode 11.4
# gemfile: .ci/gemfiles/Gemfile.travis
# osx_image: xcode11.4
# env:
# - TID=GRDBtvOS (Swift 5.2, tvOS <MAX>)
# script: make test_framework_GRDBtvOS_maxTarget_minSwift
- stage: Test GRDB Xcode 11.4
- name: "Test GRDB Xcode 11.4 - GRDBtvOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBtvOS (Swift 5.2, tvOS <MIN>)
script: make test_framework_GRDBtvOS_minTarget
- stage: Test GRDB Xcode 11.4
- name: "Test GRDB Xcode 11.4 - SPM"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDB [SPM] (macOS)
script: make test_SPM
###########################################
## Test GRDBCustom Xcode 11.4
- stage: Test GRDBCustom Xcode 11.4
- name: "Test GRDBCustom Xcode 11.4 - GRDBOSX"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBOSX (Swift 5.2, macOS)
script: make test_framework_GRDBCustomSQLiteOSX
- stage: Test GRDBCustom Xcode 11.4
- name: "Test GRDBCustom Xcode 11.4 - GRDBiOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 5.2, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
# - stage: Test GRDBCustom Xcode 11.4
# gemfile: .ci/gemfiles/Gemfile.travis
# osx_image: xcode11.4
# env:
# - TID=GRDBiOS (Swift 5.2, iOS <MAX>)
# script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_minSwift
- stage: Test GRDBCustom Xcode 11.4
- name: "Test GRDBCustom Xcode 11.4 - GRDBiOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 5.2, iOS <MIN>)
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
###########################################
## Test SQLCipher Xcode 11.4
- stage: Test SQLCipher Xcode 11.4
- name: "Test SQLCipher Xcode 11.4 - SQLCipher 3"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=SQLCipher 3
script: make test_framework_SQLCipher3
- stage: Test SQLCipher Xcode 11.4
- name: "Test SQLCipher Xcode 11.4 - SQLCipher 4"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=SQLCipher 4
script: make test_framework_SQLCipher4
###########################################
## Test Installation Xcode 11.4
# Manual Install
- stage: Test Installation Xcode 11.4
- name: "Test Installation Xcode 11.4 - Manual Install"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=Manual Install
script: make test_install_manual
# CocoaPods Lint
- stage: Test Installation Xcode 11.4
- name: "Test Installation Xcode 11.4 - CocoaPods Lint"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=CocoaPods Lint
script: make test_CocoaPodsLint_GRDB
# CocoaPods Install GRDB
- stage: Test Installation Xcode 11.4
- name: "Test Installation Xcode 11.4 - CocoaPods Framework"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=CocoaPods GRDB (framework)
script: make test_install_GRDB_CocoaPods_framework
# CocoaPods Install GRDB
- stage: Test Installation Xcode 11.4
- name: "Test Installation Xcode 11.4 - CocoaPods Static"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=CocoaPods GRDB (static)
script: make test_install_GRDB_CocoaPods_static
# SPM Install
- stage: Test Installation Xcode 11.4
- name: "Test Installation Xcode 11.4 - SPM Package"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=SPM Package
script: make test_install_SPM_Package
# SPM Install
- stage: Test Installation Xcode 11.4
- name: "Test Installation Xcode 11.4 - SPM Package in Xcode Project"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=SPM Package in Xcode Project
script: make test_install_SPM_Project
# Custom SQLite Install
- stage: Test Installation Xcode 11.4
- name: "Test Installation Xcode 11.4 - Custom SQLite"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=Custom SQLite
script: make test_install_customSQLite
+6
View File
@@ -70,6 +70,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
## Next Release
### Documentation Diff
- Updated FAQ: [How do I print a request as SQL?](README.md#how-do-i-print-a-request-as-sql)
- New FAQ: [How do I monitor the duration of database statements execution?](README.md#how-do-i-monitor-the-duration-of-database-statements-execution)
### Fixed
- [#784](https://github.com/groue/GRDB.swift/pull/784): Fix observation of eager-loaded to-many associations
@@ -77,6 +82,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
### Breaking Changes
- [#790](https://github.com/groue/GRDB.swift/pull/790): Bump required iOS version to 10.0
- [#791](https://github.com/groue/GRDB.swift/pull/791): Extend tracing of statement execution
## 5.0.0-beta.2
+25 -9
View File
@@ -293,7 +293,23 @@ The changes can quite impact your application. We'll describe them below, as wel
## Other Changes
1. [Batch updates] used to rely of the `<-` operator. This operator has been removed. Use the `set(to:)` method instead:
1. The `Configuration.trace` property has been removed. You know use the `Database.trace(options:_:)` method instead:
```swift
// BEFORE: GRDB 4
var config = Configuration()
config.trace = { print($0) }
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
// NEW: GRDB 5
var config = Configuration()
config.prepareDatabase = { db in
db.trace { print($0) }
}
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
```
2. [Batch updates] used to rely of the `<-` operator. This operator has been removed. Use the `set(to:)` method instead:
```swift
// BEFORE: GRDB 4
@@ -305,7 +321,7 @@ The changes can quite impact your application. We'll describe them below, as wel
> :question: This change avoids conflicts with other libraries that define the same operator.
2. [SQL Interpolation] does no longer wrap subqueries in parenthesis:
3. [SQL Interpolation] does no longer wrap subqueries in parenthesis:
```swift
// BEFORE: GRDB 4
@@ -320,7 +336,7 @@ The changes can quite impact your application. We'll describe them below, as wel
> :question: This change makes it possible to concatenate subqueries with the UNION operator.
3. In order to extract raw SQL string from an [SQLLiteral], you now need a database connection:
4. In order to extract raw SQL string from an [SQLLiteral], you now need a database connection:
```swift
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
@@ -335,7 +351,7 @@ The changes can quite impact your application. We'll describe them below, as wel
print(arguments) // prints ["O'Brien", 42]
```
4. In order to extract raw SQL string from a request ([SQLRequest] or [QueryInterfaceRequest]), you now need to call the `makePreparedRequest()` method:
5. In order to extract raw SQL string from a request ([SQLRequest] or [QueryInterfaceRequest]), you now need to call the `makePreparedRequest()` method:
```swift
// BEFORE: GRDB 4
@@ -355,7 +371,7 @@ The changes can quite impact your application. We'll describe them below, as wel
}
```
5. The `TableRecord.selectionSQL()` method is no longer avaible. When you need to embed the columns selected by a record type in an SQL request, you now have to use [SQL Interpolation]:
6. The `TableRecord.selectionSQL()` method is no longer avaible. When you need to embed the columns selected by a record type in an SQL request, you now have to use [SQL Interpolation]:
```swift
// BEFORE: GRDB 4
@@ -367,7 +383,7 @@ The changes can quite impact your application. We'll describe them below, as wel
let players = try request.fetchAll(db)
```
6. [Custom SQL functions] are now [callable values](https://github.com/apple/swift-evolution/blob/master/proposals/0253-callable.md):
7. [Custom SQL functions] are now [callable values](https://github.com/apple/swift-evolution/blob/master/proposals/0253-callable.md):
```swift
// BEFORE: GRDB 4
@@ -377,13 +393,13 @@ The changes can quite impact your application. We'll describe them below, as wel
Player.select(myFunction(Column("name")))
```
7. Defining custom `FetchRequest` types is now **discouraged**.
8. Defining custom `FetchRequest` types is now **discouraged**.
A future GRDB version will remove the ability to define custom `FetchRequest` types.
Our suggestion is to refactor your app so that your custom request type is no longer needed: [SQLRequest] and [QueryInterfaceRequest] are now supposed to fully address your needs. If it is not possible, then please [open an issue](https://github.com/groue/GRDB.swift/issues) and describe your particular use case.
8. The module name for [custom SQLite builds](CustomSQLiteBuilds.md) is now the plain `GRDB`:
9. The module name for [custom SQLite builds](CustomSQLiteBuilds.md) is now the plain `GRDB`:
```swift
// BEFORE: GRDB 4
@@ -393,7 +409,7 @@ The changes can quite impact your application. We'll describe them below, as wel
import GRDB
```
9. Importing the `GRDB` module grants access to the [SQLite C interface](https://www.sqlite.org/c3ref/intro.html). You don't need any longer to import the underlying SQLite library:
10. Importing the `GRDB` module grants access to the [SQLite C interface](https://www.sqlite.org/c3ref/intro.html). You don't need any longer to import the underlying SQLite library:
```swift
// BEFORE: GRDB 4
+8
View File
@@ -814,6 +814,9 @@
56FC987B1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; };
56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; };
56FDECE31BB32DFD009AD709 /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; };
56FEB8F8248403000081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */; };
56FEB8F9248403010081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */; };
56FEB8FA248403020081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */; };
56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; };
56FEE7FF1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; };
56FF45441D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; };
@@ -1506,6 +1509,7 @@
56FBFED82210731A00945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = "<group>"; };
56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = "<group>"; };
56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = "<group>"; };
56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseTraceTests.swift; sourceTree = "<group>"; };
56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = "<group>"; };
56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordDeleteTests.swift; sourceTree = "<group>"; };
56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = "<group>"; };
@@ -2053,6 +2057,7 @@
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */,
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */,
56A238131B9C74A90082EB20 /* DatabaseTests.swift */,
56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */,
564FCE5D20F7E11A00202B90 /* DatabaseValueConversionErrorTests.swift */,
56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */,
56A238191B9C74A90082EB20 /* DatabaseValueConvertible */,
@@ -3115,6 +3120,7 @@
56176C701EACCCC9000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */,
56FEE7FF1F47253700D930EA /* TableRecordTests.swift in Sources */,
56057C562291B16A00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */,
56FEB8F9248403010081AF83 /* DatabaseTraceTests.swift in Sources */,
56A2386A1B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */,
56A2383E1B9C74A90082EB20 /* DatabaseValueTests.swift in Sources */,
567156181CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */,
@@ -3322,6 +3328,7 @@
5674A72A1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */,
566A84402041914000E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */,
56057C552291B16A00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */,
56FEB8F8248403000081AF83 /* DatabaseTraceTests.swift in Sources */,
56176C5E1EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */,
56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */,
56D496641D81304E008276D7 /* FoundationUUIDTests.swift in Sources */,
@@ -3659,6 +3666,7 @@
AAA4DD76230F262000C74B15 /* FTS5WrapperTokenizerTests.swift in Sources */,
AAA4DD77230F262000C74B15 /* TableRecordTests.swift in Sources */,
AAA4DD78230F262000C74B15 /* AssociationHasManyRowScopeTests.swift in Sources */,
56FEB8FA248403020081AF83 /* DatabaseTraceTests.swift in Sources */,
AAA4DD79230F262000C74B15 /* RecordSubClassTests.swift in Sources */,
AAA4DD7A230F262000C74B15 /* DatabaseValueTests.swift in Sources */,
AAA4DD7B230F262000C74B15 /* DatabaseQueueReadOnlyTests.swift in Sources */,
-8
View File
@@ -63,11 +63,6 @@ public struct Configuration {
/// The default label is nil.
public var label: String? = nil
/// A function that is called on every statement executed by the database.
///
/// Default: nil
public var trace: TraceFunction?
/// If false, SQLite from version 3.29.0 will not interpret a double-quoted
/// string as a string literal if it does not match any valid identifier.
///
@@ -219,6 +214,3 @@ public struct Configuration {
}
}
}
/// A tracing function that takes an SQL string.
public typealias TraceFunction = (String) -> Void
+229 -68
View File
@@ -153,7 +153,7 @@ public final class Database {
// MARK: - Private properties
private var busyCallback: BusyCallback?
private var trace: ((TraceEvent) -> Void)?
private var functions = Set<DatabaseFunction>()
private var collations = Set<DatabaseCollation>()
private var _readOnlyDepth = 0 // Modify with beginReadOnly/endReadOnly
@@ -200,8 +200,6 @@ public final class Database {
/// This method must be called after database initialization
func setup() throws {
// Setup trace first, so that setup queries are traced.
setupTrace()
setupDoubleQuotedStringLiterals()
try setupForeignKeys()
setupBusyMode()
@@ -222,71 +220,6 @@ public final class Database {
configuration.SQLiteConnectionDidOpen?()
}
private func setupTrace() {
guard configuration.trace != nil else {
return
}
// sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0
// http://www.sqlite.org/changes.html#version_3_14
// It is available from macOS 10.12, tvOS 10.0, watchOS 3.0
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace_v2(
sqliteConnection,
UInt32(SQLITE_TRACE_STMT),
{ (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in
Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql)
},
dbPointer)
#elseif os(Linux)
setupTrace_v1()
#else
if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace_v2(
sqliteConnection,
UInt32(SQLITE_TRACE_STMT),
{ (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in
Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql)
},
dbPointer)
} else {
setupTrace_v1()
}
#endif
}
#if !(GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS))
// Precondition: configuration.trace != nil
private func setupTrace_v1() {
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
guard let sql = sql.map(String.init) else { return }
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.configuration.trace!(sql)
}, dbPointer)
}
#endif
// Precondition: configuration.trace != nil
private static func trace_v2(
_ mask: UInt32,
_ dbPointer: UnsafeMutableRawPointer?,
_ stmt: UnsafeMutableRawPointer?,
_ unexpandedSQL: UnsafeMutableRawPointer?,
_ sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
-> Int32
{
guard let stmt = stmt else { return SQLITE_OK }
guard let expandedSQLCString = sqlite3_expanded_sql(OpaquePointer(stmt)) else { return SQLITE_OK }
let sql = String(cString: expandedSQLCString)
sqlite3_free(expandedSQLCString)
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.configuration.trace!(sql)
return SQLITE_OK
}
private func setupDoubleQuotedStringLiterals() {
if configuration.acceptsDoubleQuotedStringLiterals {
enableDoubleQuotedStringLiterals(sqliteConnection)
@@ -555,6 +488,128 @@ public final class Database {
return try block()
}
// MARK: - Trace
/// Registers a tracing function.
///
/// For example:
///
/// // Trace all SQL statements executed by the database
/// var configuration = Configuration()
/// configuration.prepareDatabase = { db in
/// db.trace(options: .statement) { event in
/// print("SQL: \(event)")
/// }
/// }
/// let dbQueue = try DatabaseQueue(path: "...", configuration: configuration)
///
/// Pass an empty options set in order to stop database tracing:
///
/// // Stop tracing
/// db.trace(options: [])
///
/// See https://www.sqlite.org/c3ref/trace_v2.html for more information.
///
/// - parameter options: The set of desired event kinds. Defaults to
/// `.statement`, which notifies all executed database statements.
/// - parameter trace: the tracing function.
public func trace(options: TracingOptions = .statement, _ trace: ((TraceEvent) -> Void)? = nil) {
SchedulingWatchdog.preconditionValidQueue(self)
self.trace = trace
if options.isEmpty || trace == nil {
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
sqlite3_trace_v2(sqliteConnection, 0, nil, nil)
#elseif os(Linux)
sqlite3_trace(sqliteConnection, nil)
#else
if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
sqlite3_trace_v2(sqliteConnection, 0, nil, nil)
} else {
sqlite3_trace(sqliteConnection, nil, nil)
}
#endif
return
}
// sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0
// http://www.sqlite.org/changes.html#version_3_14
// It is available from macOS 10.12, tvOS 10.0, watchOS 3.0
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace_v2(sqliteConnection, UInt32(bitPattern: options.rawValue), { (mask, dbPointer, p, x) in
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.trace_v2(CInt(bitPattern: mask), p, x, sqlite3_expanded_sql)
return SQLITE_OK
}, dbPointer)
#elseif os(Linux)
setupTrace_v1()
#else
if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace_v2(sqliteConnection, UInt32(bitPattern: options.rawValue), { (mask, dbPointer, p, x) in
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.trace_v2(CInt(bitPattern: mask), p, x, sqlite3_expanded_sql)
return SQLITE_OK
}, dbPointer)
} else {
setupTrace_v1()
}
#endif
}
#if !(GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS))
private func setupTrace_v1() {
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
guard let sql = sql.map(String.init(cString:)) else { return }
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.trace?(Database.TraceEvent.statement(TraceEvent.Statement(impl: .trace_v1(sql))))
}, dbPointer)
}
#endif
// Precondition: configuration.trace != nil
private func trace_v2(
_ mask: CInt,
_ p: UnsafeMutableRawPointer?,
_ x: UnsafeMutableRawPointer?,
_ sqlite3_expanded_sql: @escaping @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
{
guard let trace = trace else { return }
switch mask {
case SQLITE_TRACE_STMT:
if let sqliteStatement = p, let unexpandedSQL = x {
let statement = TraceEvent.Statement(impl: .trace_v2(
sqliteStatement: OpaquePointer(sqliteStatement),
unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)),
sqlite3_expanded_sql: sqlite3_expanded_sql))
trace(TraceEvent.statement(statement))
}
case SQLITE_TRACE_PROFILE:
if let sqliteStatement = p, let durationP = x?.assumingMemoryBound(to: Int64.self) {
let statement = TraceEvent.Statement(impl: .trace_v2(
sqliteStatement: OpaquePointer(sqliteStatement),
unexpandedSQL: nil,
sqlite3_expanded_sql: sqlite3_expanded_sql))
let duration = TimeInterval(durationP.pointee) / 1.0e9
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
trace(TraceEvent.profile(statement: statement, duration: duration))
#elseif os(Linux)
#else
if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
trace(TraceEvent.profile(statement: statement, duration: duration))
}
#endif
}
default:
break
}
}
// MARK: - Checkpoints
func checkpoint(_ kind: Database.CheckpointMode) throws {
@@ -1308,6 +1363,112 @@ extension Database {
/// log function that takes an error message.
public typealias LogErrorFunction = (_ resultCode: ResultCode, _ message: String) -> Void
/// An option for `Database.trace(options:_:)`
public struct TracingOptions: OptionSet {
public let rawValue: CInt
public init(rawValue: CInt) {
self.rawValue = rawValue
}
/// Reports executed statements
public static let statement = TracingOptions(rawValue: SQLITE_TRACE_STMT)
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
/// Reports executed statements and the estimated duration that the
/// statement took to run.
public static let profile = TracingOptions(rawValue: SQLITE_TRACE_PROFILE)
#elseif os(Linux)
#else
/// Reports executed statements and the estimated duration that the
/// statement took to run.
@available(OSX 10.12, tvOS 10.0, watchOS 3.0, *)
public static let profile = TracingOptions(rawValue: SQLITE_TRACE_PROFILE)
#endif
}
/// An event reported by `Database.trace(options:_:)`
public enum TraceEvent: CustomStringConvertible {
/// Information about a statement reported by `Database.trace(options:_:)`
public struct Statement {
enum Impl {
case trace_v1(String)
case trace_v2(
sqliteStatement: SQLiteStatement,
unexpandedSQL: UnsafePointer<CChar>?,
sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
}
let impl: Impl
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
/// The executed SQL.
public var sql: String { _sql }
#elseif os(Linux)
#else
/// The executed SQL.
@available(OSX 10.12, tvOS 10.0, watchOS 3.0, *)
public var sql: String { _sql }
#endif
var _sql: String {
switch impl {
case .trace_v1:
// Likely a GRDB bug
fatalError("Not get statement SQL")
case let .trace_v2(sqliteStatement, unexpandedSQL, _):
if let unexpandedSQL = unexpandedSQL {
return String(cString: unexpandedSQL)
.trimmingCharacters(in: .sqlStatementSeparators)
} else {
return String(cString: sqlite3_sql(sqliteStatement))
.trimmingCharacters(in: .sqlStatementSeparators)
}
}
}
/// The executed SQL, with bound parameters expanded.
public var expandedSQL: String {
switch impl {
case let .trace_v1(expandedSQL):
return expandedSQL
case let .trace_v2(sqliteStatement, _, sqlite3_expanded_sql):
guard let cString = sqlite3_expanded_sql(sqliteStatement) else {
return ""
}
defer { sqlite3_free(cString) }
return String(cString: cString)
.trimmingCharacters(in: .sqlStatementSeparators)
}
}
}
/// An event reported by `TracingOptions.statement`.
case statement(Statement)
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
/// An event reported by `TracingOptions.profile`.
case profile(statement: Statement, duration: TimeInterval)
#elseif os(Linux)
#else
/// An event reported by `TracingOptions.profile`.
@available(OSX 10.12, tvOS 10.0, watchOS 3.0, *)
case profile(statement: Statement, duration: TimeInterval)
#endif
public var description: String {
switch self {
case let .statement(statement):
return statement.expandedSQL
case let .profile(statement: statement, duration: duration):
let durationString = String(format: "%.3f", duration)
return "\(durationString)s \(statement.expandedSQL)"
}
}
}
/// The end of a transaction: Commit, or Rollback
public enum TransactionCompletion {
case commit
+11
View File
@@ -47,6 +47,14 @@ extension AssociationAggregate {
{ preconditionFailure() }
}
extension Configuration {
@available(*, unavailable, message: "Use Database.trace(options:_:) in Configuration.prepareDatabase instead.")
public var trace: TraceFunction? {
get { preconditionFailure() }
set { preconditionFailure() }
}
}
extension DatabaseFunction {
@available(*, unavailable, renamed: "callAsFunction(_:)")
public func apply(_ arguments: SQLExpressible...) -> SQLExpression
@@ -251,6 +259,9 @@ extension TableRecord where Self: FetchableRecord {
{ preconditionFailure() }
}
@available(*, unavailable)
public typealias TraceFunction = (String) -> Void
extension ValueObservation {
@available(*, unavailable, message: "ValueObservation now schedules its values asynchronously on the main queue by default. See ValueObservation.start() for possible configuration")
var scheduling: ValueScheduling {
+6
View File
@@ -470,6 +470,8 @@
56F409292465C8F500A7A152 /* SQLRequestProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F409262465C8F500A7A152 /* SQLRequestProtocol.swift */; };
56FBFED62210731100945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED52210731000945324 /* SQLRequest.swift */; };
56FBFED72210731100945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED52210731000945324 /* SQLRequest.swift */; };
56FEB8FE248403270081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */; };
56FEB8FF248403270081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */; };
56FEE7FE1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; };
56FEE8021F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; };
56FF45431D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; };
@@ -1039,6 +1041,7 @@
56F409262465C8F500A7A152 /* SQLRequestProtocol.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestProtocol.swift; sourceTree = "<group>"; };
56FBFED52210731000945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = "<group>"; };
56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = "<group>"; };
56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTraceTests.swift; sourceTree = "<group>"; };
56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = "<group>"; };
56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordDeleteTests.swift; sourceTree = "<group>"; };
56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = "<group>"; };
@@ -1559,6 +1562,7 @@
566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */,
564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */,
56A238131B9C74A90082EB20 /* DatabaseTests.swift */,
56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */,
5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */,
56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */,
56A238191B9C74A90082EB20 /* DatabaseValueConvertible */,
@@ -2393,6 +2397,7 @@
567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */,
5674A7291F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */,
56057C5A2291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */,
56FEB8FF248403270081AF83 /* DatabaseTraceTests.swift in Sources */,
56FEE8021F47253700D930EA /* TableRecordTests.swift in Sources */,
F3BA81211CFB3063003DC1BA /* RecordPrimaryKeyNoneTests.swift in Sources */,
F3BA80F71CFB3021003DC1BA /* SelectStatementTests.swift in Sources */,
@@ -2730,6 +2735,7 @@
F3BA80FA1CFB3021003DC1BA /* SelectStatementTests.swift in Sources */,
5674A7271F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */,
56057C592291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */,
56FEB8FE248403270081AF83 /* DatabaseTraceTests.swift in Sources */,
56FEE7FE1F47253700D930EA /* TableRecordTests.swift in Sources */,
F3BA81191CFB305F003DC1BA /* QueryInterfaceRequestTests.swift in Sources */,
F3BA812F1CFB3064003DC1BA /* RecordPrimaryKeyNoneTests.swift in Sources */,
+43 -4
View File
@@ -470,7 +470,6 @@ let newPlaceCount = try dbQueue.write { db -> Int in
var config = Configuration()
config.readonly = true
config.foreignKeysEnabled = true // Default is already true
config.trace = { print($0) } // Prints all SQL statements
config.label = "MyDatabase" // Useful when your app opens multiple databases
let dbQueue = try DatabaseQueue(
@@ -550,7 +549,6 @@ let newPlaceCount = try dbPool.write { db -> Int in
var config = Configuration()
config.readonly = true
config.foreignKeysEnabled = true // Default is already true
config.trace = { print($0) } // Prints all SQL statements
config.label = "MyDatabase" // Useful when your app opens multiple databases
config.maximumReaderCount = 10 // The default is 5
@@ -7279,6 +7277,7 @@ FAQ
- [How do I open a database stored as a resource of my application?](#how-do-i-open-a-database-stored-as-a-resource-of-my-application)
- [How do I close a database connection?](#how-do-i-close-a-database-connection)
- [How do I print a request as SQL?](#how-do-i-print-a-request-as-sql)
- [How do I monitor the duration of database statements execution?](#how-do-i-monitor-the-duration-of-database-statements-execution)
- [Generic parameter 'T' could not be inferred](#generic-parameter-t-could-not-be-inferred)
- [SQLite error 10 "disk I/O error", SQLite error 23 "not authorized"](#sqlite-error-10-disk-io-error-sqlite-error-23-not-authorized)
- [SQLite error 21 "wrong number of statement arguments" with LIKE queries](#sqlite-error-21-wrong-number-of-statement-arguments-with-like-queries)
@@ -7348,11 +7347,14 @@ try dbQueue.read { db in
}
```
Another option is to setup a tracing function that prints out all SQL requests executed by your application. You provide the trace 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
var config = Configuration()
config.trace = { print($0) } // Prints all SQL statements
config.prepareDatabase = { db in
db.trace { print($0) }
}
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
try dbQueue.read { db in
@@ -7361,9 +7363,46 @@ try dbQueue.read { db in
}
```
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)
}
}
```
> :point_up: **Note**: the generated SQL may change between GRDB releases, without notice: don't have your application rely on any specific SQL output.
### How do I monitor the duration of database statements execution?
Use the `trace(options:_:)` method, with the `.profile` option:
```swift
var config = Configuration()
config.prepareDatabase = { db in
db.trace(options: .profile) { event in
// Prints all SQL statements with their duration
print(event)
// Access to detailed profiling information
if case let .profile(statement, duration) = event, duration > 0.5 {
print("Slow query: \(statement.sql)")
}
}
}
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'"
}
```
### Generic parameter 'T' could not be inferred
You may get this error when using the `read` and `write` methods of database queues and pools:
@@ -25,8 +25,6 @@
561CFAB12376EFBE000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAAD2376EFBE000C8BAA /* AssociationHasManyOrderingTests.swift */; };
563DE4FB231A9212005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4FA231A9212005081B7 /* DatabaseConfigurationTests.swift */; };
563DE4FC231A9212005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4FA231A9212005081B7 /* DatabaseConfigurationTests.swift */; };
563F4CBA242F801A0052E96C /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563F4CB9242F801A0052E96C /* ValueObservationRecordTests.swift */; };
563F4CBB242F801A0052E96C /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563F4CB9242F801A0052E96C /* ValueObservationRecordTests.swift */; };
564A1FDE226B89E1001F64F1 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F27226B89CE001F64F1 /* MutablePersistableRecordDeleteTests.swift */; };
564A1FDF226B89E1001F64F1 /* AssociationHasOneThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F28226B89CE001F64F1 /* AssociationHasOneThroughRowScopeTests.swift */; };
564A1FE0226B89E1001F64F1 /* RowCopiedFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F29226B89CF001F64F1 /* RowCopiedFromStatementTests.swift */; };
@@ -935,7 +933,7 @@
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 1020;
LastUpgradeCheck = 1100;
LastUpgradeCheck = 1150;
TargetAttributes = {
564A1F1C226B876D001F64F1 = {
CreatedOnToolsVersion = 10.2.1;
@@ -1130,7 +1128,6 @@
564A202E226B89E1001F64F1 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
564A2078226B89E1001F64F1 /* ForeignKeyInfoTests.swift in Sources */,
564A2050226B89E1001F64F1 /* RecordPrimaryKeySingleTests.swift in Sources */,
563F4CBA242F801A0052E96C /* ValueObservationRecordTests.swift in Sources */,
561017D22462968600317275 /* DatabasePoolTests.swift in Sources */,
564A2091226B89E1001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */,
5676FBB022F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */,
@@ -1334,7 +1331,6 @@
564A20CD226B8E18001F64F1 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
564A20CE226B8E18001F64F1 /* ForeignKeyInfoTests.swift in Sources */,
564A20CF226B8E18001F64F1 /* RecordPrimaryKeySingleTests.swift in Sources */,
563F4CBB242F801A0052E96C /* ValueObservationRecordTests.swift in Sources */,
561017D32462968600317275 /* DatabasePoolTests.swift in Sources */,
564A20D0226B8E18001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */,
5676FBB122F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */,
+155
View File
@@ -0,0 +1,155 @@
import XCTest
import GRDB
class DatabaseTraceTests : GRDBTestCase {
func testTraceStatementExpandedSQL() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var lastExpandedSQL: String?
db.trace(options: .statement) { event in
switch event {
case let .statement(statement):
lastExpandedSQL = statement.expandedSQL
default:
XCTFail("Unexpected event")
}
}
try db.execute(sql: "CREATE table t(a);")
XCTAssertEqual(lastExpandedSQL, "CREATE table t(a)")
try db.execute(sql: "INSERT INTO t (a) VALUES (?)", arguments: [1])
XCTAssertEqual(lastExpandedSQL, "INSERT INTO t (a) VALUES (1)")
}
}
func testTraceStatementSQL() throws {
guard #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) else {
return
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var lastSQL: String?
var lastDescription: String?
db.trace(options: .statement) { event in
lastDescription = event.description
switch event {
case let .statement(statement):
lastSQL = statement.sql
default:
XCTFail("Unexpected event")
}
}
try db.execute(sql: "CREATE table t(a);")
XCTAssertEqual(lastSQL, "CREATE table t(a)")
XCTAssertEqual(lastDescription, "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)")
}
}
func testTraceProfile() throws {
guard #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) else {
return
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var lastSQL: String?
var lastExpandedSQL: String?
var lastDuration: TimeInterval?
var lastDescription: String?
db.trace(options: .profile) { event in
lastDescription = event.description
switch event {
case let .profile(statement: statement, duration: duration):
lastSQL = statement.sql
lastExpandedSQL = statement.expandedSQL
lastDuration = duration
default:
XCTFail("Unexpected event")
}
}
try db.execute(sql: "CREATE table t(a);")
XCTAssertEqual(lastSQL, "CREATE table t(a)")
XCTAssertEqual(lastExpandedSQL, "CREATE table t(a)")
XCTAssertTrue(lastDuration! > 0)
XCTAssert(lastDescription!.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)"))
db.add(function: DatabaseFunction("wait", argumentCount: 1, pure: true, function: { dbValues in
if let delay = TimeInterval.fromDatabaseValue(dbValues[0]) {
Thread.sleep(forTimeInterval: delay)
}
return nil
}))
try db.execute(sql: "SELECT wait(?)", arguments: [0.5])
XCTAssertEqual(lastSQL, "SELECT wait(?)")
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)"))
}
}
func testTraceMultiple() throws {
guard #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) else {
return
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var events: [String] = []
db.trace(options: [.statement, .profile]) { event in
events.append(event.description)
}
try db.execute(sql: "CREATE table t(a);")
XCTAssertEqual(events.count, 2)
}
}
func testTraceFromConfigurationWithDefaultOptions() throws {
var events: [String] = []
var configuration = Configuration()
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
var events: [String] = []
db.trace(options: .statement) { event in
events.append(event.description)
}
try db.execute(sql: "CREATE table t(a);")
XCTAssertEqual(events.last, "CREATE table t(a)")
db.trace(options: [])
try db.execute(sql: "INSERT INTO t (a) VALUES (?)", arguments: [1])
XCTAssertEqual(events.last, "CREATE table t(a)")
}
}
}
+11 -17
View File
@@ -34,18 +34,6 @@ extension Book : MutablePersistableRecord {
}
class FTS3RecordTests: GRDBTestCase {
override func setUp() {
super.setUp()
dbConfiguration.trace = { [unowned self] sql in
// Ignore virtual table logs
if !sql.hasPrefix("--") {
self.sqlQueries.append(sql)
}
}
}
override func setup(_ dbWriter: DatabaseWriter) throws {
try dbWriter.write { db in
try db.create(virtualTable: "books", using: FTS3()) { t in
@@ -113,12 +101,18 @@ class FTS3RecordTests: GRDBTestCase {
try book.insert(db)
}
let pattern = try FTS3Pattern(rawPattern: "Herman Melville")
XCTAssertEqual(try Book.matching(pattern).fetchCount(db), 1)
XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"books\" WHERE \"books\" MATCH 'Herman Melville'")
do {
sqlQueries = []
let pattern = try FTS3Pattern(rawPattern: "Herman Melville")
XCTAssertEqual(try Book.matching(pattern).fetchCount(db), 1)
XCTAssertTrue(sqlQueries.contains("SELECT COUNT(*) FROM \"books\" WHERE \"books\" MATCH 'Herman Melville'"))
}
XCTAssertEqual(try Book.fetchCount(db), 1)
XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"books\"")
do {
sqlQueries = []
XCTAssertEqual(try Book.fetchCount(db), 1)
XCTAssertTrue(sqlQueries.contains("SELECT COUNT(*) FROM \"books\""))
}
}
}
}
@@ -2,18 +2,6 @@ import XCTest
import GRDB
class FTS3TableBuilderTests: GRDBTestCase {
override func setUp() {
super.setUp()
dbConfiguration.trace = { [unowned self] sql in
// Ignore virtual table logs
if !sql.hasPrefix("--") {
self.sqlQueries.append(sql)
}
}
}
func testWithoutBody() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
+11 -17
View File
@@ -34,18 +34,6 @@ extension Book : MutablePersistableRecord {
}
class FTS4RecordTests: GRDBTestCase {
override func setUp() {
super.setUp()
dbConfiguration.trace = { [unowned self] sql in
// Ignore virtual table logs
if !sql.hasPrefix("--") {
self.sqlQueries.append(sql)
}
}
}
override func setup(_ dbWriter: DatabaseWriter) throws {
try dbWriter.write { db in
try db.create(virtualTable: "books", using: FTS4()) { t in
@@ -113,12 +101,18 @@ class FTS4RecordTests: GRDBTestCase {
try book.insert(db)
}
let pattern = try FTS3Pattern(rawPattern: "Herman Melville")
XCTAssertEqual(try Book.matching(pattern).fetchCount(db), 1)
XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"books\" WHERE \"books\" MATCH 'Herman Melville'")
do {
sqlQueries = []
let pattern = try FTS3Pattern(rawPattern: "Herman Melville")
XCTAssertEqual(try Book.matching(pattern).fetchCount(db), 1)
XCTAssertTrue(sqlQueries.contains("SELECT COUNT(*) FROM \"books\" WHERE \"books\" MATCH 'Herman Melville'"))
}
XCTAssertEqual(try Book.fetchCount(db), 1)
XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"books\"")
do {
sqlQueries = []
XCTAssertEqual(try Book.fetchCount(db), 1)
XCTAssertTrue(sqlQueries.contains("SELECT COUNT(*) FROM \"books\""))
}
}
}
}
@@ -2,18 +2,6 @@ import XCTest
import GRDB
class FTS4TableBuilderTests: GRDBTestCase {
override func setUp() {
super.setUp()
dbConfiguration.trace = { [unowned self] sql in
// Ignore virtual table logs
if !sql.hasPrefix("--") {
self.sqlQueries.append(sql)
}
}
}
func testWithoutBody() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
+11 -17
View File
@@ -35,18 +35,6 @@ extension Book : MutablePersistableRecord {
}
class FTS5RecordTests: GRDBTestCase {
override func setUp() {
super.setUp()
dbConfiguration.trace = { [unowned self] sql in
// Ignore virtual table logs
if !sql.hasPrefix("--") {
self.sqlQueries.append(sql)
}
}
}
override func setup(_ dbWriter: DatabaseWriter) throws {
try dbWriter.write { db in
try db.create(virtualTable: "books", using: FTS5()) { t in
@@ -109,12 +97,18 @@ class FTS5RecordTests: GRDBTestCase {
try book.insert(db)
}
let pattern = FTS5Pattern(matchingAllTokensIn: "Herman Melville")!
XCTAssertEqual(try Book.matching(pattern).fetchCount(db), 1)
XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"books\" WHERE \"books\" MATCH 'herman melville'")
do {
sqlQueries = []
let pattern = FTS5Pattern(matchingAllTokensIn: "Herman Melville")!
XCTAssertEqual(try Book.matching(pattern).fetchCount(db), 1)
XCTAssertTrue(sqlQueries.contains("SELECT COUNT(*) FROM \"books\" WHERE \"books\" MATCH 'herman melville'"))
}
XCTAssertEqual(try Book.fetchCount(db), 1)
XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"books\"")
do {
sqlQueries = []
XCTAssertEqual(try Book.fetchCount(db), 1)
XCTAssertTrue(sqlQueries.contains("SELECT COUNT(*) FROM \"books\""))
}
}
}
}
@@ -3,18 +3,6 @@ import XCTest
import GRDB
class FTS5TableBuilderTests: GRDBTestCase {
override func setUp() {
super.setUp()
dbConfiguration.trace = { [unowned self] sql in
// Ignore virtual table logs
if !sql.hasPrefix("--") {
self.sqlQueries.append(sql)
}
}
}
func testWithoutBody() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
+6 -7
View File
@@ -99,16 +99,15 @@ class GRDBTestCase: XCTestCase {
}
}
dbConfiguration.trace = { [unowned self] sql in
self.sqlQueries.append(sql)
}
#if GRDBCIPHER_USE_ENCRYPTION
// Encrypt all databases by default.
dbConfiguration.prepareDatabase = { db in
db.trace { event in
self.sqlQueries.append(event.description)
}
#if GRDBCIPHER_USE_ENCRYPTION
try db.usePassphrase("secret")
#endif
}
#endif
sqlQueries = []
}
@@ -382,7 +382,7 @@ extension GRDBTestCase {
// debug SQLite builds can be *very* slow
let timeout: TimeInterval = 2
#else
let timeout: TimeInterval = 0.3
let timeout: TimeInterval = 1
#endif
func test(
@@ -599,7 +599,7 @@ extension GRDBTestCase {
// debug SQLite builds can be *very* slow
let timeout: TimeInterval = 2
#else
let timeout: TimeInterval = 0.3
let timeout: TimeInterval = 1
#endif
func test(