DatabaseUtil.m 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. //
  2. // DatabaseUtil.m
  3. // YYDebugDatabase
  4. //
  5. // Created by wentian on 17/8/11.
  6. // Copyright © 2017年 wentian. All rights reserved.
  7. //
  8. #import "DatabaseUtil.h"
  9. #import <sqlite3.h>
  10. #ifdef COCOAPODS
  11. #import "FMDB.h"
  12. #else
  13. #import <FMDB/FMDB.h>
  14. #endif
  15. @interface DatabaseUtil ()
  16. @property(nonatomic) sqlite3 *db;
  17. @property(nonatomic, ) NSString *dbPath;
  18. @property(nonatomic, copy) NSString *dbName;
  19. @property(nonatomic, strong) FMDatabase *fmdb;
  20. @end
  21. @implementation DatabaseUtil
  22. + (instancetype)shared {
  23. static dispatch_once_t onceToken;
  24. static DatabaseUtil *dbUtil;
  25. dispatch_once(&onceToken, ^{
  26. dbUtil = [[self alloc] init];
  27. });
  28. return dbUtil;
  29. }
  30. - (BOOL)openDatabase:(NSString*)dbPath {
  31. if (self.dbPath && _db && ![dbPath isEqualToString:self.dbPath]){
  32. [self closeDatabase];
  33. }
  34. _dbPath = dbPath;
  35. _dbName = [_dbPath lastPathComponent];
  36. NSString *dbDir = [_dbPath stringByDeletingLastPathComponent];
  37. if (![[NSFileManager defaultManager] fileExistsAtPath:dbDir]) {
  38. return NO;
  39. }
  40. self.fmdb = [FMDatabase databaseWithPath:dbPath];
  41. if (![self.fmdb open]) {
  42. NSLog(@"Could not open db %@.", dbPath);
  43. return NO;
  44. }
  45. return YES;
  46. }
  47. - (BOOL)closeDatabase {
  48. if (self.fmdb != nil){
  49. [self.fmdb close];
  50. }
  51. return YES;
  52. }
  53. - (NSArray*)allTables {
  54. NSString *sql = @"SELECT tbl_name FROM sqlite_master WHERE type = 'table'";
  55. FMResultSet *rs = [self.fmdb executeQuery:sql];
  56. NSMutableArray *tables = @[].mutableCopy;
  57. while ([rs next]) {
  58. [tables safe_addObject:[rs stringForColumn:@"tbl_name"]];
  59. }
  60. return tables;
  61. }
  62. - (NSArray*)tableInfo:(NSString*)tableName {
  63. FMResultSet *rs = [self.fmdb getTableSchema:tableName];
  64. NSMutableArray *infos = @[].mutableCopy;
  65. while ([rs next]) {
  66. [infos safe_addObject:rs.resultDictionary?:[NSNull null]];
  67. }
  68. return infos;
  69. }
  70. - (NSDictionary*)rowsInTable:(NSString*)tableName {
  71. NSMutableDictionary *tableData = [NSMutableDictionary dictionary];
  72. [tableData safe_setObject:@(1) forKey:@"isSelectQuery"];
  73. [tableData safe_setObject:@(1) forKey:@"isSuccessful"];
  74. //标题
  75. FMResultSet *infors = [self.fmdb getTableSchema:tableName];
  76. NSMutableArray *tableInfoResult = [NSMutableArray array];
  77. NSMutableArray *columnKeys = [NSMutableArray arrayWithCapacity:10];
  78. while ([infors next]) {
  79. NSMutableDictionary *info = [NSMutableDictionary dictionary];
  80. [info safe_setObject:@([infors boolForColumn:@"pk"]) forKey:@"isPrimary"];
  81. // [info safe_setObject:[NSString stringWithFormat:@"%@[%@]", [infors stringForColumn:@"name"]?:@"", [infors stringForColumn:@"type"]] forKey:@"titleDisplay"];
  82. [info safe_setObject:[NSString stringWithFormat:@"%@", [infors stringForColumn:@"name"]?:@""] forKey:@"title"];
  83. [info safe_setObject:[infors stringForColumn:@"type"] forKey:@"dataType"];
  84. [tableInfoResult safe_addObject:info];
  85. [columnKeys addObject:[infors stringForColumn:@"name"]?:@""];
  86. }
  87. [tableData safe_setObject:tableInfoResult forKey:@"tableInfos"];
  88. BOOL isEditable = tableName != nil && [tableData objectForKey:@"tableInfos"] != nil;
  89. [tableData safe_setObject:@(isEditable) forKey:@"isEditable"];
  90. //数据
  91. NSString *sql = [NSString stringWithFormat:@"select * from %@",tableName];
  92. FMResultSet *rs = [self.fmdb executeQuery:sql];
  93. NSMutableArray *rows = @[].mutableCopy;
  94. while ([rs next]) {
  95. NSMutableArray *row = @[].mutableCopy;
  96. for ( int i = 0; i < tableInfoResult.count; i++) {
  97. NSMutableDictionary *columnData = [NSMutableDictionary dictionaryWithCapacity:10];
  98. NSString *columName = [columnKeys objectAtIndex:i];
  99. NSString *type = [[tableInfoResult objectAtIndex:i] objectForKey:@"dataType"];
  100. if ([[type lowercaseString] isEqualToString:@"integer"]) {
  101. [columnData safe_setObject:@"integer" forKey:@"dataType"];
  102. }else if ([[type lowercaseString] isEqualToString:@"real"]) {
  103. [columnData safe_setObject:@"float" forKey:@"dataType"];
  104. }else if ([[type lowercaseString] isEqualToString:@"text"]) {
  105. [columnData safe_setObject:@"text" forKey:@"dataType"];
  106. }else if ([[type lowercaseString] isEqualToString:@"blob"]) {
  107. [columnData safe_setObject:@"blob" forKey:@"dataType"];
  108. }else if ([[type lowercaseString] isEqualToString:@"null"]) {
  109. [columnData safe_setObject:@"null" forKey:@"dataType"];
  110. }else {
  111. [columnData safe_setObject:@"text" forKey:@"dataType"];
  112. }
  113. if ([[type lowercaseString] isEqualToString:@"blob"]) {
  114. [columnData safe_setObject:@"blob" forKey:@"value"];
  115. }else if ([[type lowercaseString] isEqualToString:@"guid"]){
  116. id data = [rs respondsToSelector:@selector(objectForColumn:)] ? [rs performSelector:@selector(objectForColumn:) withObject:columName] : [rs performSelector:@selector(objectForColumnName:) withObject:columName];
  117. const unsigned char *bytes = (const unsigned char *)[data bytes];
  118. NSMutableString *hex = [NSMutableString new];
  119. for (NSInteger i = 0; i < [data length]; i++) {
  120. [hex appendFormat:@"%02x", bytes[i]];
  121. }
  122. [columnData safe_setObject:hex?:[NSNull null] forKey:@"value"];
  123. }else {
  124. id obj = [rs respondsToSelector:@selector(objectForColumn:)] ? [rs performSelector:@selector(objectForColumn:) withObject:columName] : [rs performSelector:@selector(objectForColumnName:) withObject:columName];
  125. [columnData safe_setObject:obj?:[NSNull null] forKey:@"value"];
  126. }
  127. [row safe_addObject:columnData];
  128. }
  129. [rows safe_addObject:row];
  130. }
  131. [tableData safe_setObject:rows forKey:@"rows"];
  132. return tableData;
  133. }
  134. - (BOOL)updateRecordInDatabase:(NSString *)database tableName:(NSString *)tableName data:(NSDictionary *)data condition:(NSDictionary *)condition {
  135. NSMutableArray *fields = @[].mutableCopy;
  136. for (NSString *key in data.allKeys) {
  137. [fields safe_addObject:[NSString stringWithFormat:@"%@ = '%@'", key, [data objectForKey:key]]];
  138. }
  139. NSString *values = [fields componentsJoinedByString:@","];
  140. NSString *where = @"1";
  141. if ([condition isKindOfClass:[NSDictionary class]] && condition.count > 0) {
  142. NSMutableArray *conArray = @[].mutableCopy;
  143. for (NSString *key in condition.allKeys) {
  144. [conArray safe_addObject:[NSString stringWithFormat:@"%@ = '%@'", key, [condition objectForKey:key]]];
  145. }
  146. where = [conArray componentsJoinedByString:@" AND "];
  147. }
  148. NSString *sqlString = [NSString stringWithFormat:@"UPDATE \"%@\" SET %@ WHERE %@",tableName,values,where];
  149. return [self.fmdb executeQuery:sqlString];
  150. }
  151. - (BOOL)deleteRecordInDatabase:(NSString *)database tableName:(NSString *)tableName condition:(NSDictionary *)condition limit:(NSString *)limit {
  152. NSString *where = @"1";
  153. NSString *limitString =@"";
  154. if (limit.length > 0) {
  155. limitString = [NSString stringWithFormat:@"LIMIT %@",limit];
  156. }
  157. if ([condition isKindOfClass:[NSDictionary class]] && condition.count > 0) {
  158. NSMutableArray *conArray = @[].mutableCopy;
  159. for (NSString *key in condition.allKeys) {
  160. [conArray safe_addObject:[NSString stringWithFormat:@"%@ = '%@'", key, [condition objectForKey:key]]];
  161. }
  162. where = [conArray componentsJoinedByString:@" AND "];
  163. }
  164. NSString *sqlString =[NSString stringWithFormat:@"DELETE FROM \"%@\" WHERE %@ %@",tableName,where,limitString];
  165. NSLog(@"delete %@",sqlString);
  166. return [self.fmdb executeUpdate:sqlString];
  167. }
  168. - (NSDictionary*)executeQueryInDatabase:(NSString*)database tableName:(NSString*)tableName operator:(NSString*)operator query:(NSString*)query {
  169. if ([operator isEqualToString:@"select"]) {
  170. NSMutableDictionary *tableData = [NSMutableDictionary dictionary];
  171. [tableData safe_setObject:@(1) forKey:@"isSelectQuery"];
  172. [tableData safe_setObject:@(1) forKey:@"isSuccessful"];
  173. //数据
  174. NSString *sql = query;
  175. FMResultSet *rs = [self.fmdb executeQuery:sql];
  176. NSMutableArray *rows = @[].mutableCopy;
  177. //标题
  178. FMResultSet *infors = [self.fmdb getTableSchema:tableName];
  179. NSMutableArray *tableInfoResult = [NSMutableArray array];
  180. while ([infors next]) {
  181. NSMutableDictionary *info = [NSMutableDictionary dictionary];
  182. NSString *columnName = [infors stringForColumn:@"name"];
  183. if ([rs.columnNameToIndexMap.allKeys containsObject:columnName]) {
  184. [info safe_setObject:@([infors boolForColumn:@"pk"]) forKey:@"isPrimary"];
  185. [info safe_setObject:[infors stringForColumn:@"name"]?:@"" forKey:@"title"];
  186. [info safe_setObject:[infors stringForColumn:@"type"] forKey:@"dataType"];
  187. [tableInfoResult safe_addObject:info];
  188. }
  189. }
  190. [tableData safe_setObject:tableInfoResult forKey:@"tableInfos"];
  191. BOOL isEditable = tableName != nil && [tableData objectForKey:@"tableInfos"] != nil;
  192. [tableData safe_setObject:@(isEditable) forKey:@"isEditable"];
  193. while ([rs next]) {
  194. NSMutableArray *row = @[].mutableCopy;
  195. for ( int i = 0; i < tableInfoResult.count; i++) {
  196. NSMutableDictionary *columnData = [NSMutableDictionary dictionaryWithCapacity:10];
  197. NSString *columName = [[tableInfoResult objectAtIndex:i] objectForKey:@"title"];
  198. NSString *type = [[tableInfoResult objectAtIndex:i] objectForKey:@"dataType"];
  199. if ([[type lowercaseString] isEqualToString:@"integer"]) {
  200. [columnData safe_setObject:@"integer" forKey:@"dataType"];
  201. [columnData safe_setObject:@([rs intForColumn:columName]) forKey:@"value"];
  202. }else if ([[type lowercaseString] isEqualToString:@"real"]) {
  203. [columnData safe_setObject:@"float" forKey:@"dataType"];
  204. [columnData safe_setObject:@([rs doubleForColumn:columName]) forKey:@"value"];
  205. }else if ([[type lowercaseString] isEqualToString:@"text"]) {
  206. [columnData safe_setObject:@"text" forKey:@"dataType"];
  207. [columnData safe_setObject:[rs stringForColumn:columName]?:@"" forKey:@"value"];
  208. }else if ([[type lowercaseString] isEqualToString:@"blob"]) {
  209. [columnData safe_setObject:@"blob" forKey:@"dataType"];
  210. [columnData safe_setObject:@"blob" forKey:@"value"];
  211. }else if ([[type lowercaseString] isEqualToString:@"null"]) {
  212. [columnData safe_setObject:@"null" forKey:@"dataType"];
  213. [columnData safe_setObject:[NSNull null] forKey:@"value"];
  214. }else {
  215. [columnData safe_setObject:@"text" forKey:@"dataType"];
  216. [columnData safe_setObject:[rs stringForColumn:columName] forKey:@"value"];
  217. }
  218. [row safe_addObject:columnData];
  219. }
  220. [rows safe_addObject:row];
  221. }
  222. [tableData safe_setObject:rows forKey:@"rows"];
  223. return tableData;
  224. }else {
  225. BOOL result = [self.fmdb executeUpdate:query];
  226. NSDictionary *respone;
  227. if (result) {
  228. respone = @{@"isSelectQuery":@(true),@"isSuccessful":@(true)};
  229. }else{
  230. respone = @{@"isSelectQuery":@(true),@"isSuccessful":@(false),@"errorMessage":@"Database Opration faild!"};
  231. }
  232. return respone;
  233. }
  234. }
  235. - (NSDictionary*)userDefaultData {
  236. NSMutableDictionary *tableData = [NSMutableDictionary dictionary];
  237. [tableData safe_setObject:@(1) forKey:@"isSelectQuery"];
  238. [tableData safe_setObject:@(1) forKey:@"isSuccessful"];
  239. NSMutableArray *tableInfoResult = [NSMutableArray array];
  240. [tableInfoResult safe_addObject:@{@"title": @"key", @"isPrimary" : @(1), @"dataType" : @"text"}];
  241. [tableInfoResult safe_addObject:@{@"title": @"value", @"isPrimary" : @(0), @"dataType" : @"text"}];
  242. [tableData safe_setObject:tableInfoResult forKey:@"tableInfos"];
  243. [tableData safe_setObject:@(NO) forKey:@"isEditable"];
  244. NSMutableArray *rows = @[].mutableCopy;
  245. NSDictionary *userData = [[NSUserDefaults standardUserDefaults]dictionaryRepresentation];
  246. for (NSString *key in userData.allKeys) {
  247. NSMutableArray *row = @[].mutableCopy;
  248. [row safe_addObject:@{@"dataType" : @"text", @"value" : key?key:@""}];
  249. id value = [userData objectForKey:key];
  250. if ([value isKindOfClass:[NSString class]] || [value isKindOfClass:[NSNumber class]]) {
  251. [row safe_addObject:@{@"dataType" : @"text", @"value" : yy_dicGetStringSafe(userData, key)}];
  252. }else {
  253. [row safe_addObject:@{@"dataType" : @"text", @"value" : [value description]?:@""}];
  254. }
  255. [rows addObject:row];
  256. }
  257. [tableData safe_setObject:rows forKey:@"rows"];
  258. return tableData;
  259. }
  260. - (NSDictionary*)getAppInfoData {
  261. NSMutableDictionary *tableData = [NSMutableDictionary dictionary];
  262. [tableData safe_setObject:@(1) forKey:@"isSelectQuery"];
  263. [tableData safe_setObject:@(1) forKey:@"isSuccessful"];
  264. NSMutableArray *tableInfoResult = [NSMutableArray array];
  265. [tableInfoResult safe_addObject:@{@"title": @"property name", @"isPrimary" : @(1), @"dataType" : @"text"}];
  266. [tableInfoResult safe_addObject:@{@"title": @"property value", @"isPrimary" : @(0), @"dataType" : @"text"}];
  267. [tableData safe_setObject:tableInfoResult forKey:@"tableInfos"];
  268. [tableData safe_setObject:@(NO) forKey:@"isEditable"];
  269. NSMutableArray *rows = @[].mutableCopy;
  270. NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
  271. //app name
  272. NSString *displayName = yy_dicGetStringSafe(infoDic, @"CFBundleDisplayName");
  273. NSMutableArray *displayRow = @[].mutableCopy;
  274. [displayRow safe_addObject:@{@"dataType": @"text", @"value": @"Display Name"}];
  275. [displayRow safe_addObject:@{@"dataType": @"text", @"value": displayName}];
  276. [rows safe_addObject:displayRow];
  277. //app bundle identifier
  278. NSString *bundleIdentifer = yy_dicGetStringSafe(infoDic, kCFBundleIdentifierKey);
  279. NSMutableArray *bundleRow = @[].mutableCopy;
  280. [bundleRow safe_addObject:@{@"dataType": @"text", @"value": @"Bundle Identifer"}];
  281. [bundleRow safe_addObject:@{@"dataType": @"text", @"value": bundleIdentifer}];
  282. [rows safe_addObject:bundleRow];
  283. //app version
  284. NSString *version = yy_dicGetStringSafe(infoDic, @"CFBundleShortVersionString");
  285. NSMutableArray *versionRow = @[].mutableCopy;
  286. [versionRow safe_addObject:@{@"dataType": @"text", @"value": @"Version"}];
  287. [versionRow safe_addObject:@{@"dataType": @"text", @"value": version}];
  288. [rows safe_addObject:versionRow];
  289. //app build number
  290. NSString *build = yy_dicGetStringSafe(infoDic, kCFBundleVersionKey);
  291. NSMutableArray *buildRow = @[].mutableCopy;
  292. [buildRow safe_addObject:@{@"dataType": @"text", @"value": @"Build"}];
  293. [buildRow safe_addObject:@{@"dataType": @"text", @"value": build}];
  294. [rows safe_addObject:buildRow];
  295. //document path
  296. NSArray *pathSearch = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  297. NSString *documentsPath = [pathSearch objectAtIndex:0];
  298. NSMutableArray *documentRow = @[].mutableCopy;
  299. [documentRow safe_addObject:@{@"dataType": @"text", @"value": @"Documents"}];
  300. [documentRow safe_addObject:@{@"dataType": @"text", @"value": documentsPath?documentsPath:@""}];
  301. [rows safe_addObject:documentRow];
  302. //cache path
  303. NSArray *pathSearchCache = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  304. NSString *cachePath = [pathSearchCache objectAtIndex:0];
  305. NSMutableArray *cacheRow = @[].mutableCopy;
  306. [cacheRow safe_addObject:@{@"dataType": @"text", @"value": @"Cache"}];
  307. [cacheRow safe_addObject:@{@"dataType": @"text", @"value": cachePath?cachePath:@""}];
  308. [rows safe_addObject:cacheRow];
  309. [tableData safe_setObject:rows forKey:@"rows"];
  310. return tableData;
  311. }
  312. @end