WIP: StorageInterface methods

This commit is contained in:
John Rommel Estropia
2016-03-07 07:23:44 +09:00
parent 3c514830d9
commit 75a4ebb49b
12 changed files with 589 additions and 426 deletions

View File

@@ -72,12 +72,34 @@ public extension CoreStore {
/**
Adds a `StorageInterface` to the `defaultStack` and blocks until completion.
- parameter store: the `StorageInterface`
- parameter storage: the `StorageInterface`
- returns: the `StorageInterface` added to the `defaultStack`
*/
public static func addStorageAndWait<T: StorageInterface>(store: T) throws -> T {
public static func addStorageAndWait<T: StorageInterface>(storage: T) throws -> T {
return try self.defaultStack.addStorageAndWait(store)
return try self.defaultStack.addStorageAndWait(storage)
}
/**
Creates a `LocalStorageface` of the specified store type with default values and adds it to the `defaultStack`. This method blocks until completion.
- parameter storeType: the `LocalStorageface` type
- returns: the local storage added to the stack
*/
public static func addStorageAndWait<T: LocalStorage where T: DefaultInitializableStore>(storageType: T.Type) throws -> T {
return try self.defaultStack.addStorageAndWait(storageType.init())
}
/**
Adds a `LocalStorage` to the stack and blocks until completion.
- parameter storage: the local storage
- returns: the local storage added to the stack
*/
public static func addStorageAndWait<T: LocalStorage>(storage: T) throws -> T {
return try self.defaultStack.addStorageAndWait(storage)
}

View File

@@ -115,24 +115,20 @@ public final class DataStack {
/**
Adds a `StorageInterface` to the stack and blocks until completion.
- parameter store: the `StorageInterface`
- parameter storage: the `StorageInterface`
- returns: the `StorageInterface` added to the stack
*/
public func addStorageAndWait<T: StorageInterface>(store: T) throws -> T {
public func addStorageAndWait<T: StorageInterface>(storage: T) throws -> T {
CoreStore.assert(
store.internalStore == nil,
"The specified \"\(typeName(store))\" was already added to the data stack: \(store)"
)
CoreStore.assert(
T.validateStoreURL(store.storeURL),
"The specified store URL for the \"\(typeName(store))\" is invalid: \"\(store.storeURL)\""
storage.internalStore == nil,
"The specified \"\(typeName(storage))\" was already added to the data stack: \(storage)"
)
// TODO: check
// if let store = coordinator.persistentStoreForURL(fileURL) {
//
// guard store.type == NSSQLiteStoreType
// guard store.type == storage.dynamicType.storeType
// && store.configurationName == (configuration ?? Into.defaultConfigurationName) else {
//
// let error = NSError(coreStoreErrorCode: .DifferentPersistentStoreExistsAtURL)
@@ -152,16 +148,114 @@ public final class DataStack {
do {
let persistentStore = try store.addToPersistentStoreCoordinatorSynchronously(self.coordinator)
let persistentStore = try self.coordinator.addPersistentStoreSynchronously(
storage.dynamicType.storeType,
configuration: storage.configuration,
URL: nil,
options: storage.storeOptions
)
self.updateMetadataForPersistentStore(persistentStore)
store.internalStore = persistentStore
return store
storage.internalStore = persistentStore
return storage
}
catch {
CoreStore.handleError(
error as NSError,
"Failed to add \(typeName(T)) to the stack."
"Failed to add \(typeName(storage)) to the stack."
)
throw error
}
}
/**
Creates a `LocalStorageface` of the specified store type with default values and adds it to the stack. This method blocks until completion.
- parameter storeType: the `LocalStorageface` type
- returns: the local storage added to the stack
*/
public func addStorageAndWait<T: LocalStorage where T: DefaultInitializableStore>(storageType: T.Type) throws -> T {
return try self.addStorageAndWait(storageType.init())
}
/**
Adds a `LocalStorage` to the stack and blocks until completion.
- parameter storage: the local storage
- returns: the local storage added to the stack
*/
public func addStorageAndWait<T: LocalStorage>(storage: T) throws -> T {
CoreStore.assert(
storage.internalStore == nil,
"The specified \"\(typeName(storage))\" was already added to the data stack: \(storage)"
)
let fileURL = storage.fileURL
CoreStore.assert(
fileURL.fileURL,
"The specified store URL for the \"\(typeName(storage))\" is invalid: \"\(fileURL)\""
)
if let persistentStore = coordinator.persistentStoreForURL(fileURL) {
guard persistentStore.type == storage.dynamicType.storeType
&& persistentStore.configurationName == (storage.configuration ?? Into.defaultConfigurationName) else {
let error = NSError(coreStoreErrorCode: .DifferentPersistentStoreExistsAtURL)
CoreStore.handleError(
error,
"Failed to add SQLite \(typeName(NSPersistentStore)) at \"\(fileURL)\" because a different \(typeName(NSPersistentStore)) at that URL already exists."
)
throw error
}
storage.internalStore = persistentStore
return storage
}
do {
let coordinator = self.coordinator
let persistentStore = try coordinator.performBlockAndWait { () throws -> NSPersistentStore in
let fileManager = NSFileManager.defaultManager()
do {
try fileManager.createDirectoryAtURL(
fileURL.URLByDeletingLastPathComponent!,
withIntermediateDirectories: true,
attributes: nil
)
return try coordinator.addPersistentStoreWithType(
storage.dynamicType.storeType,
configuration: storage.configuration,
URL: fileURL,
options: storage.storeOptions
)
}
catch let error as NSError where storage.resetStoreOnModelMismatch && error.isCoreDataMigrationError {
try storage.eraseStorageAndWait()
return try coordinator.addPersistentStoreWithType(
storage.dynamicType.storeType,
configuration: storage.configuration,
URL: fileURL,
options: storage.storeOptions
)
}
}
self.updateMetadataForPersistentStore(persistentStore)
storage.internalStore = persistentStore
return storage
}
catch {
CoreStore.handleError(
error as NSError,
"Failed to add \(typeName(storage)) to the stack."
)
throw error
}
@@ -189,11 +283,6 @@ public final class DataStack {
return migrationQueue
}()
internal func optionsForSQLiteStore() -> [String: AnyObject] {
return [NSSQLitePragmasOption: ["journal_mode": "WAL"]]
}
internal func entityNameForEntityClass(entityClass: AnyClass) -> String? {
return self.model.entityNameForClass(entityClass)

View File

@@ -53,40 +53,8 @@ public class InMemoryStore: StorageInterface, DefaultInitializableStore {
return storeURL == nil
}
public let storeURL: NSURL? = nil
public let configuration: String?
public let storeOptions: [String: AnyObject]? = nil
public var internalStore: NSPersistentStore?
public func addToPersistentStoreCoordinatorSynchronously(coordinator: NSPersistentStoreCoordinator) throws -> NSPersistentStore {
return try coordinator.addPersistentStoreSynchronously(
self.dynamicType.storeType,
configuration: self.configuration,
URL: self.storeURL,
options: self.storeOptions
)
}
public func addToPersistentStoreCoordinatorAsynchronously(coordinator: NSPersistentStoreCoordinator, mappingModelBundles: [NSBundle]?, completion: (NSPersistentStore) -> Void, failure: (NSError) -> Void) throws {
coordinator.performBlock {
do {
let persistentStore = try coordinator.addPersistentStoreWithType(
self.dynamicType.storeType,
configuration: self.configuration,
URL: self.storeURL,
options: self.storeOptions
)
completion(persistentStore)
}
catch {
failure(error as NSError)
}
}
}
}

View File

@@ -30,11 +30,12 @@ import Foundation
public final class LegacySQLiteStore: SQLiteStore {
public required init(fileURL: NSURL, configuration: String? = nil, resetStoreOnModelMismatch: Bool = false) {
public required init(fileURL: NSURL, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles(), resetStoreOnModelMismatch: Bool = false) {
super.init(
fileURL: fileURL,
configuration: configuration,
mappingModelBundles: mappingModelBundles,
resetStoreOnModelMismatch: resetStoreOnModelMismatch
)
}
@@ -46,7 +47,7 @@ public final class LegacySQLiteStore: SQLiteStore {
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`, the "Default" configuration. Note that if you have multiple configurations, you will need to specify a different `fileName` explicitly for each of them.
- parameter resetStoreOnModelMismatch: When the `SQLiteStore` is passed to the `DataStack`'s `addStorage()` methods, a true value tells the `DataStack` to delete the store on model mismatch; a false value lets exceptions be thrown on failure instead. Typically should only be set to true when debugging, or if the persistent store can be recreated easily. If not specified, defaults to false.
*/
public required init(fileName: String, configuration: String? = nil, resetStoreOnModelMismatch: Bool = false) {
public required init(fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles(), resetStoreOnModelMismatch: Bool = false) {
super.init(
fileURL: LegacySQLiteStore.legacyDefaultRootDirectory.URLByAppendingPathComponent(
@@ -54,6 +55,7 @@ public final class LegacySQLiteStore: SQLiteStore {
isDirectory: false
),
configuration: configuration,
mappingModelBundles: mappingModelBundles,
resetStoreOnModelMismatch: resetStoreOnModelMismatch
)
}
@@ -63,11 +65,7 @@ public final class LegacySQLiteStore: SQLiteStore {
public required init() {
super.init(
fileURL: LegacySQLiteStore.legacyDefaultFileURL,
configuration: nil,
resetStoreOnModelMismatch: false
)
super.init(fileURL: LegacySQLiteStore.legacyDefaultFileURL)
}

View File

@@ -28,7 +28,7 @@ import CoreData
// MARK: - SQLiteStore
public class SQLiteStore: StorageInterface, DefaultInitializableStore {
public class SQLiteStore: LocalStorage, DefaultInitializableStore {
/**
Initializes an SQLite store interface from the given SQLite file URL. When this instance is passed to the `DataStack`'s `addStorage()` methods, a new SQLite file will be created if it does not exist.
@@ -37,10 +37,11 @@ public class SQLiteStore: StorageInterface, DefaultInitializableStore {
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`, the "Default" configuration. Note that if you have multiple configurations, you will need to specify a different `fileURL` explicitly for each of them.
- parameter resetStoreOnModelMismatch: When the `SQLiteStore` is passed to the `DataStack`'s `addStorage()` methods, a true value tells the `DataStack` to delete the store on model mismatch; a false value lets exceptions be thrown on failure instead. Typically should only be set to true when debugging, or if the persistent store can be recreated easily. If not specified, defaults to false.
*/
public required init(fileURL: NSURL, configuration: String? = nil, resetStoreOnModelMismatch: Bool = false) {
public required init(fileURL: NSURL, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles(), resetStoreOnModelMismatch: Bool = false) {
self.fileURL = fileURL
self.configuration = configuration
self.mappingModelBundles = mappingModelBundles
self.resetStoreOnModelMismatch = resetStoreOnModelMismatch
}
@@ -51,11 +52,12 @@ public class SQLiteStore: StorageInterface, DefaultInitializableStore {
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`, the "Default" configuration. Note that if you have multiple configurations, you will need to specify a different `fileName` explicitly for each of them.
- parameter resetStoreOnModelMismatch: When the `SQLiteStore` is passed to the `DataStack`'s `addStorage()` methods, a true value tells the `DataStack` to delete the store on model mismatch; a false value lets exceptions be thrown on failure instead. Typically should only be set to true when debugging, or if the persistent store can be recreated easily. If not specified, defaults to false.
*/
public required init(fileName: String, configuration: String? = nil, resetStoreOnModelMismatch: Bool = false) {
public required init(fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles(), resetStoreOnModelMismatch: Bool = false) {
self.fileURL = SQLiteStore.defaultRootDirectory
.URLByAppendingPathComponent(fileName, isDirectory: false)
self.configuration = configuration
self.mappingModelBundles = mappingModelBundles
self.resetStoreOnModelMismatch = resetStoreOnModelMismatch
}
@@ -66,10 +68,18 @@ public class SQLiteStore: StorageInterface, DefaultInitializableStore {
self.fileURL = SQLiteStore.defaultFileURL
self.configuration = nil
self.mappingModelBundles = NSBundle.allBundles()
self.resetStoreOnModelMismatch = false
}
// MAKR: LocalStorage
public let fileURL: NSURL
public let resetStoreOnModelMismatch: Bool
// MARK: StorageInterface
public static let storeType = NSSQLiteStoreType
@@ -78,143 +88,29 @@ public class SQLiteStore: StorageInterface, DefaultInitializableStore {
return storeURL?.fileURL == true
}
public var storeURL: NSURL? {
return self.fileURL
}
public let configuration: String?
public let storeOptions: [String: AnyObject]? = [NSSQLitePragmasOption: ["journal_mode": "WAL"]]
public let mappingModelBundles: [NSBundle]
public var internalStore: NSPersistentStore?
public func addToPersistentStoreCoordinatorSynchronously(coordinator: NSPersistentStoreCoordinator) throws -> NSPersistentStore {
public func eraseStorageAndWait() throws {
let fileManager = NSFileManager.defaultManager()
// TODO: check if attached to persistent store
do {
let fileURL = self.fileURL
try autoreleasepool {
let fileURL = self.fileURL
try fileManager.createDirectoryAtURL(
fileURL.URLByDeletingLastPathComponent!,
withIntermediateDirectories: true,
attributes: nil
)
return try coordinator.addPersistentStoreSynchronously(
let journalUpdatingCoordinator = NSPersistentStoreCoordinator()
let store = try journalUpdatingCoordinator.addPersistentStoreWithType(
self.dynamicType.storeType,
configuration: self.configuration,
URL: fileURL,
options: self.storeOptions
options: [NSSQLitePragmasOption: ["journal_mode": "DELETE"]]
)
}
catch let error as NSError where resetStoreOnModelMismatch && error.isCoreDataMigrationError {
fileManager.removeSQLiteStoreAtURL(fileURL)
return try coordinator.addPersistentStoreSynchronously(
self.dynamicType.storeType,
configuration: self.configuration,
URL: fileURL,
options: self.storeOptions
)
}
}
public func addToPersistentStoreCoordinatorAsynchronously(coordinator: NSPersistentStoreCoordinator, mappingModelBundles: [NSBundle]?, completion: (NSPersistentStore) -> Void, failure: (NSError) -> Void) throws {
let fileManager = NSFileManager.defaultManager()
do {
let fileURL = self.fileURL
try fileManager.createDirectoryAtURL(
fileURL.URLByDeletingLastPathComponent!,
withIntermediateDirectories: true,
attributes: nil
)
let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStoreOfType(
self.dynamicType.storeType,
URL: fileURL,
options: self.storeOptions
)
return self.upgradeSQLiteStoreIfNeeded(
fileURL: fileURL,
metadata: metadata,
configuration: configuration,
mappingModelBundles: mappingModelBundles,
completion: { (result) -> Void in
if case .Failure(let error) = result {
if resetStoreOnModelMismatch && error.isCoreDataMigrationError {
fileManager.removeSQLiteStoreAtURL(fileURL)
do {
let store = try self.addSQLiteStoreAndWait(
fileURL: fileURL,
configuration: configuration,
resetStoreOnModelMismatch: false
)
GCDQueue.Main.async {
completion(PersistentStoreResult(store))
}
}
catch {
completion(PersistentStoreResult(error as NSError))
}
return
}
completion(PersistentStoreResult(error))
return
}
do {
let store = try self.addSQLiteStoreAndWait(
fileURL: fileURL,
configuration: configuration,
resetStoreOnModelMismatch: false
)
completion(PersistentStoreResult(store))
}
catch {
completion(PersistentStoreResult(error as NSError))
}
}
)
}
catch let error as NSError
where error.code == NSFileReadNoSuchFileError && error.domain == NSCocoaErrorDomain {
let store = try self.addSQLiteStoreAndWait(
fileURL: fileURL,
configuration: configuration,
resetStoreOnModelMismatch: false
)
GCDQueue.Main.async {
completion(PersistentStoreResult(store))
}
return nil
}
catch {
CoreStore.handleError(
error as NSError,
"Failed to load SQLite \(typeName(NSPersistentStore)) metadata."
)
throw error
try journalUpdatingCoordinator.removePersistentStore(store)
try NSFileManager.defaultManager().removeItemAtURL(fileURL)
}
}
@@ -247,8 +143,4 @@ public class SQLiteStore: StorageInterface, DefaultInitializableStore {
.URLByAppendingPathComponent(applicationName, isDirectory: false)
.URLByAppendingPathExtension("sqlite")
}()
internal let fileURL: NSURL
internal let resetStoreOnModelMismatch: Bool
}

View File

@@ -31,17 +31,11 @@ import CoreData
public protocol StorageInterface: class {
static var storeType: String { get }
static func validateStoreURL(storeURL: NSURL?) -> Bool
var storeURL: NSURL? { get }
var configuration: String? { get }
var storeOptions: [String: AnyObject]? { get }
var internalStore: NSPersistentStore? { get set }
func addToPersistentStoreCoordinatorSynchronously(coordinator: NSPersistentStoreCoordinator) throws -> NSPersistentStore
func addToPersistentStoreCoordinatorAsynchronously(coordinator: NSPersistentStoreCoordinator, mappingModelBundles: [NSBundle]?, completion: (NSPersistentStore) -> Void, failure: (NSError) -> Void) throws
}
@@ -52,3 +46,14 @@ public protocol DefaultInitializableStore: StorageInterface {
init()
}
// MARK: - LocalStorage
public protocol LocalStorage: StorageInterface {
var fileURL: NSURL { get }
var mappingModelBundles: [NSBundle] { get }
var resetStoreOnModelMismatch: Bool { get }
func eraseStorageAndWait() throws
}

View File

@@ -27,6 +27,50 @@ import Foundation
import CoreData
// MARK: - SetupResult
public enum SetupResult<T: StorageInterface>: BooleanType {
case Success(T)
case Failure(NSError)
// MARK: BooleanType
public var boolValue: Bool {
switch self {
case .Success: return true
case .Failure: return false
}
}
// MARK: Internal
internal init(_ storage: T) {
self = .Success(storage)
}
internal init(_ error: NSError) {
self = .Failure(error)
}
internal init(_ errorCode: CoreStoreErrorCode) {
self.init(errorCode, userInfo: nil)
}
internal init(_ errorCode: CoreStoreErrorCode, userInfo: [NSObject: AnyObject]?) {
self.init(NSError(coreStoreErrorCode: errorCode, userInfo: userInfo))
}
}
// MARK: - PersistentStoreResult
/**