LKDBHelper.h 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. //
  2. // LKDBHelper.h
  3. // LJH
  4. //
  5. // Created by LJH on 12-12-6.
  6. // Copyright (c) 2012年 LJH. All rights reserved.
  7. //
  8. #import "LKDB+Mapping.h"
  9. #import "LKDBUtils.h"
  10. #import "NSObject+LKDBHelper.h"
  11. #import "NSObject+LKModel.h"
  12. #import <fmdb/FMDB.h>
  13. #import <Foundation/Foundation.h>
  14. NS_ASSUME_NONNULL_BEGIN
  15. @interface LKDBHelper : NSObject
  16. /**
  17. * @brief Log error message, Default: NO
  18. */
  19. + (void)setLogError:(BOOL)logError;
  20. /**
  21. * @brief null is '' , Default: NO
  22. */
  23. + (void)setNullToEmpty:(BOOL)empty;
  24. /**
  25. * @brief filepath the use of : "documents/db/" + fileName + ".db"
  26. * add to global cache with instance created
  27. * refer: FMDatabase.h + (instancetype)databaseWithPath:(NSString *)inPath;
  28. */
  29. - (instancetype)initWithDBName:(NSString *)dbname;
  30. - (void)setDBName:(NSString *)fileName;
  31. /**
  32. * @brief path of database file
  33. * refer: FMDatabase.h + (instancetype)databaseWithPath:(NSString *)inPath;
  34. */
  35. - (instancetype)initWithDBPath:(NSString *)filePath;
  36. - (void)setDBPath:(NSString *)filePath;
  37. /**
  38. * @brief closing a database connection and remove instance for global cache
  39. */
  40. - (void)closeDB;
  41. /**
  42. * @brief 当数据库无操作 多少秒后 自动关闭数据库连接, 区间 [0 ~ int_max] 默认:15秒,0:不自动关闭
  43. */
  44. - (void)setAutoCloseDBTime:(NSInteger)time;
  45. /**
  46. * @brief 当数据库10秒未操作时,自动压缩数据库空间,3天只会执行一次
  47. * 如果需要比较及时,自行执行 vacuum 命令
  48. */
  49. @property (nonatomic, assign) BOOL enableAutoVacuum;
  50. /**
  51. * @brief current encryption key.
  52. */
  53. @property (nullable, nonatomic, copy, readonly) NSString *encryptionKey;
  54. /**
  55. * @brief Set encryption key
  56. refer: FMDatabase.h - (BOOL)setKey:(NSString *)key;
  57. * invoking after the `LKDBHelper initialize` in YourModelClass.m `getUsingLKDBHelper` function
  58. */
  59. - (BOOL)setKey:(NSString *)key;
  60. /// Reset encryption key
  61. - (BOOL)rekey:(NSString *)key;
  62. /**
  63. * @brief execute database operations synchronously,not afraid of recursive deadlock
  64. 同步执行数据库操作 可递归调用
  65. */
  66. - (void)executeDB:(void (^)(FMDatabase *db))block;
  67. - (BOOL)executeSQL:(NSString *)sql arguments:(nullable NSArray *)args;
  68. - (nullable NSString *)executeScalarWithSQL:(NSString *)sql arguments:(nullable NSArray *)args;
  69. /**
  70. * @brief execute database operations synchronously in a transaction
  71. block return the YES commit transaction returns the NO rollback transaction
  72. 同步执行数据库操作 在事务内部
  73. block 返回 YES commit 事务 返回 NO rollback 事务
  74. */
  75. - (void)executeForTransaction:(BOOL (^)(LKDBHelper *helper))block;
  76. @end
  77. @interface LKDBHelper (DatabaseManager)
  78. ///get table has created
  79. - (BOOL)getTableCreatedWithClass:(Class)model;
  80. - (BOOL)getTableCreatedWithTableName:(NSString *)tableName;
  81. ///drop all table
  82. - (void)dropAllTable;
  83. ///drop table with entity class
  84. - (BOOL)dropTableWithClass:(Class)modelClass;
  85. - (BOOL)dropTableWithTableName:(NSString *)tableName;
  86. @end
  87. @interface LKDBHelper (DatabaseExecute)
  88. /**
  89. * @brief The number of rows query table
  90. *
  91. * @param modelClass entity class
  92. * @param where can use NSString or NSDictionary or nil
  93. *
  94. * @return rows number
  95. */
  96. - (NSInteger)rowCount:(Class)modelClass where:(nullable id)where;
  97. - (void)rowCount:(Class)modelClass where:(nullable id)where callback:(void (^)(NSInteger rowCount))callback;
  98. - (NSInteger)rowCountWithTableName:(NSString *)tableName where:(nullable id)where;
  99. /**
  100. * @brief query table
  101. *
  102. * @param params query condition
  103. */
  104. - (nullable NSMutableArray *)searchWithParams:(LKDBQueryParams *)params;
  105. /**
  106. * @brief query table
  107. *
  108. * @param modelClass entity class
  109. * @param where can use NSString or NSDictionary or nil
  110. * @param orderBy The Sort: Ascending "name asc",Descending "name desc"
  111. For example: @"rowid desc"x or @"rowid asc"
  112. * @param offset Skip how many rows
  113. * @param count Limit the number
  114. *
  115. * @return query finished result is an array(model instance collection)
  116. */
  117. - (nullable NSMutableArray *)search:(Class)modelClass
  118. where:(nullable id)where
  119. orderBy:(nullable NSString *)orderBy
  120. offset:(NSInteger)offset
  121. count:(NSInteger)count;
  122. /**
  123. * query sql, query finished result is an array(model instance collection)
  124. * you can use the "@t" replace Model TableName
  125. * query sql use lowercase string
  126. * 查询的sql语句 请使用小写 ,否则会不能自动获取 rowid
  127. * example:
  128. NSMutableArray *array = [[LKDBHelper getUsingLKDBHelper] searchWithSQL:@"select * from @t where blah blah.." toClass:[ModelClass class]];
  129. *
  130. */
  131. - (nullable NSMutableArray *)searchWithSQL:(NSString *)sql toClass:(nullable Class)modelClass;
  132. /**
  133. * @brief don't do any operations of the sql
  134. */
  135. - (nullable NSMutableArray *)searchWithRAWSQL:(NSString *)sql toClass:(nullable Class)modelClass;
  136. /**
  137. * query sql, query finished result is an array(model instance collection)
  138. * you can use the "@t" replace Model TableName and replace all ? placeholders with the va_list
  139. * example:
  140. NSMutableArray *array = [[LKDBHelper getUsingLKDBHelper] searc:[ModelClass class] withSQL:@"select rowid from name_table where name = ?", @"Swift"];
  141. *
  142. */
  143. - (nullable NSMutableArray *)search:(Class)modelClass withSQL:(NSString *)sql, ...;
  144. /**
  145. columns may NSArray or NSString if query column count == 1 return single column string array
  146. other return models entity array
  147. */
  148. - (nullable NSMutableArray *)search:(Class)modelClass
  149. column:(nullable id)columns
  150. where:(nullable id)where
  151. orderBy:(nullable NSString *)orderBy
  152. offset:(NSInteger)offset
  153. count:(NSInteger)count;
  154. /**
  155. * @brief async search
  156. */
  157. - (void)search:(Class)modelClass
  158. where:(nullable id)where
  159. orderBy:(nullable NSString *)orderBy
  160. offset:(NSInteger)offset
  161. count:(NSInteger)count
  162. callback:(void (^)(NSMutableArray *_Nullable array))block;
  163. ///return first model or nil
  164. - (nullable id)searchSingle:(Class)modelClass where:(nullable id)where orderBy:(nullable NSString *)orderBy;
  165. /**
  166. * @brief insert table
  167. *
  168. * @param model you want to insert the entity
  169. *
  170. * @return the inserted was successful
  171. */
  172. - (BOOL)insertToDB:(NSObject *)model;
  173. - (void)insertToDB:(NSObject *)model callback:(void (^)(BOOL result))block;
  174. /**
  175. * @brief insert when the entity primary key does not exist
  176. *
  177. * @param model you want to insert the entity
  178. *
  179. * @return the inserted was successful
  180. */
  181. - (BOOL)insertWhenNotExists:(NSObject *)model;
  182. - (void)insertWhenNotExists:(NSObject *)model callback:(void (^)(BOOL result))block;
  183. /**
  184. * @brief update table
  185. *
  186. * @param model you want to update the entity
  187. * @param where can use NSString or NSDictionary or nil
  188. when "where" is nil : update the value based on rowid column or primary key column
  189. *
  190. * @return the updated was successful
  191. */
  192. - (BOOL)updateToDB:(NSObject *)model where:(nullable id)where;
  193. - (void)updateToDB:(NSObject *)model where:(nullable id)where callback:(void (^)(BOOL result))block;
  194. - (BOOL)updateToDB:(Class)modelClass set:(NSString *)sets where:(nullable id)where;
  195. - (BOOL)updateToDBWithTableName:(NSString *)tableName set:(NSString *)sets where:(nullable id)where;
  196. /**
  197. * @brief delete table
  198. *
  199. * @param model you want to delete entity
  200. when entity property "rowid" == 0 based on the primary key to delete
  201. *
  202. * @return the deleted was successful
  203. */
  204. - (BOOL)deleteToDB:(NSObject *)model;
  205. - (void)deleteToDB:(NSObject *)model callback:(void (^)(BOOL result))block;
  206. /**
  207. * @brief delete table with "where" constraint
  208. *
  209. * @param modelClass entity class
  210. * @param where can use NSString or NSDictionary, can not is nil
  211. *
  212. * @return the deleted was successful
  213. */
  214. - (BOOL)deleteWithClass:(Class)modelClass where:(nullable id)where;
  215. - (void)deleteWithClass:(Class)modelClass where:(nullable id)where callback:(void (^)(BOOL result))block;
  216. - (BOOL)deleteWithTableName:(NSString *)tableName where:(nullable id)where;
  217. /**
  218. * @brief entity exists?
  219. * for primary key column
  220. (if rowid > 0 would certainly exist so we do not rowid judgment)
  221. * @param model entity
  222. *
  223. * @return YES: entity presence , NO: entity not exist
  224. */
  225. - (BOOL)isExistsModel:(NSObject *)model;
  226. - (BOOL)isExistsClass:(Class)modelClass where:(nullable id)where;
  227. - (BOOL)isExistsWithTableName:(NSString *)tableName where:(nullable id)where;
  228. /**
  229. * @brief Clear data based on the entity class
  230. *
  231. * @param modelClass entity class
  232. */
  233. + (void)clearTableData:(Class)modelClass;
  234. /**
  235. * @brief Clear Unused Data File
  236. if you property has UIImage or NSData, will save their data in the (documents dir)
  237. *
  238. * @param modelClass entity class
  239. * @param columns UIImage or NSData Column Name
  240. */
  241. + (void)clearNoneImage:(Class)modelClass columns:(NSArray<NSString *> *)columns;
  242. + (void)clearNoneData:(Class)modelClass columns:(NSArray<NSString *> *)columns;
  243. @end
  244. @interface LKDBHelper (Deprecated_Nonfunctional)
  245. /// you can use [LKDBHelper getUsingLKDBHelper]
  246. #pragma mark - deprecated
  247. + (LKDBHelper *)sharedDBHelper __deprecated_msg("Method deprecated. Use `[Model getUsingLKDBHelper]`");
  248. - (BOOL)createTableWithModelClass:(Class)modelClass __deprecated_msg("Now you can not call it. Will automatically determine whether you need to create");
  249. - (void)setEncryptionKey:(NSString *)encryptionKey __deprecated_msg("Method deprecated. Use `setKey: OR resetKey:` invoking after the `LKDBHelper initialize` in YourModelClass.m `getUsingLKDBHelper` function");
  250. #pragma mark -
  251. @end
  252. NS_ASSUME_NONNULL_END