Refactor DatabaseTransactionDelegate into TransactionObserverType

This commit is contained in:
Gwendal Roué committed 2015-09-28 08:50:25 +02:00
1 parent 4b082fa0a0
commit 6fcc986e1a
10 files changed
+343 -342

No files matched your search

+3 -1
View File
@@ -3,7 +3,9 @@ Release Notes
## Next Release
- DatabaseTransactionDelegate protocol.
**New**
- The `Configuration.transactionObserver` lets you observe database changes.
## 0.18.0
+13 -9
View File
@@ -5,6 +5,18 @@ class GRDBTestCase: XCTestCase {
var databasePath: String!
var dbQueue: DatabaseQueue!
var sqlQueries: [String]!
var dbConfiguration: Configuration {
var dbConfiguration = Configuration()
dbConfiguration.trace = { (sql, arguments) in
self.sqlQueries.append(sql)
if let arguments = arguments {
NSLog("GRDB: %@ -- arguments: %@", sql, arguments.description)
} else {
NSLog("GRDB: %@", sql)
}
}
return dbConfiguration
}
override func setUp() {
super.setUp()
@@ -12,15 +24,7 @@ class GRDBTestCase: XCTestCase {
sqlQueries = []
databasePath = "/tmp/GRDB.sqlite"
do { try NSFileManager.defaultManager().removeItemAtPath(databasePath) } catch { }
let configuration = Configuration(trace: { (sql, arguments) in
self.sqlQueries.append(sql)
if let arguments = arguments {
NSLog("GRDB: %@ -- arguments: %@", sql, arguments.description)
} else {
NSLog("GRDB: %@", sql)
}
})
dbQueue = try! DatabaseQueue(path: databasePath, configuration: configuration)
dbQueue = try! DatabaseQueue(path: databasePath, configuration: dbConfiguration)
}
override func tearDown() {
@@ -3,7 +3,7 @@ import GRDB
class ConcurrencyTests: XCTestCase {
var databasePath: String!
var busyCallback: Database.BusyCallback?
var busyCallback: BusyCallback?
var dbQueue1: DatabaseQueue!
var dbLog1: [String]!
@@ -17,7 +17,7 @@ class ConcurrencyTests: XCTestCase {
databasePath = "/tmp/GRDBConcurrencyTests.sqlite"
do { try NSFileManager.defaultManager().removeItemAtPath(databasePath) } catch { }
self.busyCallback = nil
let busyCallback: Database.BusyCallback = {
let busyCallback: BusyCallback = {
if let busyCallback = self.busyCallback {
return busyCallback(numberOfTries: $0)
} else {
@@ -25,9 +25,9 @@ class ConcurrencyTests: XCTestCase {
return false
}
}
let baseConfiguration = Configuration(
trace: Configuration.logSQL,
busyMode: .Callback(busyCallback))
var baseConfiguration = Configuration()
baseConfiguration.trace = LogSQL
baseConfiguration.busyMode = .Callback(busyCallback)
dbLog1 = []
var configuration1 = baseConfiguration
@@ -1,22 +1,22 @@
import XCTest
import GRDB
class TransactionDelegate : DatabaseTransactionDelegate {
var lastTransactionCompletion: Database.TransactionCompletion! = nil
class TransactionObserver : TransactionObserverType {
var lastTransactionCompletion: TransactionCompletion! = nil
var lastCommittedEvents: [DatabaseEvent] = []
var events: [DatabaseEvent] = []
func database(db: Database, didChangeWithEvent event: DatabaseEvent) {
func databaseDidChangeWithEvent(event: DatabaseEvent) {
events.append(event)
}
func databaseDidCommit(db: Database) {
func databaseDidCommit() {
lastTransactionCompletion = .Commit
lastCommittedEvents = events
events = []
}
func databaseDidRollback(db: Database) {
func databaseDidRollback() {
lastTransactionCompletion = .Rollback
lastCommittedEvents = []
events = []
@@ -99,7 +99,8 @@ class Artwork : Record {
}
}
class DatabaseTransactionDelegateTests: GRDBTestCase {
class TransactionObserverTests: GRDBTestCase {
var observer: TransactionObserver!
override func setUp() {
super.setUp()
@@ -112,21 +113,26 @@ class DatabaseTransactionDelegateTests: GRDBTestCase {
}
}
override var dbConfiguration: Configuration {
observer = TransactionObserver()
var c = super.dbConfiguration
c.transactionObserver = observer
return c
}
func match(event event: DatabaseEvent, kind: DatabaseEvent.Kind, tableName: String, rowId: Int64) -> Bool {
return (event.tableName == tableName) && (event.rowID == rowId) && (event.kind == kind)
}
func testInsertEvent() {
let delegate = TransactionDelegate()
assertNoError {
try dbQueue.inDatabase { db in
db.transactionDelegate = delegate
let artist = Artist(name: "Gerhard Richter")
//
try artist.save(db)
XCTAssertEqual(delegate.lastCommittedEvents.count, 1)
let event = delegate.lastCommittedEvents.filter { event in
XCTAssertEqual(self.observer.lastCommittedEvents.count, 1)
let event = self.observer.lastCommittedEvents.filter { event in
self.match(event: event, kind: .Insert, tableName: "artists", rowId: artist.id!)
}.first
XCTAssertTrue(event != nil)
@@ -135,18 +141,16 @@ class DatabaseTransactionDelegateTests: GRDBTestCase {
}
func testUpdateEvent() {
let delegate = TransactionDelegate()
assertNoError {
try dbQueue.inDatabase { db in
db.transactionDelegate = delegate
let artist = Artist(name: "Gerhard Richter")
try artist.save(db)
artist.name = "Vincent Fournier"
//
try artist.save(db)
XCTAssertEqual(delegate.lastCommittedEvents.count, 1)
let event = delegate.lastCommittedEvents.filter {
XCTAssertEqual(self.observer.lastCommittedEvents.count, 1)
let event = self.observer.lastCommittedEvents.filter {
self.match(event: $0, kind: .Update, tableName: "artists", rowId: artist.id!)
}.first
XCTAssertTrue(event != nil)
@@ -155,17 +159,15 @@ class DatabaseTransactionDelegateTests: GRDBTestCase {
}
func testDeleteEvent() {
let delegate = TransactionDelegate()
assertNoError {
try dbQueue.inDatabase { db in
db.transactionDelegate = delegate
let artist = Artist(name: "Gerhard Richter")
try artist.save(db)
//
try artist.delete(db)
XCTAssertEqual(delegate.lastCommittedEvents.count, 1)
let event = delegate.lastCommittedEvents.filter {
XCTAssertEqual(self.observer.lastCommittedEvents.count, 1)
let event = self.observer.lastCommittedEvents.filter {
self.match(event: $0, kind: .Delete, tableName: "artists", rowId: artist.id!)
}.first
XCTAssertTrue(event != nil)
@@ -174,10 +176,8 @@ class DatabaseTransactionDelegateTests: GRDBTestCase {
}
func testCascadingDeleteEvents() {
let delegate = TransactionDelegate()
assertNoError {
try dbQueue.inDatabase { db in
db.transactionDelegate = delegate
let artist = Artist(name: "Gerhard Richter")
try artist.save(db)
let artwork1 = Artwork(title: "Cloud", artistId: artist.id)
@@ -187,16 +187,16 @@ class DatabaseTransactionDelegateTests: GRDBTestCase {
//
try artist.delete(db)
XCTAssertEqual(delegate.lastCommittedEvents.count, 3)
let artistEvent = delegate.lastCommittedEvents.filter {
XCTAssertEqual(self.observer.lastCommittedEvents.count, 3)
let artistEvent = self.observer.lastCommittedEvents.filter {
self.match(event: $0, kind: .Delete, tableName: "artists", rowId: artist.id!)
}.first
XCTAssertTrue(artistEvent != nil)
let artwork1Event = delegate.lastCommittedEvents.filter {
let artwork1Event = self.observer.lastCommittedEvents.filter {
self.match(event: $0, kind: .Delete, tableName: "artworks", rowId: artwork1.id!)
}.first
XCTAssertTrue(artwork1Event != nil)
let artwork2Event = delegate.lastCommittedEvents.filter {
let artwork2Event = self.observer.lastCommittedEvents.filter {
self.match(event: $0, kind: .Delete, tableName: "artworks", rowId: artwork2.id!)
}.first
XCTAssertTrue(artwork2Event != nil)
@@ -205,39 +205,36 @@ class DatabaseTransactionDelegateTests: GRDBTestCase {
}
func testTransactionCommit() {
let delegate = TransactionDelegate()
assertNoError {
let artist = Artist(name: "Gerhard Richter")
let artwork1 = Artwork(title: "Cloud")
let artwork2 = Artwork(title: "Ema (Nude on a Staircase)")
try dbQueue.inTransaction { db in
db.transactionDelegate = delegate
try artist.save(db)
artwork1.artistId = artist.id
artwork2.artistId = artist.id
XCTAssertEqual(delegate.lastCommittedEvents.count, 0)
XCTAssertEqual(self.observer.lastCommittedEvents.count, 0)
try artwork1.save(db)
XCTAssertEqual(delegate.lastCommittedEvents.count, 0)
XCTAssertEqual(self.observer.lastCommittedEvents.count, 0)
try artwork2.save(db)
XCTAssertEqual(delegate.lastCommittedEvents.count, 0)
XCTAssertEqual(self.observer.lastCommittedEvents.count, 0)
return .Commit
}
XCTAssertEqual(delegate.lastTransactionCompletion, Database.TransactionCompletion.Commit)
XCTAssertEqual(delegate.lastCommittedEvents.count, 3)
let artistEvent = delegate.lastCommittedEvents.filter {
XCTAssertEqual(observer.lastTransactionCompletion, TransactionCompletion.Commit)
XCTAssertEqual(observer.lastCommittedEvents.count, 3)
let artistEvent = observer.lastCommittedEvents.filter {
self.match(event: $0, kind: .Insert, tableName: "artists", rowId: artist.id!)
}.first
XCTAssertTrue(artistEvent != nil)
let artwork1Event = delegate.lastCommittedEvents.filter {
let artwork1Event = observer.lastCommittedEvents.filter {
self.match(event: $0, kind: .Insert, tableName: "artworks", rowId: artwork1.id!)
}.first
XCTAssertTrue(artwork1Event != nil)
let artwork2Event = delegate.lastCommittedEvents.filter {
let artwork2Event = observer.lastCommittedEvents.filter {
self.match(event: $0, kind: .Insert, tableName: "artworks", rowId: artwork2.id!)
}.first
XCTAssertTrue(artwork2Event != nil)
@@ -245,30 +242,27 @@ class DatabaseTransactionDelegateTests: GRDBTestCase {
}
func testTransactionRollback() {
let delegate = TransactionDelegate()
assertNoError {
let artist = Artist(name: "Gerhard Richter")
let artwork1 = Artwork(title: "Cloud")
let artwork2 = Artwork(title: "Ema (Nude on a Staircase)")
try dbQueue.inTransaction { db in
db.transactionDelegate = delegate
try artist.save(db)
artwork1.artistId = artist.id
artwork2.artistId = artist.id
XCTAssertEqual(delegate.lastCommittedEvents.count, 0)
XCTAssertEqual(self.observer.lastCommittedEvents.count, 0)
try artwork1.save(db)
XCTAssertEqual(delegate.lastCommittedEvents.count, 0)
XCTAssertEqual(self.observer.lastCommittedEvents.count, 0)
try artwork2.save(db)
XCTAssertEqual(delegate.lastCommittedEvents.count, 0)
XCTAssertEqual(self.observer.lastCommittedEvents.count, 0)
return .Rollback
}
XCTAssertEqual(delegate.lastTransactionCompletion, Database.TransactionCompletion.Rollback)
XCTAssertEqual(delegate.lastCommittedEvents.count, 0)
XCTAssertEqual(observer.lastTransactionCompletion, TransactionCompletion.Rollback)
XCTAssertEqual(observer.lastCommittedEvents.count, 0)
}
}
}
+9 -15
View File
@@ -7,10 +7,8 @@
objects = {
/* Begin PBXBuildFile section */
5607EFCC1BB7F72D00605DE3 /* DatabaseTransactionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFCB1BB7F72D00605DE3 /* DatabaseTransactionDelegate.swift */; settings = {ASSET_TAGS = (); }; };
5607EFCD1BB7F72D00605DE3 /* DatabaseTransactionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFCB1BB7F72D00605DE3 /* DatabaseTransactionDelegate.swift */; settings = {ASSET_TAGS = (); }; };
5607EFD31BB8254800605DE3 /* DatabaseTransactionDelegateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* DatabaseTransactionDelegateTests.swift */; settings = {ASSET_TAGS = (); }; };
5607EFD41BB827FD00605DE3 /* DatabaseTransactionDelegateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* DatabaseTransactionDelegateTests.swift */; settings = {ASSET_TAGS = (); }; };
5607EFD31BB8254800605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; settings = {ASSET_TAGS = (); }; };
5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; settings = {ASSET_TAGS = (); }; };
5614DEF01BA9DA15003163B3 /* SQLiteStatementConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5614DEEF1BA9DA15003163B3 /* SQLiteStatementConvertible.swift */; settings = {ASSET_TAGS = (); }; };
5614DEF11BA9DA15003163B3 /* SQLiteStatementConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5614DEEF1BA9DA15003163B3 /* SQLiteStatementConvertible.swift */; settings = {ASSET_TAGS = (); }; };
5614DEF81BAA1B43003163B3 /* DatabaseValueConversionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */; settings = {ASSET_TAGS = (); }; };
@@ -271,8 +269,7 @@
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
5607EFCB1BB7F72D00605DE3 /* DatabaseTransactionDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTransactionDelegate.swift; sourceTree = "<group>"; };
5607EFD21BB8254800605DE3 /* DatabaseTransactionDelegateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTransactionDelegateTests.swift; sourceTree = "<group>"; };
5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = "<group>"; };
5614DEEF1BA9DA15003163B3 /* SQLiteStatementConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteStatementConvertible.swift; sourceTree = "<group>"; };
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = "<group>"; };
5683C2681B4D445E00296494 /* libsqlite3.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libsqlite3.dylib; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.4.sdk/usr/lib/libsqlite3.dylib; sourceTree = DEVELOPER_DIR; };
@@ -419,12 +416,12 @@
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
5607EFD11BB8253300605DE3 /* DatabaseTransactionDelegate */ = {
5607EFD11BB8253300605DE3 /* TransactionObserver */ = {
isa = PBXGroup;
children = (
5607EFD21BB8254800605DE3 /* DatabaseTransactionDelegateTests.swift */,
5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */,
);
path = DatabaseTransactionDelegate;
path = TransactionObserver;
sourceTree = "<group>";
};
5614DEEE1BA9D6F9003163B3 /* Frameworks */ = {
@@ -494,12 +491,12 @@
56AC8CCC1BA3F267009E4319 /* Concurrency */,
56A238121B9C74A90082EB20 /* Database */,
56A238151B9C74A90082EB20 /* DatabaseError */,
5607EFD11BB8253300605DE3 /* DatabaseTransactionDelegate */,
56A238171B9C74A90082EB20 /* DatabaseValue */,
56A238191B9C74A90082EB20 /* DatabaseValueConvertible */,
56A2381D1B9C74A90082EB20 /* Row */,
56EE573B1BB317B7007A6A95 /* SQLiteStatementConvertible */,
56A238201B9C74A90082EB20 /* Statement */,
5607EFD11BB8253300605DE3 /* TransactionObserver */,
);
path = Core;
sourceTree = "<group>";
@@ -630,7 +627,6 @@
56A238951B9C752B0082EB20 /* Protocols */ = {
isa = PBXGroup;
children = (
5607EFCB1BB7F72D00605DE3 /* DatabaseTransactionDelegate.swift */,
56A238961B9C752B0082EB20 /* DatabaseTableMapping.swift */,
56A238971B9C752B0082EB20 /* DatabaseValueConvertible.swift */,
56A238981B9C752B0082EB20 /* RowConvertible.swift */,
@@ -1062,7 +1058,6 @@
buildActionMask = 2147483647;
files = (
56A238901B9C75030082EB20 /* UpdateStatement.swift in Sources */,
5607EFCD1BB7F72D00605DE3 /* DatabaseTransactionDelegate.swift in Sources */,
56A2388E1B9C75030082EB20 /* StatementArguments.swift in Sources */,
56A2380A1B9C6DD20082EB20 /* StandardLibraryTypes.swift in Sources */,
5614DEF11BA9DA15003163B3 /* SQLiteStatementConvertible.swift in Sources */,
@@ -1126,7 +1121,7 @@
56A238421B9C74A90082EB20 /* DatabaseValueConversionTests.swift in Sources */,
56E589171BB8666F00CC0140 /* ExperimentalTests.swift in Sources */,
56A238441B9C74A90082EB20 /* RawRepresentableTests.swift in Sources */,
5607EFD41BB827FD00605DE3 /* DatabaseTransactionDelegateTests.swift in Sources */,
5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */,
56BB86281BA988F2001F9168 /* FMDatabasePool.m in Sources */,
56CA22231BB41565009A04C5 /* PerformanceRecord.swift in Sources */,
56A2386A1B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */,
@@ -1184,7 +1179,7 @@
56CA22221BB41565009A04C5 /* PerformanceRecord.swift in Sources */,
56E589161BB8666F00CC0140 /* ExperimentalTests.swift in Sources */,
56A238691B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */,
5607EFD31BB8254800605DE3 /* DatabaseTransactionDelegateTests.swift in Sources */,
5607EFD31BB8254800605DE3 /* TransactionObserverTests.swift in Sources */,
56A2383D1B9C74A90082EB20 /* DatabaseValueTests.swift in Sources */,
56A238571B9C74A90082EB20 /* PrimaryKeyRowIDTests.swift in Sources */,
56A238611B9C74A90082EB20 /* RecordEditedTests.swift in Sources */,
@@ -1214,7 +1209,6 @@
buildActionMask = 2147483647;
files = (
56A238AD1B9C90090082EB20 /* NSNull.swift in Sources */,
5607EFCC1BB7F72D00605DE3 /* DatabaseTransactionDelegate.swift in Sources */,
56A2389D1B9C752B0082EB20 /* RowConvertible.swift in Sources */,
56A2388D1B9C75030082EB20 /* StatementArguments.swift in Sources */,
5614DEF01BA9DA15003163B3 /* SQLiteStatementConvertible.swift in Sources */,
+61 -70
View File
@@ -3,44 +3,8 @@ Configuration are arguments to the DatabaseQueue initializers.
*/
public struct Configuration {
// MARK: - Utilities
/// A tracing function that logs SQL statements
public static func logSQL(sql: String, arguments: StatementArguments?) {
if let arguments = arguments {
NSLog("GRDB: %@ -- arguments: %@", sql, arguments.description)
} else {
NSLog("GRDB: %@", sql)
}
}
// MARK: - Configuration options
/// A SQLite threading mode. See https://www.sqlite.org/threadsafe.html.
enum ThreadingMode {
case Default
case MultiThread
case Serialized
var sqliteOpenFlags: Int32 {
switch self {
case .Default:
return 0
case .MultiThread:
return SQLITE_OPEN_NOMUTEX
case .Serialized:
return SQLITE_OPEN_FULLMUTEX
}
}
}
/**
A tracing function.
- parameter sql: An SQL query
- parameter arguments: Eventual query arguments.
*/
public typealias TraceFunction = (sql: String, arguments: StatementArguments?) -> Void
// =========================================================================
// MARK: - Misc options
/// If true, the database has support for foreign keys.
public var foreignKeysEnabled: Bool
@@ -48,17 +12,32 @@ public struct Configuration {
/// If true, the database is opened readonly.
public var readonly: Bool
/// Default transaction type
public var transactionType: Database.TransactionType
// =========================================================================
// MARK: - Transactions
/// Default transaction kind
public var defaultTransactionKind: TransactionKind
/// The optional transaction observer
public var transactionObserver: TransactionObserverType?
// =========================================================================
// MARK: - Concurrency
/// Busy Mode
public var busyMode: Database.BusyMode
public var busyMode: BusyMode
/// The Threading mode
///
/// Not public because we don't expose any public API that could have a use
/// for it.
var threadingMode: ThreadingMode = .Default
var threadingMode: ThreadingMode
// =========================================================================
// MARK: - Logging
/**
An optional tracing function.
@@ -69,44 +48,56 @@ public struct Configuration {
public var trace: TraceFunction?
// MARK: - Initialization
// =========================================================================
// MARK: - Factory Configuration
/**
Setup a configuration.
Returns a factory configuration:
You can use Configuration.logSQL as a tracing function: it logs all SQL
statements with NSLog().
- parameter foreignKeysEnabled: If true (the default), the database has
support for foreign keys.
- parameter readonly: If false (the default), the database will be created
and opened for writing. If true, the database is opened readonly.
- parameter transactionType: An optional transaction type (default
.Immediate). Unless specified otherwise, transactions opened by
DatabaseQueue.inTransaction() will use this transaction type. See
https://www.sqlite.org/lang_transaction.html for more information.
- parameter busyMode: A BusyMode (default .ImmediateError).
- parameter trace: An optional tracing function (default nil).
- returns: A Configuration.
- `foreignKeysEnabled`: true
- `readonly`: false
- `defaultTransactionKind`: Immediate
- `transactionDelegate`: nil
- `busyMode`: Immediate error
- `trace`: nil
*/
public init(
foreignKeysEnabled: Bool = true,
readonly: Bool = false,
transactionType: Database.TransactionType = .Immediate,
busyMode: Database.BusyMode = .ImmediateError,
trace: TraceFunction? = nil)
public init()
{
self.foreignKeysEnabled = foreignKeysEnabled
self.readonly = readonly
self.transactionType = transactionType
self.busyMode = busyMode
self.trace = trace
self.foreignKeysEnabled = true
self.readonly = false
self.defaultTransactionKind = .Immediate
self.transactionObserver = nil
self.busyMode = .ImmediateError
self.threadingMode = .Default
self.trace = nil
}
// MARK: - Not public
// =========================================================================
// MARK: - SQLite flags
var sqliteOpenFlags: Int32 {
return threadingMode.sqliteOpenFlags | (readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE))
}
}
/**
A tracing function.
- parameter sql: An SQL query
- parameter arguments: Eventual query arguments.
*/
public typealias TraceFunction = (sql: String, arguments: StatementArguments?) -> Void
/// A tracing function that logs SQL statements
public func LogSQL(sql: String, arguments: StatementArguments?) {
if let arguments = arguments {
NSLog("GRDB: %@ -- arguments: %@", sql, arguments.description)
} else {
NSLog("GRDB: %@", sql)
}
}
+190 -78
View File
@@ -104,19 +104,6 @@ public final class Database {
// MARK: - Transactions
/// A SQLite transaction type. See https://www.sqlite.org/lang_transaction.html
public enum TransactionType {
case Deferred
case Immediate
case Exclusive
}
/// The end of a transaction: Commit, or Rollback
public enum TransactionCompletion {
case Commit
case Rollback
}
/**
Executes a block inside a database transaction.
@@ -130,17 +117,17 @@ public final class Database {
This method is not reentrant: you can't nest transactions.
- parameter type: The transaction type
- parameter kind: The transaction kind
See https://www.sqlite.org/lang_transaction.html
- parameter block: A block that executes SQL statements and return either
.Commit or .Rollback.
- throws: The error thrown by the block.
*/
func inTransaction(type: TransactionType?, block: () throws -> TransactionCompletion) throws {
func inTransaction(kind: TransactionKind?, block: () throws -> TransactionCompletion) throws {
var completion: TransactionCompletion = .Rollback
var blockError: ErrorType? = nil
try beginTransaction(type)
try beginTransaction(kind)
do {
completion = try block()
@@ -156,7 +143,7 @@ public final class Database {
// https://www.sqlite.org/lang_transaction.html#immediate
//
// > Response To Errors Within A Transaction
//
// >
// > If certain kinds of errors occur within a transaction, the
// > transaction may or may not be rolled back automatically. The
// > errors that can cause an automatic rollback include:
@@ -188,8 +175,8 @@ public final class Database {
}
}
private func beginTransaction(type: TransactionType? = nil) throws {
switch type ?? configuration.transactionType {
private func beginTransaction(kind: TransactionKind? = nil) throws {
switch kind ?? configuration.defaultTransactionKind {
case .Deferred:
try execute("BEGIN DEFERRED TRANSACTION")
case .Immediate:
@@ -214,11 +201,7 @@ public final class Database {
The transaction delegate is notified of database changes, commits,
and rollbacks.
*/
public weak var transactionDelegate: DatabaseTransactionDelegate? = nil {
willSet {
assertValidQueue()
}
}
let transactionObserver: TransactionObserverType?
func updateStatementDidFail() {
// TODO: trigger this callback on a COMMIT or a ROLLBACK statement, and
@@ -240,12 +223,12 @@ public final class Database {
// Ready for next statement
self.pendingTransactionCompletion = nil
if let transactionDelegate = transactionDelegate {
if let transactionObserver = transactionObserver {
switch pendingTransactionCompletion {
case .Commit:
transactionDelegate.databaseDidCommit(self)
transactionObserver.databaseDidCommit()
case .Rollback:
transactionDelegate.databaseDidRollback(self)
transactionObserver.databaseDidRollback()
}
}
}
@@ -260,7 +243,7 @@ public final class Database {
sqlite3_update_hook(sqliteConnection, { (dbPointer, updateKind, databaseName, tableName, rowID) in
let db = unsafeBitCast(dbPointer, Database.self)
guard let transactionDelegate = db.transactionDelegate else {
guard let transactionObserver = db.transactionObserver else {
return
}
@@ -269,18 +252,18 @@ public final class Database {
databaseName: String.fromCString(databaseName)!,
tableName: String.fromCString(tableName)!, // Tests have shown that pointers are reused for various table names: we can't use those pointers as a cache key.
rowID: rowID)
transactionDelegate.database(db, didChangeWithEvent: event)
transactionObserver.databaseDidChangeWithEvent(event)
}, dbPointer)
sqlite3_commit_hook(sqliteConnection, { dbPointer in
let db = unsafeBitCast(dbPointer, Database.self)
db.pendingTransactionCompletion = .Commit
guard let transactionDelegate = db.transactionDelegate else {
guard let transactionObserver = db.transactionObserver else {
return 0 // commit
}
if transactionDelegate.databaseShouldCommit(db) {
if transactionObserver.databaseShouldCommit() {
return 0 // commit
}
@@ -294,51 +277,7 @@ public final class Database {
}
// MARK: - Busy Mode
/// See BusyMode and https://www.sqlite.org/c3ref/busy_handler.html
public typealias BusyCallback = (numberOfTries: Int) -> Bool
/**
When there are several connections to a database, a connection may try to
access the database while it is locked by another connection.
The BusyMode enum describes the behavior of GRDB when such a situation
occurs:
- .ImmediateError: The SQLITE_BUSY error is immediately returned to the
connection that tries to access the locked database.
- .Timeout: The SQLITE_BUSY error will be returned only if the database
remains locked for more than the specified duration.
- .Callback: Perform your custom lock handling.
To set the busy mode of a database, use Configuration:
let configuration = Configuration(busyMode: .Timeout(1))
let dbQueue = DatabaseQueue(path: "...", configuration: configuration)
Relevant SQLite documentation:
- https://www.sqlite.org/c3ref/busy_timeout.html
- https://www.sqlite.org/c3ref/busy_handler.html
- https://www.sqlite.org/lang_transaction.html
- https://www.sqlite.org/wal.html
*/
public enum BusyMode {
/// The SQLITE_BUSY error is immediately returned to the connection that
/// tries to access the locked database.
case ImmediateError
/// The SQLITE_BUSY error will be returned only if the database remains
/// locked for more than the specified duration.
case Timeout(NSTimeInterval)
/// A custom callback that is called when a database is locked.
/// See https://www.sqlite.org/c3ref/busy_handler.html
case Callback(BusyCallback)
}
// MARK: - Concurrency
/// The busy handler callback, if any. See Configuration.busyMode.
private var busyCallback: BusyCallback?
@@ -475,7 +414,7 @@ public final class Database {
// 0 | id | INTEGER | 0 | NULL | 1 |
// 1 | firstName | TEXT | 0 | NULL | 0 |
// 2 | lastName | TEXT | 0 | NULL | 0 |
struct ColumnInfo : RowConvertible {
private struct ColumnInfo : RowConvertible {
let name: String
let type: String
let notNull: Bool
@@ -492,7 +431,7 @@ public final class Database {
// Cache for columnInfosForTable(named:)
private var columnInfosCache: [String: [ColumnInfo]] = [:]
func columnInfosForTable(named tableName: String) -> [ColumnInfo] {
private func columnInfosForTable(named tableName: String) -> [ColumnInfo] {
if let columnInfos = columnInfosCache[tableName] {
return columnInfos
} else {
@@ -520,6 +459,7 @@ public final class Database {
init(path: String, configuration: Configuration) throws {
self.configuration = configuration
self.transactionObserver = configuration.transactionObserver
// See https://www.sqlite.org/c3ref/open.html
var sqliteConnection = SQLiteConnection()
@@ -585,3 +525,175 @@ enum PrimaryKey {
}
}
// =============================================================================
// MARK: - Transactions
/// A SQLite transaction kind. See https://www.sqlite.org/lang_transaction.html
public enum TransactionKind {
case Deferred
case Immediate
case Exclusive
}
/// The end of a transaction: Commit, or Rollback
public enum TransactionCompletion {
case Commit
case Rollback
}
/**
A transaction observer is notified of all changes and transactions committed or
rollbacked on a database.
Adopting types must be a class.
*/
public protocol TransactionObserverType : class {
/**
Notifies a database change (insert, update, or delete).
The change is pending until the end of the current transaction, notified to
databaseShouldCommit(_), databaseDidCommit(_) and databaseDidRollback(_).
This method is called on the database queue.
**WARNING**: this method must not change the database.
- parameter event: A database event.
*/
func databaseDidChangeWithEvent(event: DatabaseEvent)
/**
When a transaction is about to be committed, the transaction delegate has an
opportunity to rollback pending changes.
This method is called on the database queue.
**WARNING**: this method must not change the database.
- returns: Whether the transaction should be committed.
*/
func databaseShouldCommit() -> Bool
/**
Database changes have been committed.
This method is called on the database queue. It can change the database.
*/
func databaseDidCommit()
/**
Database changes have been rollbacked.
This method is called on the database queue. It can change the database.
*/
func databaseDidRollback()
}
/// Default implementations for TransactionObserverType methods.
public extension TransactionObserverType {
/// Default implementation does nothing.
func databaseDidChangeWithEvent(event: DatabaseEvent) { }
/// Default implementation return true.
func databaseShouldCommit() -> Bool { return true }
/// Default implementation does nothing.
func databaseDidCommit() { }
/// Default implementation does nothing.
func databaseDidRollback() { }
}
/**
A database event, notified to TransactionObserverType.
See https://www.sqlite.org/c3ref/update_hook.html for more information.
*/
public struct DatabaseEvent {
/// An event kind
public enum Kind: Int32 {
case Insert = 18 // SQLITE_INSERT
case Delete = 9 // SQLITE_DELETE
case Update = 23 // SQLITE_UPDATE
}
/// The event kind
public let kind: Kind
/// The database name
public let databaseName: String
/// The table name
public let tableName: String
/// The rowID of the changed row.
public let rowID: Int64
}
// =============================================================================
// MARK: - Concurrency
/// A SQLite threading mode. See https://www.sqlite.org/threadsafe.html.
enum ThreadingMode {
case Default
case MultiThread
case Serialized
var sqliteOpenFlags: Int32 {
switch self {
case .Default:
return 0
case .MultiThread:
return SQLITE_OPEN_NOMUTEX
case .Serialized:
return SQLITE_OPEN_FULLMUTEX
}
}
}
/// See BusyMode and https://www.sqlite.org/c3ref/busy_handler.html
public typealias BusyCallback = (numberOfTries: Int) -> Bool
/**
When there are several connections to a database, a connection may try to
access the database while it is locked by another connection.
The BusyMode enum describes the behavior of GRDB when such a situation
occurs:
- .ImmediateError: The SQLITE_BUSY error is immediately returned to the
connection that tries to access the locked database.
- .Timeout: The SQLITE_BUSY error will be returned only if the database
remains locked for more than the specified duration.
- .Callback: Perform your custom lock handling.
To set the busy mode of a database, use Configuration:
let configuration = Configuration(busyMode: .Timeout(1))
let dbQueue = DatabaseQueue(path: "...", configuration: configuration)
Relevant SQLite documentation:
- https://www.sqlite.org/c3ref/busy_timeout.html
- https://www.sqlite.org/c3ref/busy_handler.html
- https://www.sqlite.org/lang_transaction.html
- https://www.sqlite.org/wal.html
*/
public enum BusyMode {
/// The SQLITE_BUSY error is immediately returned to the connection that
/// tries to access the locked database.
case ImmediateError
/// The SQLITE_BUSY error will be returned only if the database remains
/// locked for more than the specified duration.
case Timeout(NSTimeInterval)
/// A custom callback that is called when a database is locked.
/// See https://www.sqlite.org/c3ref/busy_handler.html
case Callback(BusyCallback)
}
+5 -5
View File
@@ -112,16 +112,16 @@ public final class DatabaseQueue {
This method is *not* reentrant.
- parameter type: The transaction type (default nil). If nil, the
transaction type is configuration.transactionType, which itself defaults
to .Immediate. See https://www.sqlite.org/lang_transaction.html for more
information.
transaction type is configuration.defaultTransactionKind, which itself
defaults to .Immediate. See https://www.sqlite.org/lang_transaction.html
for more information.
- parameter block: A block that executes SQL statements and return either
.Commit or .Rollback.
- throws: The error thrown by the block.
*/
public func inTransaction(type: Database.TransactionType? = nil, block: (db: Database) throws -> Database.TransactionCompletion) throws {
public func inTransaction(kind: TransactionKind? = nil, block: (db: Database) throws -> TransactionCompletion) throws {
try inQueue {
try self.database.inTransaction(type) {
try self.database.inTransaction(kind) {
try block(db: self.database)
}
}
@@ -1,94 +0,0 @@
/**
The transaction delegate of a database is notified of all changes and
transactions committed or rollbacked on a database.
*/
public protocol DatabaseTransactionDelegate: class {
/**
Notifies a database change (insert, update, or delete).
The change is pending until the end of the current transaction, notified to
databaseShouldCommit(_), databaseDidCommit(_) and databaseDidRollback(_).
This method is called on the database queue.
**WARNING**: this method must not change the database.
- parameter db: A Database.
- parameter event: A database event.
*/
func database(db: Database, didChangeWithEvent event: DatabaseEvent)
/**
When a transaction is about to be committed, the transaction delegate has an
opportunity to rollback pending changes.
This method is called on the database queue.
**WARNING**: this method must not change the database.
- parameter db: A Database.
- returns: Whether the transaction should be committed.
*/
func databaseShouldCommit(db: Database) -> Bool
/**
Database changes have been committed.
This method is called on the database queue. It can change the database.
- parameter db: A Database.
*/
func databaseDidCommit(db: Database)
/**
Database changes have been rollbacked.
This method is called on the database queue. It can change the database.
- parameter db: A Database.
*/
func databaseDidRollback(db: Database)
}
/// Default implementations for DatabaseTransactionDelegate methods.
public extension DatabaseTransactionDelegate {
/// Default implementation does nothing.
func database(db: Database, didChangeWithEvent event: DatabaseEvent) { }
/// Default implementation return true.
func databaseShouldCommit(db: Database) -> Bool { return true }
/// Default implementation does nothing.
func databaseDidCommit(db: Database) { }
/// Default implementation does nothing.
func databaseDidRollback(db: Database) { }
}
/**
A database event, notified to DatabaseTransactionDelegate.
See https://www.sqlite.org/c3ref/update_hook.html for more information.
*/
public struct DatabaseEvent {
/// An event kind
public enum Kind: Int32 {
case Insert = 18 // SQLITE_INSERT
case Delete = 9 // SQLITE_DELETE
case Update = 23 // SQLITE_UPDATE
}
/// The event kind
public let kind: Kind
/// The database name
public let databaseName: String
/// The table name
public let tableName: String
/// The rowID of the changed row.
public let rowID: Int64
}
+20 -22
View File
@@ -191,16 +191,14 @@ The database connection is closed when the database queue gets deallocated.
**Configure** databases:
```swift
let configuration = Configuration(
foreignKeysEnabled: true, // Default true
readonly: false, // Default false
trace: Configuration.logSQL // An optional trace function.
// Configuration.logSQL logs all SQL statements.
)
var config = Configuration()
config.foreignKeysEnabled = true // Default true
config.readonly: false // Default false
config.trace = LogSQL // The built-in LogSQL function logs all SQL statements with NSLog.
let dbQueue = try DatabaseQueue(
path: "/path/to/database.sqlite",
configuration: configuration)
configuration: config)
```
See [Concurrency](#concurrency) for more details on database configuration.
@@ -956,21 +954,21 @@ for path in migrationPaths {
## Database Changes Observation
**The DatabaseTransactionDelegate protocol** lets you observe database changes:
The TransactionObserverType protocol lets you **observe database changes**:
```swift
public protocol DatabaseTransactionDelegate: class {
public protocol TransactionObserverType : class {
// Notifies a database change (insert, update, or delete):
func database(db: Database, didChangeWithEvent event: DatabaseEvent)
func databaseDidChangeWithEvent(event: DatabaseEvent)
// An opportunity to rollback pending changes.
func databaseShouldCommit(db: Database) -> Bool
func databaseShouldCommit() -> Bool
// Database changes have been committed.
func databaseDidCommit(db: Database)
func databaseDidCommit()
// Database changes have been rollbacked.
func databaseDidRollback(db: Database)
func databaseDidRollback()
}
```
@@ -1006,15 +1004,15 @@ try dbQueue.inDatabase do { db in
As a sample code, let's write an object that uses NSNotificationCenter to notify, on the main thread, of modified database tables. Your view controllers can listen to those notifications and update their views accordingly.
```swift
class TableChangeNotifier : DatabaseTransactionDelegate {
class TableChangeObserver : TransactionObserverType {
var changedTableNames: Set<String> = []
func database(db: Database, didChangeWithEvent event: DatabaseEvent) {
func databaseDidChangeWithEvent(event: DatabaseEvent) {
// Remember the name of the changed table:
changedTableNames.insert(event.tableName)
}
func databaseDidCommit(db: Database) {
func databaseDidCommit() {
// Extract the names of changed tables, and reset until
// next database event:
let changedTableNames = self.changedTableNames
@@ -1029,18 +1027,18 @@ class TableChangeNotifier : DatabaseTransactionDelegate {
}
}
func databaseDidRollback(db: Database) {
func databaseDidRollback() {
// Forget the names of changed tables:
self.changedTableNames = []
}
}
// Activate notifications:
let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
let notifier = TableChangeNotifier()
dbQueue.inDatabase { db in
db.transactionDelegate = notifier
}
var config = Configuration()
config.transactionObserver = TableChangeNotifier()
let dbQueue = try DatabaseQueue(
path: "/path/to/database.sqlite",
configuration: config)
```