Compare commits

...
10 Commits
16 changed files with 737 additions and 791 deletions

No files matched your search

+18
View File
@@ -1,6 +1,24 @@
Release Notes
=============
## 2.3.1
Released November 8, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.3.0...v2.3.1)
**Fixed**
- GRDB 2.2.0 has introduced a fix in the way [transaction observers](https://github.com/groue/GRDB.swift/blob/master/README.md#transactionobserver-protocol) are notified of empty deferred transactions (`BEGIN; COMMIT;`). That fix was incomplete, and inconsistent.
Now all transactions are notified, without any exception, including:
```swift
try db.execute("BEGIN; COMMIT;")
try db.execute("SAVEPOINT foo; RELEASE SAVEPOINT foo;")
```
[Rationale](https://github.com/groue/GRDB.swift/commit/820bc87cfeee701743da852f3634e2c695e911ee#diff-3e791e9db648cd302590c9b86c70757fR376)
## 2.3.0
Released November 5, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.2.0...v2.3.0)
+1 -1
View File
@@ -15,7 +15,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
```sh
cd [GRDB directory]
git checkout v2.3.0
git checkout v2.3.1
git submodule update --init SQLiteCustom/src
````
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '2.3.0'
s.version = '2.3.1'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A Swift application toolkit for SQLite databases.'
+2 -2
View File
@@ -228,12 +228,12 @@ extension Database {
observationBroker.updateStatementWillExecute(statement)
}
func updateStatementDidExecute(_ statement: UpdateStatement) {
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
if statement.invalidatesDatabaseSchemaCache {
clearSchemaCache()
}
observationBroker.updateStatementDidExecute(statement)
try observationBroker.updateStatementDidExecute(statement)
}
func updateStatementDidFail(_ statement: UpdateStatement) throws {
+1 -1
View File
@@ -510,7 +510,7 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
case SQLITE_DONE:
database.authorizer = nil
database.updateStatementDidExecute(self)
try database.updateStatementDidExecute(self)
return
case let code:
+68 -59
View File
@@ -250,45 +250,24 @@ class DatabaseObservationBroker {
}
}
func updateStatementDidExecute(_ statement: UpdateStatement) {
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
// Wait for next statement
activeTransactionObservations = []
// Has statement any effect on transaction/savepoints?
if let transactionEffect = statement.transactionEffect {
// Statement has modified transaction/savepoint state
switch transactionEffect {
case .beginTransaction:
break
case .commitTransaction:
if case .none = self.transactionState {
// A COMMIT statement has ended an empty deferred
// transaction. For SQLite, no transaction has ever begun:
case .commitTransaction: // 1. A COMMIT statement has been executed
if case .none = self.transactionState { // 2. sqlite3_commit_hook was not triggered
// 1+2 mean that an empty deferred transaction has been completed:
//
// BEGIN DEFERRED TRANSACTION
// COMMIT
// BEGIN DEFERRED TRANSACTION; COMMIT
//
// We don't need to tell transaction observers about it.
//
// But we have to take care of the .nextTransaction
// observation extent. In the sample code below, the
// observer must not be notified of the second transaction,
// because this is the intent of the programmer:
//
// // Register an observer for next transaction only
// let observer = Observer()
// dbQueue.add(transactionObserver:observer, extent: .nextTransaction)
//
// try dbQueue.inTransaction(.deferred) { db in
// return .commit
// }
//
// // Must not notify observer
// try dbQueue.inTransaction(.deferred) { db in
// try db.execute("...")
// return .commit
// }
emptyDeferredTransactionDidCommit()
// This special case has a dedicated handling:
return try emptyDeferredTransactionDidCommit()
}
case .rollbackTransaction:
@@ -297,17 +276,22 @@ class DatabaseObservationBroker {
case .beginSavepoint(let name):
savepointStack.savepointDidBegin(name)
case .releaseSavepoint(let name):
case .releaseSavepoint(let name): // 1. A RELEASE SAVEPOINT statement has been executed
savepointStack.savepointDidRelease(name)
if case .none = self.transactionState, // 2. sqlite3_commit_hook was not triggered
!database.isInsideTransaction // 3. database is no longer inside a transaction
{
// 1+2+3 mean that an empty deferred transaction has been completed:
//
// SAVEPOINT foo; RELEASE SAVEPOINT foo
//
// This special case has a dedicated handling:
return try emptyDeferredTransactionDidCommit()
}
if savepointStack.isEmpty {
// Notify buffered events
let eventsBuffer = savepointStack.eventsBuffer
savepointStack.clear()
for (event, observations) in eventsBuffer {
for observation in observations {
event.send(to: observation)
}
}
notifyBufferedEvents()
}
case .rollbackSavepoint(let name):
@@ -358,10 +342,15 @@ class DatabaseObservationBroker {
}
}
// Called from sqlite3_commit_hook
// Called from sqlite3_commit_hook and emptyDeferredTransactionDidCommit()
private func databaseWillCommit() throws {
// Time to send all buffered events
notifyBufferedEvents()
for observation in transactionObservations {
try observation.databaseWillCommit()
}
}
private func notifyBufferedEvents() {
let eventsBuffer = savepointStack.eventsBuffer
savepointStack.clear()
@@ -370,10 +359,6 @@ class DatabaseObservationBroker {
event.send(to: observation)
}
}
for observation in transactionObservations {
try observation.databaseWillCommit()
}
}
// Called from updateStatementDidExecute
@@ -387,11 +372,45 @@ class DatabaseObservationBroker {
}
// Called from updateStatementDidExecute
private func emptyDeferredTransactionDidCommit() {
for observation in transactionObservations {
observation.emptyDeferredTransactionDidCommit(database)
private func emptyDeferredTransactionDidCommit() throws {
// A statement that ends a transaction has been executed. But for
// SQLite, no transaction at all has started, and sqlite3_commit_hook
// was not triggered:
//
// try db.execute("BEGIN DEFERRED TRANSACTION")
// try db.execute("COMMIT") // <- no sqlite3_commit_hook callback invocation
//
// Should we tell transaction observers of this transaction, or not?
// The code says that a transaction was open, but SQLite says the
// opposite. How do we lift this ambiguity? Should we notify of
// *transactions expressed in the code*, or *SQLite transactions* only?
//
// If we would notify of SQLite transactions only, then we'd notify of
// all transactions expressed in the code, but empty deferred
// transaction. This means that we'd make an exception. And exceptions
// are the recipe for both surprise and confusion.
//
// For example, is the code below expected to print "did commit"?
//
// db.afterNextTransactionCommit { _ in print("did commit") }
// try db.inTransaction {
// performSomeTask(db)
// return .commit
// }
//
// Yes it is. And the only way to make it reliably print "did commit" is
// to behave consistently, regardless of the implementation of the
// `performSomeTask` function. Even if the `performSomeTask` is empty,
// even if we actually execute an empty deferred transaction.
//
// For better or for worse, let's simulate a transaction:
do {
try databaseWillCommit()
databaseDidCommit()
} catch {
databaseDidRollback(notifyTransactionObservers: true)
throw error
}
cleanupTransactionObservations()
}
// Called from updateStatementDidExecute or updateStatementDidFails
@@ -591,16 +610,6 @@ final class TransactionObservation {
}
}
func emptyDeferredTransactionDidCommit(_ db: Database) {
switch extent {
case .observerLifetime, .databaseLifetime:
break
case .nextTransaction:
// Observer most not get any further notification.
strongObserver = nil
}
}
func databaseDidRollback(_ db: Database) {
switch extent {
case .observerLifetime, .databaseLifetime:
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDBCipher'
s.version = '2.3.0'
s.version = '2.3.1'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A Swift application toolkit for SQLite databases.'
+28 -52
View File
@@ -3,7 +3,7 @@ GRDB 2 [![Swift](https://img.shields.io/badge/swift-4-orange.svg?style=flat)](ht
### A toolkit for SQLite databases, with a focus on application development
**Latest release**: November 5, 2017 • version 2.3.0 • [CHANGELOG](CHANGELOG.md)
**Latest release**: November 8, 2017 • version 2.3.1 • [CHANGELOG](CHANGELOG.md)
**Requirements**: iOS 8.0+ / OSX 10.9+ / watchOS 2.0+ &bull; Swift 4.0 / Xcode 9+
@@ -14,7 +14,7 @@ GRDB 2 [![Swift](https://img.shields.io/badge/swift-4-orange.svg?style=flat)](ht
| Swift 3 | [v1.0](https://github.com/groue/GRDB.swift/tree/v1.0) |
| Swift 3.1 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) |
| Swift 3.2 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) |
| **Swift 4** | **v2.3.0** |
| **Swift 4** | **v2.3.1** |
Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips.
@@ -265,7 +265,7 @@ The [Swift Package Manager](https://swift.org/package-manager/) automates the di
```swift
let package = Package(
dependencies: [
.package(url: "https://github.com/groue/GRDB.swift.git", from: "2.3.0")
.package(url: "https://github.com/groue/GRDB.swift.git", from: "2.3.1")
]
)
```
@@ -282,7 +282,7 @@ If you decide to use Carthage despite this warning, and get any Carthage-related
## Manually
1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v2.3.0) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v2.3.0` command.
1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v2.3.1) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v2.3.1` command.
2. Embed the `GRDB.xcodeproj` project in your own project.
@@ -2439,15 +2439,18 @@ try player.insert(db)
GRDB provides default implementations for [`RowConvertible.init(row:)`](#rowconvertible-protocol) and [`Persistable.encode(to:)`](#persistable-protocol) for record types that also adopt an archival protocol (`Codable`, `Encodable` or `Decodable`). When all their properties are themselves codable, Swift generates the archiving methods, and you don't need to write them down:
```swift
// This is just enough...
struct Player: RowConvertible, Persistable, Codable {
static let databaseTableName = "players"
// Declare a plain Codable struct or class...
struct Player: Codable {
let name: String
let score: Int
}
// ... so that you can save and fetch players:
// Adopt Record protocols...
extension Player: RowConvertible, Persistable {
static let databaseTableName = "players"
}
// ...and you can save and fetch players:
try dbQueue.inDatabase { db in
try Player(name: "Arthur", score: 100).insert(db)
let players = try Player.fetchAll(db)
@@ -2462,22 +2465,20 @@ struct Place: RowConvertible, Persistable, Codable {
static let databaseTableName = "places"
var title: String
var coordinate: CLLocationCoordinate2D // <- Not a simple value
var coordinate: CLLocationCoordinate2D // <- Not a simple value!
}
```
Make it flat, as below, and you'll be granted with all Codable and GRDB advantages:
```swift
struct Place: RowConvertible, Persistable, Codable {
static let databaseTableName = "places"
// Stored properties are all plain values:
struct Place: Codable {
// Stored properties are plain values:
var title: String
var latitude: CLLocationDegrees
var longitude: CLLocationDegrees
// Complex properties are computed properties:
// Complex property is computed:
var coordinate: CLLocationCoordinate2D {
get {
return CLLocationCoordinate2D(
@@ -2490,19 +2491,26 @@ struct Place: RowConvertible, Persistable, Codable {
}
}
}
// Free database support!
extension Place: RowConvertible, Persistable {
static let databaseTableName = "places"
}
```
As documented with the [Persistable](#persistable-protocol) protocol, have you struct records use MutablePersistable instead of Persistable when they store their automatically incremented row id:
As documented with the [Persistable](#persistable-protocol) protocol, have your struct records use MutablePersistable instead of Persistable when they store their automatically incremented row id:
```swift
struct Place: RowConvertible, MutablePersistable, Codable {
static let databaseTableName = "places"
struct Place: Codable {
var id: Int64? // <- the row id
var title: String
var latitude: CLLocationDegrees
var longitude: CLLocationDegrees
var coordinate: CLLocationCoordinate2D { ... }
}
extension Place: RowConvertible, MutablePersistable {
static let databaseTableName = "places"
mutating func didInsert(with rowID: Int64, for column: String?) {
// Update id after insertion
@@ -4496,19 +4504,6 @@ try dbQueue.inTransaction { db in
}
```
> :point_up: **Note**: for SQLite, empty [deferred](#transaction-kinds) transactions are no transaction at all. In this case, the transaction callback is never executed:
>
> ```swift
> // Empty deferred transaction
> dbQueue.inTransaction { db in
> db.afterNextTransactionCommit { db in
> // Never executed
> print("success")
> }
> return .commit
> }
> ```
### TransactionObserver Protocol
@@ -4627,15 +4622,6 @@ do {
> :point_up: **Note**: all callbacks are called in a protected dispatch queue, and serialized with all database updates.
>
> :point_up: **Note**: the databaseDidChange(with:) and databaseWillCommit() callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument.
>
> :point_up: **Note**: for SQLite, empty [deferred](#transaction-kinds) transactions are no transaction at all. In this case, transaction observers are not notified:
>
> ```swift
> // Empty deferred transaction does not notify transaction observers
> dbQueue.inTransaction { db in
> return .commit
> }
> ```
[FetchedRecordsController](#fetchedrecordscontroller) and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) are based on the TransactionObserver protocol.
@@ -4737,16 +4723,6 @@ dbQueue.inDatabase { db in
- `.databaseLifetime` has the database retain and notify the observer until the database connection is closed.
> :point_up: **Note**: for SQLite, empty [deferred](#transaction-kinds) transactions are no transaction at all. In this case, an observer added with the `.nextTransaction` extent is never notified of any transaction:
>
> ```swift
> // Empty deferred transaction
> dbQueue.inTransaction { db in
> // Observer is never notified of any transaction
> db.add(transactionObserver: observer, extent: .nextTransaction)
> return .commit
> }
> ```
#### Support for SQLite Pre-Update Hooks
@@ -5118,7 +5094,7 @@ Alternatively, perform a manual installation of GRDB and SQLCipher:
```sh
cd [GRDB directory]
git checkout v2.3.0
git checkout v2.3.1
git submodule update --init SQLCipher/src
```
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>2.3.0</string>
<string>2.3.1</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
@@ -9,7 +9,41 @@ import XCTest
class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
func testDatabaseAfterNextTransactionCommit() throws {
func testTransactionCompletions() throws {
// implicit transaction
try assertTransaction(start: "", end: "CREATE TABLE t(a)", isNotifiedAs: .commit)
// explicit commit
try assertTransaction(start: "BEGIN DEFERRED TRANSACTION", end: "COMMIT", isNotifiedAs: .commit)
try assertTransaction(start: "BEGIN DEFERRED TRANSACTION; CREATE TABLE t(a)", end: "COMMIT", isNotifiedAs: .commit)
try assertTransaction(start: "BEGIN IMMEDIATE TRANSACTION", end: "COMMIT", isNotifiedAs: .commit)
try assertTransaction(start: "BEGIN IMMEDIATE TRANSACTION; CREATE TABLE t(a)", end: "COMMIT", isNotifiedAs: .commit)
try assertTransaction(start: "BEGIN EXCLUSIVE TRANSACTION", end: "COMMIT", isNotifiedAs: .commit)
try assertTransaction(start: "BEGIN EXCLUSIVE TRANSACTION; CREATE TABLE t(a)", end: "COMMIT", isNotifiedAs: .commit)
try assertTransaction(start: "SAVEPOINT test", end: "COMMIT", isNotifiedAs: .commit)
try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a)", end: "COMMIT", isNotifiedAs: .commit)
try assertTransaction(start: "SAVEPOINT test; ROLLBACK TRANSACTION TO SAVEPOINT test", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit)
try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a); ROLLBACK TRANSACTION TO SAVEPOINT test", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit)
try assertTransaction(start: "SAVEPOINT test", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit)
try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a)", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit)
// explicit rollback
try assertTransaction(start: "BEGIN DEFERRED TRANSACTION", end: "ROLLBACK", isNotifiedAs: .rollback)
try assertTransaction(start: "BEGIN DEFERRED TRANSACTION; CREATE TABLE t(a)", end: "ROLLBACK", isNotifiedAs: .rollback)
try assertTransaction(start: "BEGIN IMMEDIATE TRANSACTION", end: "ROLLBACK", isNotifiedAs: .rollback)
try assertTransaction(start: "BEGIN IMMEDIATE TRANSACTION; CREATE TABLE t(a)", end: "ROLLBACK", isNotifiedAs: .rollback)
try assertTransaction(start: "BEGIN EXCLUSIVE TRANSACTION", end: "ROLLBACK", isNotifiedAs: .rollback)
try assertTransaction(start: "BEGIN EXCLUSIVE TRANSACTION; CREATE TABLE t(a)", end: "ROLLBACK", isNotifiedAs: .rollback)
try assertTransaction(start: "SAVEPOINT test", end: "ROLLBACK", isNotifiedAs: .rollback)
try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a)", end: "ROLLBACK", isNotifiedAs: .rollback)
}
func assertTransaction(start startSQL: String, end endSQL: String, isNotifiedAs expectedCompletion: Database.TransactionCompletion) throws {
try assertTransaction_registerBefore(start: startSQL, end: endSQL, isNotifiedAs: expectedCompletion)
try assertTransaction_registerBetween(start: startSQL, end: endSQL, isNotifiedAs: expectedCompletion)
}
func assertTransaction_registerBefore(start startSQL: String, end endSQL: String, isNotifiedAs expectedCompletion: Database.TransactionCompletion) throws {
class Witness { }
let dbQueue = try makeDatabaseQueue()
@@ -26,29 +60,39 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
}
}
XCTAssertNotNil(deallocationWitness)
XCTAssertEqual(transactionCount, 0)
try db.inTransaction {
try db.execute("CREATE TABLE t(a)")
return .commit
try db.execute(startSQL)
try db.execute(endSQL)
switch expectedCompletion {
case .commit:
XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)")
case .rollback:
XCTAssertEqual(transactionCount, 0, "\(startSQL); \(endSQL)")
}
XCTAssertEqual(transactionCount, 1)
XCTAssertNil(deallocationWitness)
try db.inTransaction {
try db.execute("DROP TABLE t")
try db.execute("DROP TABLE IF EXISTS t; CREATE TABLE t(a); ")
return .commit
}
XCTAssertEqual(transactionCount, 1)
switch expectedCompletion {
case .commit:
XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)")
case .rollback:
XCTAssertEqual(transactionCount, 0, "\(startSQL); \(endSQL)")
}
}
}
func testDatabaseAfterNextTransactionWithEmptyDeferredTransaction() throws {
func assertTransaction_registerBetween(start startSQL: String, end endSQL: String, isNotifiedAs expectedCompletion: Database.TransactionCompletion) throws {
class Witness { }
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var transactionCount = 0
try db.execute(startSQL)
weak var deallocationWitness: Witness? = nil
do {
let witness = Witness()
@@ -60,51 +104,27 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
}
}
XCTAssertNotNil(deallocationWitness)
XCTAssertEqual(transactionCount, 0)
try db.inTransaction(.deferred) { .commit }
XCTAssertEqual(transactionCount, 0)
try db.execute(endSQL)
switch expectedCompletion {
case .commit:
XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)")
case .rollback:
XCTAssertEqual(transactionCount, 0, "\(startSQL); \(endSQL)")
}
XCTAssertNil(deallocationWitness)
try db.inTransaction {
try db.execute("CREATE TABLE t(a)")
try db.execute("DROP TABLE IF EXISTS t; CREATE TABLE t(a); ")
return .commit
}
XCTAssertEqual(transactionCount, 0)
}
}
func testDatabaseAfterNextTransactionCommitWithRollback() throws {
class Witness { }
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var transactionCount = 0
weak var deallocationWitness: Witness? = nil
do {
let witness = Witness()
deallocationWitness = witness
db.afterNextTransactionCommit { _ in
// use witness
withExtendedLifetime(witness, { })
transactionCount += 1
}
switch expectedCompletion {
case .commit:
XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)")
case .rollback:
XCTAssertEqual(transactionCount, 0, "\(startSQL); \(endSQL)")
}
XCTAssertEqual(transactionCount, 0)
try db.inTransaction {
try db.execute("CREATE TABLE t(a)")
return .rollback
}
XCTAssertEqual(transactionCount, 0)
XCTAssertNil(deallocationWitness)
try db.inTransaction {
try db.execute("CREATE TABLE t(a)")
return .commit
}
XCTAssertEqual(transactionCount, 0)
}
}
}
@@ -39,7 +39,7 @@ class ConcurrencyTests: GRDBTestCase {
}
func testDeferredTransactionConcurrency() throws {
let dbQueue1 = try makeDatabaseQueue()
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
#if GRDBCIPHER_USE_ENCRYPTION
// Work around SQLCipher bug when two connections are open to the
// same empty database: make sure the database is not empty before
@@ -48,7 +48,7 @@ class ConcurrencyTests: GRDBTestCase {
try db.execute("CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
}
#endif
let dbQueue2 = try makeDatabaseQueue()
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
// Queue 1 Queue 2
// BEGIN DEFERRED TRANSACTION
@@ -118,8 +118,8 @@ class ConcurrencyTests: GRDBTestCase {
}
func testExclusiveTransactionConcurrency() throws {
let dbQueue1 = try makeDatabaseQueue()
let dbQueue2 = try makeDatabaseQueue()
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
// Queue 1 Queue 2
// BEGIN EXCLUSIVE TRANSACTION
@@ -174,8 +174,8 @@ class ConcurrencyTests: GRDBTestCase {
}
func testImmediateTransactionConcurrency() throws {
let dbQueue1 = try makeDatabaseQueue()
let dbQueue2 = try makeDatabaseQueue()
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
// Queue 1 Queue 2
// BEGIN IMMEDIATE TRANSACTION
@@ -230,7 +230,7 @@ class ConcurrencyTests: GRDBTestCase {
}
func testBusyCallback() throws {
let dbQueue1 = try makeDatabaseQueue()
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
#if GRDBCIPHER_USE_ENCRYPTION
// Work around SQLCipher bug when two connections are open to the
// same empty database: make sure the database is not empty before
@@ -239,7 +239,7 @@ class ConcurrencyTests: GRDBTestCase {
try db.execute("CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
}
#endif
let dbQueue2 = try makeDatabaseQueue()
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
// Queue 1 Queue 2
// BEGIN EXCLUSIVE TRANSACTION
@@ -293,7 +293,7 @@ class ConcurrencyTests: GRDBTestCase {
}
func testReaderDuringDefaultTransaction() throws {
let dbQueue1 = try makeDatabaseQueue()
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
#if GRDBCIPHER_USE_ENCRYPTION
// Work around SQLCipher bug when two connections are open to the
// same empty database: make sure the database is not empty before
@@ -302,7 +302,7 @@ class ConcurrencyTests: GRDBTestCase {
try db.execute("CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
}
#endif
let dbQueue2 = try makeDatabaseQueue()
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
// Here we test that a reader can read while a writer is writing.
@@ -359,7 +359,7 @@ class ConcurrencyTests: GRDBTestCase {
}
func testReaderInDeferredTransactionDuringDefaultTransaction() throws {
let dbQueue1 = try makeDatabaseQueue()
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
#if GRDBCIPHER_USE_ENCRYPTION
// Work around SQLCipher bug when two connections are open to the
// same empty database: make sure the database is not empty before
@@ -368,7 +368,7 @@ class ConcurrencyTests: GRDBTestCase {
try db.execute("CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
}
#endif
let dbQueue2 = try makeDatabaseQueue()
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
// The `SELECT * FROM stuffs` statement of Queue 2 prevents Queue 1
// from committing with SQLITE_BUSY.
@@ -12,12 +12,12 @@ class DatabaseQueueReadOnlyTests : GRDBTestCase {
func testReadOnlyDatabaseCanNotBeModified() throws {
// Create database
do {
_ = try makeDatabaseQueue()
_ = try makeDatabaseQueue(filename: "test.sqlite")
}
// Open it again, readonly
dbConfiguration.readonly = true
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
let statement = try dbQueue.inDatabase { db in
try db.makeUpdateStatement("CREATE TABLE items (id INTEGER PRIMARY KEY)")
}
+31 -31
View File
@@ -7,7 +7,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPassphraseToDatabaseQueueWithPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -16,7 +16,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM data")!, 1)
}
@@ -26,7 +26,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPassphraseToDatabaseQueueWithoutPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -36,7 +36,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = nil
do {
_ = try makeDatabaseQueue()
_ = try makeDatabaseQueue(filename: "test.sqlite")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
XCTAssertEqual(error.message!, "file is encrypted or is not a database")
@@ -49,7 +49,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPassphraseToDatabaseQueueWithWrongPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -59,7 +59,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "wrong"
do {
_ = try makeDatabaseQueue()
_ = try makeDatabaseQueue(filename: "test.sqlite")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
XCTAssertEqual(error.message!, "file is encrypted or is not a database")
@@ -72,7 +72,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPassphraseToDatabaseQueueWithNewPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -81,7 +81,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.change(passphrase: "newSecret")
try dbQueue.inDatabase { db in
try db.execute("INSERT INTO data (value) VALUES (2)")
@@ -93,7 +93,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "newSecret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM data")!, 2)
}
@@ -103,7 +103,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPassphraseToDatabasePoolWithPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -112,7 +112,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool()
let dbPool = try makeDatabasePool(filename: "test.sqlite")
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM data")!, 1)
}
@@ -122,7 +122,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPassphraseToDatabasePoolWithoutPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -132,7 +132,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = nil
do {
_ = try makeDatabasePool()
_ = try makeDatabasePool(filename: "test.sqlite")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
XCTAssertEqual(error.message!, "file is encrypted or is not a database")
@@ -145,7 +145,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPassphraseToDatabasePoolWithWrongPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -155,7 +155,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "wrong"
do {
_ = try makeDatabasePool()
_ = try makeDatabasePool(filename: "test.sqlite")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
XCTAssertEqual(error.message!, "file is encrypted or is not a database")
@@ -168,7 +168,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPassphraseToDatabasePoolWithNewPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -177,7 +177,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool()
let dbPool = try makeDatabasePool(filename: "test.sqlite")
try dbPool.change(passphrase: "newSecret")
try dbPool.write { db in
try db.execute("INSERT INTO data (value) VALUES (2)")
@@ -187,7 +187,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "newSecret"
let dbPool = try makeDatabasePool()
let dbPool = try makeDatabasePool(filename: "test.sqlite")
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM data")!, 2)
}
@@ -197,7 +197,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabasePoolWithPassphraseToDatabasePoolWithPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool()
let dbPool = try makeDatabasePool(filename: "test.sqlite")
try dbPool.write { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -206,7 +206,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool()
let dbPool = try makeDatabasePool(filename: "test.sqlite")
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM data")!, 1)
}
@@ -216,7 +216,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabasePoolWithPassphraseToDatabasePoolWithoutPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool()
let dbPool = try makeDatabasePool(filename: "test.sqlite")
try dbPool.write { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -226,7 +226,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = nil
do {
_ = try makeDatabasePool()
_ = try makeDatabasePool(filename: "test.sqlite")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
XCTAssertEqual(error.message!, "file is encrypted or is not a database")
@@ -239,7 +239,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabasePoolWithPassphraseToDatabasePoolWithWrongPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool()
let dbPool = try makeDatabasePool(filename: "test.sqlite")
try dbPool.write { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -249,7 +249,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "wrong"
do {
_ = try makeDatabasePool()
_ = try makeDatabasePool(filename: "test.sqlite")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
XCTAssertEqual(error.message!, "file is encrypted or is not a database")
@@ -263,7 +263,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool()
let dbPool = try makeDatabasePool(filename: "test.sqlite")
try dbPool.write { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -272,7 +272,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool()
let dbPool = try makeDatabasePool(filename: "test.sqlite")
try dbPool.change(passphrase: "newSecret")
try dbPool.write { db in
try db.execute("INSERT INTO data (value) VALUES (2)")
@@ -282,7 +282,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "newSecret"
let dbPool = try makeDatabasePool()
let dbPool = try makeDatabasePool(filename: "test.sqlite")
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM data")!, 2)
}
@@ -292,7 +292,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPragmaPassphraseToDatabaseQueueWithPassphrase() throws {
do {
dbConfiguration.passphrase = nil
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
try db.execute("PRAGMA key = 'secret'")
try db.execute("CREATE TABLE data (value INTEGER)")
@@ -302,7 +302,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM data")!, 1)
}
@@ -312,7 +312,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPragmaPassphraseToDatabaseQueueWithoutPassphrase() throws {
do {
dbConfiguration.passphrase = nil
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
try db.execute("PRAGMA key = 'secret'")
try db.execute("CREATE TABLE data (value INTEGER)")
@@ -323,7 +323,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = nil
do {
_ = try makeDatabaseQueue()
_ = try makeDatabaseQueue(filename: "test.sqlite")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
XCTAssertEqual(error.message!, "file is encrypted or is not a database")
+4 -4
View File
@@ -17,18 +17,18 @@ class GRDBTestCase: XCTestCase {
var dbConfiguration: Configuration!
// Builds a database queue based on dbConfiguration
func makeDatabaseQueue(filename: String = "db.sqlite") throws -> DatabaseQueue {
func makeDatabaseQueue(filename: String? = nil) throws -> DatabaseQueue {
try FileManager.default.createDirectory(atPath: dbDirectoryPath, withIntermediateDirectories: true, attributes: nil)
let dbPath = (dbDirectoryPath as NSString).appendingPathComponent(filename)
let dbPath = (dbDirectoryPath as NSString).appendingPathComponent(filename ?? ProcessInfo.processInfo.globallyUniqueString)
let dbQueue = try DatabaseQueue(path: dbPath, configuration: dbConfiguration)
try setup(dbQueue)
return dbQueue
}
// Builds a database pool based on dbConfiguration
func makeDatabasePool(filename: String = "db.sqlite") throws -> DatabasePool {
func makeDatabasePool(filename: String? = nil) throws -> DatabasePool {
try FileManager.default.createDirectory(atPath: dbDirectoryPath, withIntermediateDirectories: true, attributes: nil)
let dbPath = (dbDirectoryPath as NSString).appendingPathComponent(filename)
let dbPath = (dbDirectoryPath as NSString).appendingPathComponent(filename ?? ProcessInfo.processInfo.globallyUniqueString)
let dbPool = try DatabasePool(path: dbPath, configuration: dbConfiguration)
try setup(dbPool)
return dbPool
+11 -11
View File
@@ -10,9 +10,9 @@ import XCTest
class SchedulingWatchdogTests: GRDBTestCase {
func testSchedulingWatchdog() throws {
let dbQueue1 = try makeDatabaseQueue(filename: "db1")
let dbQueue2 = try makeDatabaseQueue(filename: "db2")
let dbQueue3 = try makeDatabaseQueue(filename: "db3")
let dbQueue1 = try makeDatabaseQueue()
let dbQueue2 = try makeDatabaseQueue()
let dbQueue3 = try makeDatabaseQueue()
var db1: Database! = nil
var db2: Database! = nil
@@ -51,8 +51,8 @@ class SchedulingWatchdogTests: GRDBTestCase {
}
func testDatabaseQueueFromDatabaseQueue() throws {
let dbQueue1 = try makeDatabaseQueue(filename: "db1")
let dbQueue2 = try makeDatabaseQueue(filename: "db2")
let dbQueue1 = try makeDatabaseQueue()
let dbQueue2 = try makeDatabaseQueue()
try dbQueue1.inDatabase { db1 in
try db1.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db1.execute("INSERT INTO items (id) VALUES (NULL)")
@@ -71,8 +71,8 @@ class SchedulingWatchdogTests: GRDBTestCase {
}
func testDatabaseQueueFromDatabasePool() throws {
let dbPool1 = try makeDatabasePool(filename: "db1")
let dbQueue2 = try makeDatabaseQueue(filename: "db2")
let dbPool1 = try makeDatabasePool()
let dbQueue2 = try makeDatabaseQueue()
try dbPool1.write { db1 in
try db1.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db1.execute("INSERT INTO items (id) VALUES (NULL)")
@@ -91,8 +91,8 @@ class SchedulingWatchdogTests: GRDBTestCase {
}
func testDatabasePoolFromDatabaseQueue() throws {
let dbQueue1 = try makeDatabaseQueue(filename: "db1")
let dbPool2 = try makeDatabasePool(filename: "db2")
let dbQueue1 = try makeDatabaseQueue()
let dbPool2 = try makeDatabasePool()
try dbQueue1.inDatabase { db1 in
try db1.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db1.execute("INSERT INTO items (id) VALUES (NULL)")
@@ -111,8 +111,8 @@ class SchedulingWatchdogTests: GRDBTestCase {
}
func testDatabasePoolFromDatabasePool() throws {
let dbPool1 = try makeDatabasePool(filename: "db1")
let dbPool2 = try makeDatabasePool(filename: "db2")
let dbPool1 = try makeDatabasePool()
let dbPool2 = try makeDatabasePool()
try dbPool1.write { db1 in
try db1.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db1.execute("INSERT INTO items (id) VALUES (NULL)")
File diff suppressed because it is too large. Load diff