FMDB 版本迁移
安装
1. 通过CocoaPods
在项目根目录创建并编辑 Podfile 内容如下
$ cd /path/to/MyProject
$ touch Podfile
$ edit Podfile
platform :ios, '5.0'
# Or platform :osx, '10.7'
pod 'FMDBMigrationManager'
导入
$ pod install
打开项目,开始使用
$ open MyProject.xcworkspace
2. 手动
添加 FMDBMigrationManager.h
和 FMDBMigrationManager.m
,在使用的地方 #import "FMDBMigrationManager.h"
使用
创建迁移表
FMDBMigrationManager *manager = [FMDBMigrationManager managerWithDatabaseAtPath:@"path/to/your/DB.sqlite" migrationsBundle:[NSBundle mainBundle]];
NSError *error = nil;
BOOL success = [manager createMigrationsTable:&error];
创建补丁文件
$ touch "`ruby -e "puts Time.now.strftime('%Y%m%d%H%M%S%3N').to_i"`"_CreateMyAwesomeTable.sql
在sql文件中写入数据库变更内容,然后添加到项目中 (Application Bundle)
迁移
FMDBMigrationManager *manager = [FMDBMigrationManager managerWithDatabaseAtPath:@"path/to/your/DB.sqlite" migrationsBundle:[NSBundle mainBundle]];
NSError *error = nil;
BOOL success = [manager migrateDatabaseToVersion:UINT64_MAX progress:nil error:&error];
检查迁移状态
FMDBMigrationManager *manager = [FMDBMigrationManager managerWithDatabaseAtPath:@"path/to/your/DB.sqlite" migrationsBundle:[NSBundle mainBundle]];
NSLog(@"Has `schema_migrations` table?: %@", manager.hasMigrationsTable ? @"YES" : @"NO");
NSLog(@"Origin Version: %llu", manager.originVersion);
NSLog(@"Current version: %llu", manager.currentVersion);
NSLog(@"All migrations: %@", manager.migrations);
NSLog(@"Applied versions: %@", manager.appliedVersions);
NSLog(@"Pending versions: %@", manager.pendingVersions);
使用记录
《新天翼视讯项目》
- 手动加入 FMDBMigrationManager 文件;
-
生成、编辑sql补丁文件,并加入项目;
ALTER TABLE DownLoadMedia ADD resumeData;
-
添加迁移方法,不用指定脚本文件,会根据版本号自动识别;
- (void)migrationDB { FMDBMigrationManager *manager = [FMDBMigrationManager managerWithDatabaseAtPath:kDATABASEFILE_PATH migrationsBundle:[NSBundle mainBundle]]; NSError *error = nil;
BOOL result = NO;
if (!manager.hasMigrationsTable) {
result = [manager createMigrationsTable:&error];
} result = [manager migrateDatabaseToVersion:UINT64_MAX progress:nil error:&error]; NSLog(@"Has `schema_migrations` table?: %@", manager.hasMigrationsTable ? @"YES" : @"NO");
NSLog(@"Origin Version: %llu", manager.originVersion);
NSLog(@"Current version: %llu", manager.currentVersion);
NSLog(@"All migrations: %@", manager.migrations);
NSLog(@"Applied versions: %@", manager.appliedVersions);
NSLog(@"Pending versions: %@", manager.pendingVersions);
} -
启动自动迁移;
+ (void)load {
[[DataCenter sharedDataCenter] migrationDB];
}