Created
February 22, 2018 15:56
-
-
Save mczachurski/0c7ef7279c7d0809c6bbcb2ee4d3a39f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DatabaseContext: DatabaseContextProtocol { | |
private var sqlConnection: SqlConnectionProtocol | |
private var database: Database<SQLiteDatabaseConfiguration> | |
private let lock = NSLock() | |
public func set<T: Codable>(_ type: T.Type) -> Table<T, Database<SQLiteDatabaseConfiguration>> { | |
self.validateConnection() | |
return database.table(type) | |
} | |
init(sqlConnection: SqlConnectionProtocol) { | |
self.sqlConnection = sqlConnection | |
let databaseConfiguration = sqlConnection.getDatabaseConfiguration() as! SQLiteDatabaseConfiguration | |
self.database = Database(configuration: databaseConfiguration) | |
} | |
private func validateConnection() { | |
if self.sqlConnection.isValidConnection() { | |
return | |
} | |
lock.lock() | |
if !self.sqlConnection.isValidConnection() { | |
let databaseConfiguration = sqlConnection.getDatabaseConfiguration() as! SQLiteDatabaseConfiguration | |
self.database = Database(configuration: databaseConfiguration) | |
} | |
lock.unlock() | |
} | |
public func executeMigrations() { | |
self.validateConnection() | |
try! self.database.create(Task.self, policy: .reconcileTable) | |
try! self.database.create(User.self, policy: .reconcileTable) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment