2121// THE SOFTWARE.
2222//
2323
24+ import Foundation
25+
2426/// A connection (handle) to a SQLite database.
2527public final class Database {
2628
27- private let handle : COpaquePointer = nil
29+ internal let handle : COpaquePointer = nil
2830
2931 /// Whether or not the database was opened in a read-only state.
3032 public var readonly : Bool { return sqlite3_db_readonly ( handle, nil ) == 1 }
@@ -46,7 +48,7 @@ public final class Database {
4648 try ( sqlite3_open_v2 ( path ?? " " , & handle, flags, nil ) )
4749 }
4850
49- deinit { sqlite3_close ( handle) } // sqlite3_close_v2 in Yosemite/iOS 8?
51+ deinit { try ( sqlite3_close ( handle) ) } // sqlite3_close_v2 in Yosemite/iOS 8?
5052
5153 // MARK: -
5254
@@ -86,10 +88,7 @@ public final class Database {
8688 /// :returns: A prepared statement.
8789 public func prepare( statement: String , _ bindings: Binding ? ... ) -> Statement {
8890 if !bindings. isEmpty { return prepare ( statement, bindings) }
89-
90- var statementHandle : COpaquePointer = nil
91- try ( sqlite3_prepare_v2 ( handle, statement, - 1 , & statementHandle, nil ) )
92- return Statement ( statementHandle)
91+ return Statement ( self , statement)
9392 }
9493
9594 /// Prepares a single SQL statement and binds parameters to it.
@@ -332,10 +331,16 @@ public final class Database {
332331 return String . fromCString ( sqlite3_errmsg ( handle) ) !
333332 }
334333
335- private func try( block: @autoclosure ( ) -> Int32 ) {
336- if block ( ) != SQLITE_OK { assertionFailure ( " \( lastError) " ) }
334+ internal func try( block: @autoclosure ( ) -> Int32 ) {
335+ perform { if block ( ) != SQLITE_OK { assertionFailure ( " \( self . lastError) " ) } }
337336 }
338337
338+ // MARK: - Threading
339+
340+ private let queue = dispatch_queue_create ( " SQLite.Database " , DISPATCH_QUEUE_SERIAL)
341+
342+ internal func perform( block: ( ) -> ( ) ) { dispatch_sync ( queue, block) }
343+
339344}
340345
341346extension Database : DebugPrintable {
0 commit comments