iOS 杂谈好东西小知识点

iOS数据库技术进阶

2017-07-02  本文已影响1277人  wu大维

数据库的技术选型一直是个令人头痛的问题,之前很长一段时间我都是使用的FMDB,做一些简单的封装。有使用过synchronized同步,也有用FMDB的DB Queue总之,差强人意。

缺点

FMDB只是将SQLite的C接口封装成了ObjC接口,没有做太多别的优化,即所谓的胶水代码(Glue Code)。使用过程需要用大量的代码拼接SQL、拼装Object,每一个表都要写一堆增删改查,并不方便。

数据库版本升级不友好,特别是第一次安装时会把所有的数据库升级代码都跑一遍。

优化

1.自动建表建库:开发者可以便捷地定义数据库表和索引,并且无须写一坨胶水代码拼装对象。

2.开发者无须拼接字符串,即可完成SQL的条件、排序、过滤、更新等等语句。

3.多线程高并发:基本的增删查改等接口都支持多线程访问,开发者无需操心线程安全问题

4.多级缓存,表数据,db信息,队列等等,都会缓存。

以上说的几点我会用微信读书开源的GYDatacenter为例,在下面详细介绍其原理和逻辑。

更加深入的优化:
加密:WCDB提供基于SQLCipher的数据库加密。
损坏修复: WCDB内建了Repair Kit用于修复损坏的数据库。
反注入: WCDB内建了对SQL注入的保护
腾讯前一阵开源的微信数据库WCDB包括了上面的所有优化
我以前分享的SQLite大量数据表的优化

如果你对ObjC的Runtime不是很了解,建议你先阅读我以前写的:RunTime理解与实战之后再阅读下面的内容

GYDatacenter

1.可以用pod或者Carthage集成GYDatacenter。然后使你的模型类继承GYModelObject:

@interface Employee : GYModelObject
@property (nonatomic, readonly, assign) NSInteger employeeId;
@property (nonatomic, readonly, strong) NSString *name;
@property (nonatomic, readonly, strong) NSDate *dateOfBirth;
@property (nonatomic, readonly, strong) Department *department;
@end

2.重写父类的方法

+ (NSString *)dbName {
    return @"GYDataCenterTests";
}

+ (NSString *)tableName {
    return @"Employee";
}

+ (NSString *)primaryKey {
    return @"employeeId";
}

+ (NSArray *)persistentProperties {
    static NSArray *properties = nil;
    if (!properties) {
        properties = @[
                       @"employeeId",
                       @"name",
                       @"dateOfBirth",
                       @"department"
                       ];
    });
    return properties;
}

3.然后你就可以像下面这样保存和查询model类的数据了:

Employee *employee = ...
[employee save];

employee = [Employee objectForId:@1];
NSArray *employees = [Employee objectsWhere:@"WHERE employeeId < ? 
ORDER BY employeeId" arguments:@[ @10 ]];

model的核心是实现GYModelObjectProtocol协议

#import <Foundation/Foundation.h>

typedef NS_ENUM(NSUInteger, GYCacheLevel) {
    GYCacheLevelNoCache,   //不缓存
    GYCacheLevelDefault,    //内存不足优先清理
    GYCacheLevelResident  //常驻
};

@protocol GYModelObjectProtocol <NSObject>

@property (nonatomic, getter=isCacheHit, readonly) BOOL cacheHit;
@property (nonatomic, getter=isFault, readonly) BOOL fault;
@property (nonatomic, getter=isSaving, readonly) BOOL saving;
@property (nonatomic, getter=isDeleted, readonly) BOOL deleted;

+ (NSString *)dbName;     //db名
+ (NSString *)tableName;  //表名
+ (NSString *)primaryKey; //主键
+ (NSArray *)persistentProperties; //入表的列

+ (NSDictionary *)propertyTypes;   //属性类型
+ (NSDictionary *)propertyClasses; //属性所在的类
+ (NSSet *)relationshipProperties; //关联属性

+ (GYCacheLevel)cacheLevel; //缓存级别

+ (NSString *)fts; //虚表

@optional
+ (NSArray *)indices; //索引
+ (NSDictionary *)defaultValues; //列 默认值

+ (NSString *)tokenize; //虚表令牌

@end

自动建表建库,更新表字段

只要你定义好了你的模型类的属性,当你准备对表数据进行增删改查操作的时候,你不需要手动的去创建表和数据库,你应该调用统一的建表接口。
如果表已经建好了,当你增加表字段(persistent properties),GYDataCenter也会自动给你更新。我画了一个图:

自动建库建表.png

注意:⚠️However, GYDataCenter CANNOT delete or rename an existing column. If you plan to do so, you need to create a new table and migrate the data yourself.
GYDataCenter不能删除和重命名已经存在的列,如果你一定要这么做,需要重新建一张表并migrate数据。

GYDataCenter还可以自动的管理索引(indices),缓存(cacheLevel),事务等等。

以查询为例:

NSArray *employees = [Employee objectsWhere:@"WHERE employeeId < 
? ORDER BY employeeId"  arguments:@[ @10 ]];

不需要为每一个表去写查询接口,只要在参数中写好条件即可。开发者无须拼接字符串,即可完成SQL的条件、排序、过滤、更新等等语句。

思考

NSArray *array = [DeptUser objectsWhere:
@",userinfo where deptUsers.uid = userinfo.uid" arguments:nil];

如果参试这样写联合查询,会产生一个错误!

image.png

原因是:查询结果FMResultSet是按index解析通过KVC赋值modelClass的属性。
你可以通过指定arguments或者调用指定的联合查询接口joinObjectsWithLeftProperties来解决这个问题

下面是我在其源码中写了一个按字段解析方式来验证这个问题,有兴趣的可以看一下。

- (void)setProperty:(NSString *)property ofObject:object withResultSet:(FMResultSet *)resultSet{
    Class<GYModelObjectProtocol> modelClass = [object class];
    GYPropertyType propertyType = [[[modelClass propertyTypes] objectForKey:property] unsignedIntegerValue];
    Class propertyClass;
    if (propertyType == GYPropertyTypeRelationship) {
        propertyClass = [[modelClass propertyClasses] objectForKey:property];
        propertyType = [[[propertyClass propertyTypes] objectForKey:[propertyClass primaryKey]] unsignedIntegerValue];
    }
    
    id value = nil;
    if (![self needSerializationForType:propertyType]) {
        if (propertyType == GYPropertyTypeDate) {
            value = [resultSet dateForColumn:property];
        } else {
            value = [resultSet objectForColumnName:property];
        }
    } else {
        NSData *data = [resultSet dataForColumn:property];
        if (data.length) {
            if (propertyType == GYPropertyTypeTransformable) {
                Class propertyClass = [[modelClass propertyClasses] objectForKey:property];
                value = [propertyClass reverseTransformedValue:data];
            } else {
                value = [self valueAfterDecodingData:data];
            }
            if (!value) {
                NSAssert(NO, @"database=%@, table=%@, property=%@", [modelClass dbName], [modelClass tableName], property);
            }
        }
    }
    if ([value isKindOfClass:[NSNull class]]) {
        value = nil;
    }
    
    if (propertyClass) {
        id cache = [_cacheDelegate objectOfClass:propertyClass id:value];
        if (!cache) {
            cache = [[(Class)propertyClass alloc] init];
            [cache setValue:value forKey:[propertyClass primaryKey]];
            [cache setValue:@YES forKey:@"fault"];
            [_cacheDelegate cacheObject:cache];
        }
        value = cache;
    }
    if (value) {
        [object setValue:value forKey:property];
    }
}

多线程高并发

多线程同步FMDB已经给我们提供了FMDatabaseQueue,我们可以进一步封装为同步和异步 。

- (void)asyncInDatabase:(void (^)(FMDatabase *db))block {
    FMDatabaseQueue *currentSyncQueue = (__bridge id)dispatch_get_specific(kDatabaseQueueSpecificKey);
    
    FMDBRetain(self);
    
    dispatch_block_t task = ^() {
        
        FMDatabase *db = [self database];
        block(db);
        
        if ([db hasOpenResultSets]) {
            NSLog(@"Warning: there is at least one open result set around after performing [FMDatabaseQueue asyncInDatabase:]");
            
#ifdef DEBUG
            NSSet *openSetCopy = FMDBReturnAutoreleased([[db valueForKey:@"_openResultSets"] copy]);
            for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) {
                FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue];
                NSLog(@"query: '%@'", [rs query]);
            }
#endif
        }
    };
    
    if (currentSyncQueue == self) {
        task();
    } else {
        dispatch_async(_queue, task);
    }
    
    FMDBRelease(self);
}

- (void)syncInDatabase:(void (^)(FMDatabase *db))block {
    FMDatabaseQueue *currentSyncQueue = (__bridge id)dispatch_get_specific(kDatabaseQueueSpecificKey);
    
    FMDBRetain(self);
    
    dispatch_block_t task = ^() {
        
        FMDatabase *db = [self database];
        block(db);
        
        if ([db hasOpenResultSets]) {
            NSLog(@"Warning: there is at least one open result set around after performing [FMDatabaseQueue syncInDatabase:]");
            
#ifdef DEBUG
            NSSet *openSetCopy = FMDBReturnAutoreleased([[db valueForKey:@"_openResultSets"] copy]);
            for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) {
                FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue];
                NSLog(@"query: '%@'", [rs query]);
            }
#endif
        }
    };
    
    if (currentSyncQueue == self) {
        task();
    } else {
        dispatch_sync(_queue, task);
    }
    
    FMDBRelease(self);
}

FMDatabaseQueue已经帮你解决了线程同步死锁问题,并且并行队列,可以高并发。微信读书的开发团体之前也说过暂时并没有遇到队列瓶颈,相信FMDatabaseQueue还是值得信赖的。
dispatch_sync(queue,task) 会阻塞当前线程, 直到queue完成了你给的task。

缓存

多级缓存:我们应该在数据表(model),数据库信息,dbQueue,等建立多级缓存。model用字典缓存,其他可以用dispatch_get_specific或者运行时objc_setAssociatedObject关联。
当然,缓存必须是可控的。有一个全局控制开关和清除机制,我们查询时,如果model有缓存就取缓存,没有就读DB并添加缓存。并且在更新表数据或者删除时,更新缓存。

注意⚠️ 默认属性都是readonly,因为每一个数据表都会有一个缓存。如果你需要改变model的属性值,你必须加同步锁🔒。或者像下面这样:

@interface Employee : GYModelObject
@property (atomic, assign) NSInteger employeeId;
@property (atomic, strong) NSString *name;
@property (atomic, strong) NSDate *dateOfBirth;
@property (atomic, strong) Department *department;
@end

Relationship & Faulting

像前面的Employee类,Department类是它的一个属性,这叫做Relationship(关联)。需要在.m文件中动态实现

@dynamic department;
//use
[employee save];
[employee.department save];

当你查询Employee时,Department属性仅仅是用Department表的主键当占位符。当你employee.department.xx访问department的属性时,会自动动态的加载department的信息,这叫做Faulting。减少您的应用程序使用的内存数量,提高查询速度。

有兴趣的可以研究腾讯前一阵开源的微信数据库WCDB,或者等我下一次分享。

上一篇下一篇

猜你喜欢

热点阅读