一、前言
以前寫過一篇關于CoreData,Realm,SQLite的文章(文章鏈接),里面大概就是介紹了一下它們的用法和推薦的三方庫,建議再看這篇文章之前可以瀏覽一下之前的那篇文章。今天在這里我就來說一下關于它們的數據庫遷移問題,數據庫的遷移都是非嵌套的遷移方式,這樣就可以避免有的用戶沒有及時更新帶來的隱患。
二、CoreData
CoreData需要遷移的時候需要在
- (nullable __kindof NSPersistentStore *)addPersistentStoreWithType:(NSString *)storeType configuration:(nullable NSString *)configuration URL:(nullable NSURL *)storeURL options:(nullable NSDictionary *)options error:(NSError **)error
這個方法里面的options參數添加兩個key-value
NSDictionary *options = @{NSMigratePersistentStoresAutomaticallyOption:@(YES), NSInferMappingModelAutomaticallyOption:@(YES)};
NSMigratePersistentStoresAutomaticallyOption = YES,那么Core Data會試著把之前低版本的出現不兼容的持久化存儲區遷移到新的模型中,這里的例子里,Core Data就能識別出是新表
NSInferMappingModelAutomaticallyOption = YES,這個參數的意義是Core Data會根據自己認為最合理的方式去嘗試MappingModel,從源模型實體的某個屬性,映射到目標模型實體的某個屬性。
CoreData的遷移方式分為三種:
- 輕量級的遷移
- 默認的遷移方式
- 遷移管理器
2.1.輕量級遷移方式過程
1.選中.xcdatamodeld文件,然后選擇Editor-->add Model Version
2.在新的.xcdatamodel中新增一個字段,author字段
3.然后選擇.xcdatamodeld 選擇Model Version
4.現在我們還需要將原來Book的表結構生成的Book.h、 Book.m、Book+CoreDataProperties.h、Book+CoreDataProperties.m替換成新的,Student同樣。 將原來的這四個文件直接刪除,然后再創建新的就可以了
xcode8 創建的以后的文件格式會變成這樣,把原先的Book.h變成了Book+CoreDataClass.h文件,原先使用的Book.h現在全部改成Book+CoreDataClass.h。
我在原來的基礎上有插入100個數據,插入代碼:
NSManagedObjectContext *context = self.appDelegate.managedObjectContext;
NSLog(@"save start");
for (int i = 0; i < 100; i++) {
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];
//創建學生對象
Student *stu = [[Student alloc] initWithEntity:entity insertIntoManagedObjectContext:context];
stu.name = [NSString stringWithFormat:@"張三%d", i];
NSEntityDescription *bEntity = [NSEntityDescription entityForName:@"Book" inManagedObjectContext:context];
//創建Book對象
Book *book = [[Book alloc] initWithEntity:bEntity insertIntoManagedObjectContext:context];
book.title = @"紅樓夢";
book.author = @"曹雪芹";
//添加Book對象
[stu addBooksObject:book];
//保存Student對象
[_appDelegate saveContext];
}
NSLog(@"save end");
5.前后數據庫對比
2.2默認遷移
涉及表映射到另外一張表(實體)使用默認遷移
1.同輕量級遷移步驟1
2.在新的.xcdatamodel中將Book實體,修改兩個屬性名,增刪屬性
3.同輕量級遷移步驟3
4.同輕量級遷移步驟4
5.創建MappingModel,將之前的CoreData.xcdatamodel選作為Source,后面創建的CoreData2.xcdatamodel作為Target,前后不能選錯。
之后會生成一個.xcmappingmodel文件:
運行新增100個遷移前后數據對比
2.2遷移管理器遷移
前面的兩種操作都是需要對表進行一次操作才能完成數據庫的遷移,包括插入數據,查詢數據都可以完成數據庫的遷移工作。這里的管理器遷移,不需要對表進行一次操作。
遷移管理器操作的前5個步驟和默認遷移的步驟一樣,只是不需要對表進行一次操作,我們需要做的是使用遷移器進行操作,操作的基本步驟就是先判斷是否需要遷移,這個里面有兩部分,一部分是本地是否有這個數據庫,一部分是在有數據庫的基礎上判斷存儲數據的元數據(NSManagedObjectModel),具體操作的代碼如下:
1.是否需要遷移
- (BOOL)judgeDataMigrationIsNeed {
//是否存在文件
NSURL *storeURL = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:@"CoreDataTest.sqlite"];
if (![[NSFileManager defaultManager] fileExistsAtPath:storeURL.path]) {
return NO;
}
NSError *error = nil;
//比較存儲模型的元數據。
NSDictionary *sourceMataData = [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:NSSQLiteStoreType URL:storeURL error:&error];
NSManagedObjectModel *destinationModel = _appDelegate.managedObjectModel;
if ([destinationModel isConfiguration:nil compatibleWithStoreMetadata:sourceMataData]) {
return NO;
}
return YES;
}
2.遷移器遷移數據具體代碼
- (BOOL)executeMigration {
BOOL success = NO;
NSError *error = nil;
NSURL *sourceStore = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:@"CoreDataTest.sqlite"];
//原來的數據模型的原信息
NSDictionary *sourceMetadata = [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:NSSQLiteStoreType URL:sourceStore error:&error];
//原數據模型
NSManagedObjectModel *sourceModel = [NSManagedObjectModel mergedModelFromBundles:nil forStoreMetadata:sourceMetadata];
//最新版數據模型
NSManagedObjectModel *destinModel = _appDelegate.managedObjectModel;
//數據遷移的映射模型
NSMappingModel *mappingModel = [NSMappingModel mappingModelFromBundles:nil
forSourceModel:sourceModel
destinationModel:destinModel];
if (mappingModel) {
NSError *error = nil;
//遷移管理器
NSMigrationManager *migrationManager = [[NSMigrationManager alloc]initWithSourceModel:sourceModel
destinationModel:destinModel];
//這里可以注冊監聽 NSMigrationManager 的 migrationProgress來查看進度
[migrationManager addObserver:self forKeyPath:@"migrationProgress" options:NSKeyValueObservingOptionNew context:nil];
//先把模型存錯到Temp.sqlite
NSURL *destinStore = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:@"Temp.sqlite"];
success = [migrationManager migrateStoreFromURL:sourceStore
type:NSSQLiteStoreType
options:nil
withMappingModel:mappingModel
toDestinationURL:destinStore
destinationType:NSSQLiteStoreType
destinationOptions:nil
error:&error];
if (success) {
//替換掉原來的舊的文件
success = [[NSFileManager defaultManager] replaceItemAtURL:sourceStore withItemAtURL:destinStore backupItemName:@"backup.sqlite" options:NSFileManagerItemReplacementUsingNewMetadataOnly | NSFileManagerItemReplacementWithoutDeletingBackupItem resultingItemURL:nil error:nil];
if (success) {
// 這里移除監聽就可以了。
[migrationManager removeObserver:self forKeyPath:@"migrationProgress"];
}
}
}
return success;
}
Realm
其實這里不用說的太啰嗦,遷移的方法github的例子里面有關于遷移的部分。這里有一點說明一下,在沒有完成遷移之前,只要對realm進行訪問都會崩潰,包括訪問數據庫的位置。我這里就簡單的做一下演示和說明:
1.我用之前的默認的realm創建了一個default.realm,打開文件,查看Student
表如下圖:
2.遷移代碼
- 2.1刪除一個字段
- (void)excuteMigration {
RLMMigrationBlock migratiobBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {
// 你修改那個表就對那個進行枚舉
if (oldSchemaVersion < 1) {
[migration enumerateObjects:Student.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
// 刪除一個屬性值 我們不需要任何操作 只需要修改模型即可
}];
}
// 獲取默認配置
RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
// 修改默認配置版本和遷移block 注意版本號的變化
config.schemaVersion = 1;
config.migrationBlock = migratiobBlock;
[RLMRealmConfiguration setDefaultConfiguration:config];
// 執行打開realm,完成遷移
[RLMRealm defaultRealm];
}
- 2.1.1 遷移之后
- 2.2增加一個字段
- (void)excuteMigration {
RLMMigrationBlock migratiobBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {
// 你修改那個表就對那個進行枚舉
if (oldSchemaVersion < 1) {
[migration enumerateObjects:Student.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
// 刪除一個屬性值 我們不需要任何操作 只需要修改模型即可
}];
}
// 在前面的基礎上新增一個字段,如果不需要默認值,可不加這句話,如果一個字段需要其他字段的協助,需要自行進行操作
if (oldSchemaVersion < 2) {
[migration enumerateObjects:Student.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
//這里給新增的字段添加一個默認值
newObject[@"sex"] = @"男";
}];
}
// 獲取默認配置
RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
// 修改默認配置版本和遷移block 注意版本號的變化
config.schemaVersion = 2;
config.migrationBlock = migratiobBlock;
[RLMRealmConfiguration setDefaultConfiguration:config];
// 執行打開realm,完成遷移
[RLMRealm defaultRealm];
}
- 2.2.1遷移之后
- 2.3字段類型的變化
- (void)excuteMigration {
RLMMigrationBlock migratiobBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {
// 你修改那個表就對那個進行枚舉
if (oldSchemaVersion < 1) {
[migration enumerateObjects:Student.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
// 刪除一個屬性值 我們不需要任何操作 只需要修改模型即可
}];
}
// 在前面的基礎上新增一個字段,如果不需要默認值,可不加這句話,如果一個字段需要其他字段的協助,需要自行進行操作
if (oldSchemaVersion < 2) {
[migration enumerateObjects:Student.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
//這里給新增的字段添加一個默認值
newObject[@"sex"] = @"男";
}];
}
if (oldSchemaVersion < 3) {
[migration enumerateObjects:Student.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
if (oldObject && oldObject.objectSchema[@"sex"].type == RLMPropertyTypeString) {
newObject[@"sex"] = @([Student sexTypeForString:oldObject[@"sex"]]);
}
}];
}
};
// 獲取默認配置
RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
// 修改默認配置版本和遷移block 注意版本號的變化
config.schemaVersion = 3;
config.migrationBlock = migratiobBlock;
[RLMRealmConfiguration setDefaultConfiguration:config];
// 執行打開realm,完成遷移
[RLMRealm defaultRealm];
}
- 2.3.1執行之后
*3.Student模型變化
#import <Realm/Realm.h>
#import "Book.h"
// V0
//@interface Student : RLMObject
//@property int num;
//@property NSString *name;
//@property int age;
//@property RLMArray<Book *><Book> *books; //這里表示一對多的關系
//
//@end
RLM_ARRAY_TYPE(Student) //宏定義 定義RLMArray<Student>這個類型
//V1
//@interface Student : RLMObject
//@property int num;
//@property NSString *name;
//@property RLMArray<Book *><Book> *books; //這里表示一對多的關系
//
//@end
//V2
//@interface Student : RLMObject
//@property int num;
//@property NSString *name;
//@property NSString *sex;
//@property RLMArray<Book *><Book> *books; //這里表示一對多的關系
//@end
//V3
typedef NS_ENUM(NSInteger, Sex) {
Unknow = 0,
Male,
Female
};
@interface Student : RLMObject
@property int num;
@property NSString *name;
@property Sex sex;
@property RLMArray<Book *><Book> *books; //這里表示一對多的關系
+ (Sex)sexTypeForString:(NSString *)typeString;
@end
SQLite
關于SQLite數據庫的遷移涉及到iOS的基本全部是FMDB相關的一個三方庫FMDBMigrationManager,其實就是利用SQLite提供的ALTER TABLE命令來進行數據庫的遷移,關于SQLite數據庫遷移大家可以自行簡書相關FMDB的遷移,我在這里就不演示了,對比前面兩種的遷移方式,我感覺自己以后不會再用FMDB這個三方庫了。
總結
除非你們的數據庫設計特別完美,完全能滿足你們以后的版本迭代需求,你不需要進行數據庫的升級,但是這種情況也極少數發生,所以數據庫升級在所難免,都提前準備好自己需要使用那種,這里為你準備了一篇關于數據庫遷移的,歡迎收藏,歡迎吐槽。