-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSQLiteLibrary.m
555 lines (477 loc) · 15.3 KB
/
SQLiteLibrary.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
/*
* Copyright 2012 Dmitri Fedortchenko
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "SQLiteLibrary.h"
#define ODBsprintf(format, ...) [NSString stringWithFormat:format, ## __VA_ARGS__]
#define make_nil_if_null(__string__) (__string__==nil||[__string__ isEqualToString:@"(null)"])?nil:__string__
#ifdef __cplusplus
extern "C" {
#endif
NSString* escape_string(id value)
{
if ([value isKindOfClass:[NSString class]])
return ODBsprintf(@"\"%@\"",[value stringByReplacingOccurrencesOfString:@"\"" withString:@"\"\""]);
else
return value;
}
NSString* sqlite3_column_nsstring(sqlite3_stmt* statement, int column)
{
char* data = (char *)sqlite3_column_text(statement, column);
if (data)
{
return make_nil_if_null([NSString stringWithUTF8String:data]);
}
else
{
return nil;
}
}
#ifdef __cplusplus
}
#endif
@implementation SQLiteLibrary
{
NSString* dbFilePath_;
}
static SQLiteLibrary* _instance;
+ (void)initialize
{
[super initialize];
_instance = [[self alloc] init];
}
+ (SQLiteLibrary *)singleton
{
return _instance;
}
+ (void)setDatabaseFileInCache:(NSString *)dbFilename
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *directory = paths[0];
NSString* appFile = [directory stringByAppendingPathComponent:dbFilename];
[self setDatabaseFile:appFile];
}
+ (void)setDatabaseFileInDocuments:(NSString *)dbFilename
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *directory = paths[0];
NSString* appFile = [directory stringByAppendingPathComponent:dbFilename];
[self setDatabaseFile:appFile];
}
+ (void)setDatabaseFile:(NSString *)dbFilePath
{
SQLiteLibrary * me = [self singleton];
@synchronized (self)
{
#if !__has_feature(objc_arc)
[me->dbFilePath_ release];
#endif
me->dbFilePath_ = nil;
me->dbFilePath_ = [dbFilePath copy];
}
}
- (id)init
{
self = [super init];
if (self)
{
database = nil;
lock = [[NSRecursiveLock alloc]init];
}
return self;
}
#if !__has_feature(objc_arc)
- (void)dealloc
{
[lock release];
[super dealloc];
}
#endif
+ (BOOL)begin
{
return [[self singleton] begin];
}
+ (BOOL)verifyDatabaseFile
{
return [[self singleton]verifyDatabaseFile];
}
- (BOOL)verifyDatabaseFile
{
NSString*dbPath = dbFilePath_;
NSAssert(dbPath!=nil, @"Database file not set, perhaps you need to run `setDatabaseFileIn[Cache|Documents]:`");
#if DEBUG_LOG>=1
NSLog(@"Using sqlite database at path %@", dbPath);
#endif
NSAssert(database==nil, @"Attempted to start transaction while another is in progress.");
#if DEBUG_LOG>=2
NSLog(@"Begin db verification...");
#endif
if (![[NSFileManager defaultManager] isReadableFileAtPath:dbFilePath_])
{
#if DEBUG_LOG>=2
NSLog(@"DB File not found: %@", dbPath);
#endif
return NO;
}
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
sqlite3_exec(database, "PRAGMA quick_check;", NULL, NULL, NULL);
if (sqlite3_errcode(database) != SQLITE_DONE && sqlite3_errcode(database)>0)
{
#if DEBUG_LOG>=1
NSLog(@"!!!!!!> SQLITE ERROR ===============> %d - %@", sqlite3_errcode(database), [NSString stringWithCString:sqlite3_errmsg(database) encoding:NSUTF8StringEncoding]);
#endif
return NO;
}
return YES;
}
#if DEBUG_LOG>=1
NSLog(@"!!!!!!> SQLITE ERROR ===============> Failed to open SQLite database %@;", dbPath);
#endif
return NO;
}
- (BOOL)begin
{
[lock lock];
if (database!=nil)
{
[self commit];
[lock lock];
}
NSAssert(dbFilePath_!=nil, @"dbFilePath must be set!");
NSString*dbPath = dbFilePath_;
#if DEBUG_LOG>=2
NSLog(@"Using sqlite database at path %@", dbPath);
#endif
NSAssert([[NSFileManager defaultManager] isReadableFileAtPath:dbPath], ODBsprintf(@"Database file does not exist %@", dbPath));
NSAssert(database==nil, @"Attempted to start transaction while another is in progress.");
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
#if DEBUG_LOG>=2
NSLog(@"TRANSACTION BEGIN");
#endif
sqlite3_exec(database, "BEGIN;", NULL, NULL, NULL);
if (sqlite3_errcode(database) != SQLITE_DONE && sqlite3_errcode(database)>0)
{
#if DEBUG_LOG>=1
NSLog(@"!!!!!!> SQLITE ERROR ===============> %d - %@", sqlite3_errcode(database), [NSString stringWithCString:sqlite3_errmsg(database) encoding:NSUTF8StringEncoding]);
#endif
return NO;
}
return YES;
}
#if DEBUG_LOG>=1
NSLog(@"!!!!!!> SQLITE ERROR ===============> Failed to open SQLite database %@;", dbPath);
#endif
return NO;
}
+ (NSDictionary *)dictionaryForRowData:(sqlite3_stmt *)statement {
int columns = sqlite3_column_count(statement);
NSMutableDictionary *result = [[NSMutableDictionary alloc] initWithCapacity:(NSUInteger) columns];
for (int i = 0; i<columns; i++) {
const char *name = sqlite3_column_name(statement, i);
NSString *columnName = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
int type = sqlite3_column_type(statement, i);
switch (type) {
case SQLITE_INTEGER:
{
int value = sqlite3_column_int(statement, i);
result[columnName] = @(value);
break;
}
case SQLITE_FLOAT:
{
float value = (float)sqlite3_column_double(statement, i);
result[columnName] = @(value);
break;
}
case SQLITE_TEXT:
{
const char *value = (const char*)sqlite3_column_text(statement, i);
result[columnName] = [NSString stringWithCString:value encoding:NSUTF8StringEncoding];
break;
}
case SQLITE_BLOB:
break;
case SQLITE_NULL:
//[result setObject:[NSNull null] forKey:columnName];
break;
default:
{
const char *value = (const char *)sqlite3_column_text(statement, i);
result[columnName] = [NSString stringWithCString:value encoding:NSUTF8StringEncoding];
break;
}
} //end switch
}
#if __has_feature(objc_arc)
return result;
#else
return [result autorelease];
#endif
}
+ (BOOL)isId:(id)value columnName:(NSString*)columnName inTable:(NSString*)tableName
{
return [[self singleton] isId:value columnName:columnName inTable:tableName];
}
- (BOOL)isId:(id)value columnName:(NSString*)columnName inTable:(NSString*)tableName
{
NSString* query = ODBsprintf(@"SELECT count(%@) as count FROM %@ WHERE %@ = %@", columnName, tableName, columnName, escape_string(value));
NSArray *results = [SQLiteLibrary performQueryAndGetResultList:query];
return ([results count] && [results[0][@"count"]intValue]>0);
}
+ (NSArray *)performQueryAndGetResultList:(NSString *)query
{
return [[self singleton] performQueryAndGetResultList:query];
}
- (NSArray *)performQueryAndGetResultList:(NSString *)query
{
[lock lock];
BOOL shouldCommit = NO;
if (database == nil)
{
#if DEBUG_LOG>=2
NSLog(@"======> SQLITE INFO ===============> No transaction started, forcing autocommit");
#endif
shouldCommit=YES;
[self begin];
}
NSAssert(database!=nil, @"Must begin a transaction first.");
if (database == nil)
return nil;
#if DEBUG_LOG>=2
NSLog(@"Performing query:\n\t%@", query);
#endif
// Setup the SQL Statement and compile it for faster access
sqlite3_stmt *compiledStatement;
NSMutableArray* returnData = [NSMutableArray array];
if(sqlite3_prepare_v2(database, [query UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK)
{
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW)
{
[returnData addObject:[SQLiteLibrary dictionaryForRowData:compiledStatement]];
}
#if DEBUG_LOG>=2
if (sqlite3_errcode(database) != SQLITE_DONE && sqlite3_errcode(database)>0)
{
NSLog(@"!!!!!!> SQLITE ERROR ===============> %d - %@", sqlite3_errcode(database), [NSString stringWithCString:sqlite3_errmsg(database) encoding:NSUTF8StringEncoding]);
}
#endif
}
#if DEBUG_LOG>=1
else
{
NSLog(@"!!!!!!> SQLITE ERROR ===============> %d - %@", sqlite3_errcode(database), [NSString stringWithCString:sqlite3_errmsg(database) encoding:NSUTF8StringEncoding]);
}
#endif
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
if (shouldCommit)
[self commit];
[lock unlock];
return returnData;
}
- (int64_t)performQueryInTransaction:(NSString *)query block:(SQLiteBlock)block
{
[lock lock];
BOOL shouldCommit = NO;
if (database == nil)
{
#if DEBUG_LOG>=2
NSLog(@"======> SQLITE INFO ===============> No transaction started, forcing autocommit");
#endif
shouldCommit=YES;
[self begin];
}
NSAssert(database!=nil, @"Must begin a transaction first.");
if (database == nil)
return -1;
int returnValue = -1;
#if DEBUG_LOG>=2
NSLog(@"Performing query:\n\t%@", query);
#endif
// Setup the SQL Statement and compile it for faster access
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, [query UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
#if !__has_feature(objc_arc)
[block retain];
#endif
int resultCount = 0;
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
resultCount ++;
if (block!=nil)
block(compiledStatement);
}
#if DEBUG_LOG>=2
if (sqlite3_errcode(database) != SQLITE_DONE && sqlite3_errcode(database)>0)
{
NSLog(@"!!!!!!> SQLITE ERROR ===============> %d - %@", sqlite3_errcode(database), [NSString stringWithCString:sqlite3_errmsg(database) encoding:NSUTF8StringEncoding]);
}
#endif
if ([[query uppercaseString] hasPrefix:@"INSERT"])
returnValue = (int)sqlite3_last_insert_rowid(database);
else if ([[query uppercaseString] hasPrefix:@"SELECT"])
returnValue = resultCount;
else
returnValue = sqlite3_changes(database);
#if !__has_feature(objc_arc)
[block release];
#endif
}
#if DEBUG_LOG>=1
else
{
NSLog(@"!!!!!!> SQLITE ERROR ===============> %d - %@", sqlite3_errcode(database), [NSString stringWithCString:sqlite3_errmsg(database) encoding:NSUTF8StringEncoding]);
}
#endif
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
if (shouldCommit)
[self commit];
[lock unlock];
return returnValue;
}
+ (BOOL)commit
{
return [[self singleton] commit];
}
- (BOOL)commit
{
[lock lock];
if (database == nil)
{
[lock unlock];
return NO;
}
sqlite3_exec(database, "COMMIT;", NULL, NULL, NULL);
BOOL success = YES;
if (sqlite3_errcode(database) != SQLITE_DONE && sqlite3_errcode(database)>0)
{
#if DEBUG_LOG>=1
NSLog(@"!!!!!!> SQLITE ERROR ===============> %d - %@", sqlite3_errcode(database), [NSString stringWithCString:sqlite3_errmsg(database) encoding:NSUTF8StringEncoding]);
#endif
success=NO;
}
#if DEBUG_LOG>=2
NSLog(@"TRANSACTION COMMIT");
#endif
sqlite3_close(database);
database = nil;
[lock unlock];
[lock unlock];
return success;
}
+ (int64_t)performInsertQueryInTable:(NSString*)tableName data:(NSDictionary*)data
{
return [[self singleton] performInsertQueryInTable:tableName data:data];
}
- (int64_t)performInsertQueryInTable:(NSString*)tableName data:(NSDictionary*)data
{
return [self performInsertQueryInTable:tableName data:data allowReplace:NO];
}
+ (int64_t)performReplaceQueryInTable:(NSString*)tableName data:(NSDictionary*)data
{
return [[self singleton] performReplaceQueryInTable:tableName data:data];
}
- (int64_t)performReplaceQueryInTable:(NSString*)tableName data:(NSDictionary*)data
{
return [self performInsertQueryInTable:tableName data:data allowReplace:YES];
}
+ (int64_t)performUpdateQueryInTable:(NSString*)tableName data:(NSDictionary*)data idColumn:(NSString*)idColumn
{
return [[self singleton] performUpdateQueryInTable:tableName data:data idColumn:idColumn];
}
- (int64_t)performUpdateQueryInTable:(NSString*)tableName data:(NSDictionary*)data idColumn:(NSString*)idColumn
{
NSMutableArray* values = [NSMutableArray arrayWithCapacity:[data count]];
id idValue = nil;
for (NSString*columnKey in [data allKeys])
{
id value = data[columnKey];
id fixedValue = nil;
if ([value isKindOfClass:[NSString class]])
fixedValue = [escape_string(value) copy];
else if (value==[NSNull null])
fixedValue = [@"NULL" copy];
else
fixedValue = [value copy];
if ([columnKey isEqualToString:idColumn])
{
idValue = [fixedValue copy];
}
else
{
[values addObject:ODBsprintf(@"%@ = %@", columnKey, fixedValue)];
}
[fixedValue release];
}
NSString* queryString = ODBsprintf(
@"UPDATE %@ SET %@ WHERE %@ = %@",
tableName,
[values componentsJoinedByString:@","],
idColumn,
idValue
);
[idValue release];
return [self performQueryInTransaction:queryString block:nil];
}
- (int64_t)performInsertQueryInTable:(NSString*)tableName data:(NSDictionary*)data allowReplace:(BOOL)allowReplace
{
NSMutableDictionary * queryData = [NSMutableDictionary dictionaryWithCapacity:[data count]];
for (NSString* key in [data allKeys])
{
id value = data[key];
if ([value isKindOfClass:[NSString class]])
queryData[key] = escape_string(value);
else if (value==[NSNull null])
queryData[key] = @"NULL";
else
queryData[key] = value;
}
NSString* orReplace = @"";
if (allowReplace) orReplace = @"OR REPLACE";
NSString* queryString = ODBsprintf(
@"INSERT %@ INTO %@ (%@) VALUES(%@)",
orReplace,
tableName,
[[queryData allKeys] componentsJoinedByString:@","],
[[queryData allValues] componentsJoinedByString:@","]
);
return [self performQueryInTransaction:queryString block:nil];
}
+ (int64_t)performQuery:(NSString *)query block:(SQLiteBlock)block
{
return [[self singleton] performQueryInTransaction:query block:block];
}
- (void)setupDatabaseAndForceReset:(BOOL)forceReset
{
NSAssert(dbFilePath_!=nil, @"dbFilePath must be set!");
#if DEBUG_LOG>=1
NSLog(@"Using sqlite database at path %@", dbFilePath_);
#endif
NSString* defaultDB = [[NSBundle mainBundle]pathForResource:@"data_skeleton" ofType:@"sqlite3"];
NSString* appFile = dbFilePath_;
BOOL exists = [[NSFileManager defaultManager]fileExistsAtPath:appFile];
if (exists && forceReset)
[[NSFileManager defaultManager] removeItemAtPath:appFile error:nil];
if (!exists || forceReset)
[[NSFileManager defaultManager]copyItemAtPath:defaultDB toPath:appFile error:nil];
}
+ (void)setupDatabaseAndForceReset:(BOOL)forceReset
{
[[self singleton] setupDatabaseAndForceReset:forceReset];
}
@end