mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-30 04:28:44 +00:00
Experimental DatabaseTransactionDelegate
Built on top of sqlite3_update_hook, sqlite3_commit_hook and sqlite3_rollback_hook.
This commit is contained in:
1 parent
bc474ae583
commit
a6267a2acb
6 files changed
+157
-35
No files matched your search
@@ -5,6 +5,7 @@ class GRDBTestCase: XCTestCase {
|
||||
var databasePath: String!
|
||||
var dbQueue: DatabaseQueue!
|
||||
var sqlQueries: [String]!
|
||||
let transactionLogger = TransactionLogger()
|
||||
|
||||
override func setUp() {
|
||||
super.setUp()
|
||||
@@ -21,6 +22,9 @@ class GRDBTestCase: XCTestCase {
|
||||
}
|
||||
})
|
||||
dbQueue = try! DatabaseQueue(path: databasePath, configuration: configuration)
|
||||
dbQueue.inDatabase { db in
|
||||
db.transactionDelegate = self.transactionLogger
|
||||
}
|
||||
}
|
||||
|
||||
override func tearDown() {
|
||||
@@ -42,3 +46,34 @@ class GRDBTestCase: XCTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// EXPERIMENTAL
|
||||
class TransactionLogger : DatabaseTransactionDelegate {
|
||||
var events: [DatabaseEvent] = []
|
||||
|
||||
func databaseDidChangeWithEvent(event: DatabaseEvent) {
|
||||
events.append(event)
|
||||
}
|
||||
|
||||
func databaseWillCommit() {
|
||||
guard events.count > 0 else {
|
||||
return
|
||||
}
|
||||
|
||||
print("DATABASE DID COMMIT")
|
||||
for event in events {
|
||||
switch event.kind {
|
||||
case .Insert:
|
||||
print("-> INSERT \(event.tableName) \(event.rowID)")
|
||||
case .Delete:
|
||||
print("-> DELETE \(event.tableName) \(event.rowID)")
|
||||
case .Update:
|
||||
print("-> UPDATE \(event.tableName) \(event.rowID)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func databaseWillRollback() {
|
||||
events.removeAll()
|
||||
}
|
||||
}
|
||||
@@ -7,6 +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 = (); }; };
|
||||
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 = (); }; };
|
||||
@@ -265,6 +267,7 @@
|
||||
/* End PBXContainerItemProxy section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
5607EFCB1BB7F72D00605DE3 /* DatabaseTransactionDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTransactionDelegate.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; };
|
||||
@@ -612,6 +615,7 @@
|
||||
56A238951B9C752B0082EB20 /* Protocols */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5607EFCB1BB7F72D00605DE3 /* DatabaseTransactionDelegate.swift */,
|
||||
56A238961B9C752B0082EB20 /* DatabaseTableMapping.swift */,
|
||||
56A238971B9C752B0082EB20 /* DatabaseValueConvertible.swift */,
|
||||
56A238981B9C752B0082EB20 /* RowConvertible.swift */,
|
||||
@@ -1042,6 +1046,7 @@
|
||||
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 */,
|
||||
@@ -1189,6 +1194,7 @@
|
||||
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 */,
|
||||
|
||||
+75
-20
@@ -84,7 +84,7 @@ public final class Database {
|
||||
- throws: A DatabaseError whenever a SQLite error occurs.
|
||||
*/
|
||||
public func executeMultiStatement(sql: String) throws -> DatabaseChanges {
|
||||
assertValid()
|
||||
assertValidQueue()
|
||||
|
||||
if let trace = self.configuration.trace {
|
||||
trace(sql: sql, arguments: nil)
|
||||
@@ -208,6 +208,52 @@ public final class Database {
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Transaction Delegate
|
||||
|
||||
/// EXPERIMENTAL
|
||||
public weak var transactionDelegate: DatabaseTransactionDelegate? = nil {
|
||||
willSet {
|
||||
assertValidQueue()
|
||||
}
|
||||
didSet {
|
||||
if transactionDelegate == nil {
|
||||
sqlite3_update_hook(sqliteConnection, nil, nil)
|
||||
sqlite3_commit_hook(sqliteConnection, nil, nil)
|
||||
sqlite3_rollback_hook(sqliteConnection, nil, nil)
|
||||
return
|
||||
}
|
||||
|
||||
let dbPointer = unsafeBitCast(self, UnsafeMutablePointer<Void>.self)
|
||||
|
||||
sqlite3_update_hook( sqliteConnection, { (dbPointer, updateKind, databaseName, tableName, rowID) in
|
||||
let event = DatabaseEvent(
|
||||
kind: DatabaseEvent.Kind(rawValue: updateKind)!,
|
||||
databaseName: String.fromCString(databaseName)!,
|
||||
tableName: String.fromCString(tableName)!,
|
||||
rowID: rowID)
|
||||
let database = unsafeBitCast(dbPointer, Database.self)
|
||||
database.transactionDelegate!.databaseDidChangeWithEvent(event)
|
||||
}, dbPointer)
|
||||
|
||||
sqlite3_commit_hook(sqliteConnection, { dbPointer in
|
||||
let database = unsafeBitCast(dbPointer, Database.self)
|
||||
if database.transactionDelegate!.databaseShouldCommit() {
|
||||
database.transactionDelegate!.databaseWillCommit()
|
||||
return 0
|
||||
} else {
|
||||
return 1
|
||||
}
|
||||
}, dbPointer)
|
||||
|
||||
sqlite3_rollback_hook(sqliteConnection, { dbPointer in
|
||||
let database = unsafeBitCast(dbPointer, Database.self)
|
||||
database.transactionDelegate!.databaseWillRollback()
|
||||
}, dbPointer)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// MARK: - Database Informations
|
||||
|
||||
/// The last error message
|
||||
@@ -400,7 +446,7 @@ public final class Database {
|
||||
/// The SQLite connection handle
|
||||
let sqliteConnection: SQLiteConnection
|
||||
|
||||
/// The queue from which the database can be used. See assertValid().
|
||||
/// The queue from which the database can be used. See assertValidQueue().
|
||||
/// Design note: this is not very clean. A delegation pattern may be a
|
||||
/// better fit.
|
||||
var databaseQueueID: DatabaseQueueID = nil
|
||||
@@ -420,16 +466,7 @@ public final class Database {
|
||||
try execute("PRAGMA foreign_keys = ON")
|
||||
}
|
||||
|
||||
switch configuration.busyMode {
|
||||
case .ImmediateError:
|
||||
break
|
||||
case .Timeout(let duration):
|
||||
let milliseconds = Int32(duration * 1000)
|
||||
sqlite3_busy_timeout(sqliteConnection, milliseconds)
|
||||
case .Callback(let callback):
|
||||
self.busyCallback = callback
|
||||
sqlite3_busy_handler(sqliteConnection, sqliteBusyHandler, unsafeBitCast(self, UnsafeMutablePointer<Void>.self))
|
||||
}
|
||||
setupBusyMode(configuration.busyMode)
|
||||
}
|
||||
|
||||
// Initializes an in-memory database
|
||||
@@ -441,21 +478,39 @@ public final class Database {
|
||||
sqlite3_close(sqliteConnection)
|
||||
}
|
||||
|
||||
func assertValid() {
|
||||
func assertValidQueue() {
|
||||
guard databaseQueueID == nil || databaseQueueID == dispatch_get_specific(DatabaseQueue.databaseQueueIDKey) else {
|
||||
fatalError("Database was not used on the correct queue. Execute your statements inside DatabaseQueue.inDatabase() or DatabaseQueue.inTransaction(). Consider using fetchAll() method if this error message happens when iterating the result of the fetch() method.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let sqliteBusyHandler: @convention(c) (UnsafeMutablePointer<Void>, Int32) -> Int32 = { dbPointer, numberOfTries in
|
||||
let database = unsafeBitCast(dbPointer, Database.self)
|
||||
let callback = database.busyCallback!
|
||||
return callback(numberOfTries: Int(numberOfTries)) ? 1 : 0
|
||||
|
||||
func setupBusyMode(busyMode: BusyMode) {
|
||||
switch busyMode {
|
||||
case .ImmediateError:
|
||||
break
|
||||
|
||||
case .Timeout(let duration):
|
||||
let milliseconds = Int32(duration * 1000)
|
||||
sqlite3_busy_timeout(sqliteConnection, milliseconds)
|
||||
|
||||
case .Callback(let callback):
|
||||
let dbPointer = unsafeBitCast(self, UnsafeMutablePointer<Void>.self)
|
||||
self.busyCallback = callback
|
||||
|
||||
sqlite3_busy_handler(
|
||||
sqliteConnection,
|
||||
{ (dbPointer: UnsafeMutablePointer<Void>, numberOfTries: Int32) in
|
||||
let database = unsafeBitCast(dbPointer, Database.self)
|
||||
let callback = database.busyCallback!
|
||||
return callback(numberOfTries: Int(numberOfTries)) ? 1 : 0
|
||||
},
|
||||
dbPointer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Database Information
|
||||
// MARK: - PrimaryKey
|
||||
|
||||
/// A primary key
|
||||
enum PrimaryKey {
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
/// EXPERIMENTAL
|
||||
public protocol DatabaseTransactionDelegate: class {
|
||||
func databaseDidChangeWithEvent(event: DatabaseEvent)
|
||||
func databaseShouldCommit() -> Bool
|
||||
func databaseWillCommit()
|
||||
func databaseWillRollback()
|
||||
}
|
||||
|
||||
public extension DatabaseTransactionDelegate {
|
||||
func databaseDidChangeWithEvent(event: DatabaseEvent) { }
|
||||
func databaseShouldCommit() -> Bool { return true }
|
||||
func databaseWillCommit() { }
|
||||
func databaseWillRollback() { }
|
||||
}
|
||||
|
||||
/// EXPERIMENTAL
|
||||
public struct DatabaseEvent {
|
||||
public enum Kind: Int32 {
|
||||
case Insert = 18 // SQLITE_INSERT
|
||||
case Delete = 9 // SQLITE_DELETE
|
||||
case Update = 23 // SQLITE_UPDATE
|
||||
}
|
||||
|
||||
public let kind: Kind
|
||||
public let databaseName: String
|
||||
public let tableName: String
|
||||
public let rowID: Int64
|
||||
}
|
||||
@@ -28,7 +28,7 @@ public final class SelectStatement : Statement {
|
||||
/**
|
||||
The DatabaseSequence builder.
|
||||
*/
|
||||
func fetch<T>(arguments arguments: StatementArguments?, map: () -> T) -> DatabaseSequence<T> {
|
||||
func fetch<T>(arguments arguments: StatementArguments?, yield: () -> T) -> DatabaseSequence<T> {
|
||||
if let arguments = arguments {
|
||||
self.arguments = arguments
|
||||
}
|
||||
@@ -37,7 +37,7 @@ public final class SelectStatement : Statement {
|
||||
trace(sql: self.sql, arguments: self.arguments)
|
||||
}
|
||||
|
||||
return DatabaseSequence(statement: self, map: map)
|
||||
return DatabaseSequence(statement: self, yield: yield)
|
||||
}
|
||||
|
||||
/// The column index, case insensitive.
|
||||
@@ -64,19 +64,18 @@ A sequence of elements fetched from the database.
|
||||
*/
|
||||
public struct DatabaseSequence<T>: SequenceType {
|
||||
let statement: SelectStatement
|
||||
let map: () -> T
|
||||
let yield: () -> T
|
||||
|
||||
/// Return a *generator* over the elements of this *sequence*.
|
||||
@warn_unused_result
|
||||
public func generate() -> DatabaseGenerator<T> {
|
||||
// Check that sequence is built on a valid database.
|
||||
// See DatabaseQueue.inSafeDatabase().
|
||||
statement.database.assertValid()
|
||||
statement.database.assertValidQueue()
|
||||
|
||||
// DatabaseSequence can be restarted:
|
||||
statement.reset()
|
||||
|
||||
return DatabaseGenerator(statement: statement, map: map)
|
||||
return DatabaseGenerator(statement: statement, yield: yield)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,29 +85,28 @@ A generator of elements fetched from the database.
|
||||
public struct DatabaseGenerator<T>: GeneratorType {
|
||||
let statement: SelectStatement
|
||||
let sqliteStatement: SQLiteStatement
|
||||
let assertValid: () -> ()
|
||||
let map: () -> T
|
||||
let assertValidQueue: () -> ()
|
||||
let yield: () -> T
|
||||
|
||||
init(statement: SelectStatement, map: () -> T) {
|
||||
init(statement: SelectStatement, yield: () -> T) {
|
||||
self.statement = statement
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
self.map = map
|
||||
self.assertValid = statement.database.assertValid
|
||||
self.yield = yield
|
||||
self.assertValidQueue = statement.database.assertValidQueue
|
||||
}
|
||||
|
||||
/// Advance to the next element and return it, or `nil` if no next
|
||||
/// element exists.
|
||||
public func next() -> T? {
|
||||
// Check that generator is used on a valid database.
|
||||
// See DatabaseQueue.inSafeDatabase().
|
||||
assertValid()
|
||||
assertValidQueue()
|
||||
|
||||
let code = sqlite3_step(sqliteStatement)
|
||||
switch code {
|
||||
case SQLITE_DONE:
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return map()
|
||||
return yield()
|
||||
default:
|
||||
fatalError(DatabaseError(code: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments).description)
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ public class Statement {
|
||||
let sqliteStatement: SQLiteStatement
|
||||
|
||||
init(database: Database, sql: String) throws {
|
||||
database.assertValid()
|
||||
database.assertValidQueue()
|
||||
|
||||
// See https://www.sqlite.org/c3ref/prepare.html
|
||||
|
||||
|
||||
Reference in new issue
Block a user