forked from misato/SQLiteManager4iOS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SQLiteManager.m
484 lines (377 loc) · 13 KB
/
SQLiteManager.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
//
// SQLiteManager.m
// collections
//
// Created by Ester Sanchez on 10/03/11.
// Copyright 2011 Dinamica Studios. All rights reserved.
//
#import "SQLiteManager.h"
// Private methods
@interface SQLiteManager (Private)
- (NSString *)getDatabasePath;
- (NSError *)createDBErrorWithDescription:(NSString*)description andCode:(int)code;
@end
@implementation SQLiteManager
#pragma mark Init & Dealloc
/**
* Init method.
* Use this method to initialise the object, instead of just "init".
*
* @param name the name of the database to manage.
*
* @return the SQLiteManager object initialised.
*/
- (id)initWithDatabaseNamed:(NSString *)name; {
self = [super init];
if (self != nil) {
databaseName = [[NSString alloc] initWithString:name];
db = nil;
}
return self;
}
#pragma mark SQLite Operations
/**
* Open or create a SQLite3 database.
*
* If the db exists, then is opened and ready to use. If not exists then is created and opened.
*
* @return nil if everything was ok, an NSError in other case.
*
*/
- (NSError *) openDatabase {
NSError *error = nil;
NSString *databasePath = [self getDatabasePath];
const char *dbpath = [databasePath UTF8String];
int result = sqlite3_open(dbpath, &db);
if (result != SQLITE_OK) {
const char *errorMsg = sqlite3_errmsg(db);
NSString *errorStr = [NSString stringWithFormat:@"The database could not be opened: %@",[NSString stringWithCString:errorMsg encoding:NSUTF8StringEncoding]];
error = [self createDBErrorWithDescription:errorStr andCode:kDBFailAtOpen];
}
return error;
}
/**
* Does an SQL query.
*
* You should use this method for everything but SELECT statements.
*
* @param sql the sql statement.
*
* @return nil if everything was ok, NSError in other case.
*/
- (NSError *)doQuery:(NSString *)sql {
NSError *openError = nil;
NSError *errorQuery = nil;
//Check if database is open and ready.
if (db == nil) {
openError = [self openDatabase];
}
if (openError == nil) {
sqlite3_stmt *statement;
const char *query = [sql UTF8String];
sqlite3_prepare_v2(db, query, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_ERROR) {
const char *errorMsg = sqlite3_errmsg(db);
errorQuery = [self createDBErrorWithDescription:[NSString stringWithCString:errorMsg encoding:NSUTF8StringEncoding]
andCode:kDBErrorQuery];
}
sqlite3_finalize(statement);
errorQuery = [self closeDatabase];
}
else {
errorQuery = openError;
}
return errorQuery;
}
/**
* Does an SQL parameterized query.
*
* You should use this method for parameterized INSERT or UPDATE statements.
*
* @param sql the sql statement using ? for params.
*
* @param params NSArray of params type (id), in CORRECT order please.
*
* @return nil if everything was ok, NSError in other case.
*/
- (NSError *)doUpdateQuery:(NSString *)sql withParams:(NSArray *)params {
NSError *openError = nil;
NSError *errorQuery = nil;
//Check if database is open and ready.
if (db == nil) {
openError = [self openDatabase];
}
if (openError == nil) {
sqlite3_stmt *statement;
const char *query = [sql UTF8String];
sqlite3_prepare_v2(db, query, -1, &statement, NULL);
//BIND the params!
int count =0;
for (id param in params ) {
count++;
if ([param isKindOfClass:[NSString class]] )
sqlite3_bind_text(statement, count, [param UTF8String], -1, SQLITE_TRANSIENT);
if ([param isKindOfClass:[NSNumber class]] ) {
if (!strcmp([param objCType], @encode(float)))
sqlite3_bind_double(statement, count, [param doubleValue]);
else if (!strcmp([param objCType], @encode(int)))
sqlite3_bind_int(statement, count, [param intValue]);
else if (!strcmp([param objCType], @encode(BOOL)))
sqlite3_bind_int(statement, count, [param intValue]);
else
NSLog(@"unknown NSNumber");
}
if ([param isKindOfClass:[NSDate class]]) {
sqlite3_bind_double(statement, count, [param timeIntervalSince1970]);
}
if ([param isKindOfClass:[NSData class]] ) {
sqlite3_bind_blob(statement, count, [param bytes], [param length], SQLITE_STATIC);
}
}
if (sqlite3_step(statement) == SQLITE_ERROR) {
const char *errorMsg = sqlite3_errmsg(db);
errorQuery = [self createDBErrorWithDescription:[NSString stringWithCString:errorMsg encoding:NSUTF8StringEncoding]
andCode:kDBErrorQuery];
}
sqlite3_finalize(statement);
errorQuery = [self closeDatabase];
}
else {
errorQuery = openError;
}
return errorQuery;
}
- (NSInteger)getLastInsertRowID {
NSError *openError = nil;
sqlite3_int64 rowid = 0;
//Check if database is open and ready.
if (db == nil) {
openError = [self openDatabase];
}
if (openError == nil) {
rowid = sqlite3_last_insert_rowid(db);
}
return (NSInteger)rowid;
}
/**
* Does a SELECT query and gets the info from the db.
*
* The return array contains an NSDictionary for row, made as: key=columName value= columnValue.
*
* For example, if we have a table named "users" containing:
* name | pass
* -------------
* admin| 1234
* pepe | 5678
*
* it will return an array with 2 objects:
* resultingArray[0] = name=admin, pass=1234;
* resultingArray[1] = name=pepe, pass=5678;
*
* So to get the admin password:
* [[resultingArray objectAtIndex:0] objectForKey:@"pass"];
*
* @param sql the sql query (remember to use only a SELECT statement!).
*
* @return an array containing the rows fetched.
*/
- (NSArray *)getRowsForQuery:(NSString *)sql {
NSMutableArray *resultsArray = [[NSMutableArray alloc] initWithCapacity:1];
if (db == nil) {
[self openDatabase];
}
sqlite3_stmt *statement;
const char *query = [sql UTF8String];
int returnCode = sqlite3_prepare_v2(db, query, -1, &statement, NULL);
if (returnCode == SQLITE_ERROR) {
const char *errorMsg = sqlite3_errmsg(db);
NSError *errorQuery = [self createDBErrorWithDescription:[NSString stringWithCString:errorMsg encoding:NSUTF8StringEncoding]
andCode:kDBErrorQuery];
NSLog(@"%@", errorQuery);
}
while (sqlite3_step(statement) == SQLITE_ROW) {
int columns = sqlite3_column_count(statement);
NSMutableDictionary *result = [[NSMutableDictionary alloc] initWithCapacity: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 setObject:[NSNumber numberWithInt:value] forKey:columnName];
break;
}
case SQLITE_FLOAT:
{
float value = sqlite3_column_double(statement, i);
[result setObject:[NSNumber numberWithFloat:value] forKey:columnName];
break;
}
case SQLITE_TEXT:
{
const char *value = (const char*)sqlite3_column_text(statement, i);
[result setObject:[NSString stringWithCString:value encoding:NSUTF8StringEncoding] forKey:columnName];
break;
}
case SQLITE_BLOB:
{
int bytes = sqlite3_column_bytes(statement, i);
if (bytes > 0) {
const void *blob = sqlite3_column_blob(statement, i);
if (blob != NULL) {
[result setObject:[NSData dataWithBytes:blob length:bytes] forKey:columnName];
}
}
break;
}
case SQLITE_NULL:
[result setObject:[NSNull null] forKey:columnName];
break;
default:
{
const char *value = (const char *)sqlite3_column_text(statement, i);
[result setObject:[NSString stringWithCString:value encoding:NSUTF8StringEncoding] forKey:columnName];
break;
}
} //end switch
} //end for
[resultsArray addObject:result];
} //end while
sqlite3_finalize(statement);
[self closeDatabase];
return resultsArray;
}
/**
* Closes the database.
*
* @return nil if everything was ok, NSError in other case.
*/
- (NSError *) closeDatabase {
NSError *error = nil;
if (db != nil) {
if (sqlite3_close(db) != SQLITE_OK){
const char *errorMsg = sqlite3_errmsg(db);
NSString *errorStr = [NSString stringWithFormat:@"The database could not be closed: %@",[NSString stringWithCString:errorMsg encoding:NSUTF8StringEncoding]];
error = [self createDBErrorWithDescription:errorStr andCode:kDBFailAtClose];
}
db = nil;
}
return error;
}
/**
* Creates an SQL dump of the database.
*
* This method could get a csv format dump with a few changes.
* But i prefer working with sql dumps ;)
*
* @return an NSString containing the dump.
*/
- (NSString *)getDatabaseDump {
NSMutableString *dump = [[NSMutableString alloc] initWithCapacity:256];
// info string ;) please do not remove it
[dump appendString:@";\n; Dump generated with SQLiteManager4iOS \n;\n; By Misato (2011)\n"];
[dump appendString:[NSString stringWithFormat:@"; database %@;\n", [databaseName lastPathComponent]]];
// first get all table information
NSArray *rows = [self getRowsForQuery:@"SELECT * FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';"];
// last sql query returns something like:
// {
// name = users;
// rootpage = 2;
// sql = "CREATE TABLE users (id integer primary key autoincrement, user text, password text)";
// "tbl_name" = users;
// type = table;
// }
//loop through all tables
for (int i = 0; i<[rows count]; i++) {
NSDictionary *obj = [rows objectAtIndex:i];
//get sql "create table" sentence
NSString *sql = [obj objectForKey:@"sql"];
[dump appendString:[NSString stringWithFormat:@"%@;\n",sql]];
//get table name
NSString *tableName = [obj objectForKey:@"name"];
//get all table content
NSArray *tableContent = [self getRowsForQuery:[NSString stringWithFormat:@"SELECT * FROM %@",tableName]];
for (int j = 0; j<[tableContent count]; j++) {
NSDictionary *item = [tableContent objectAtIndex:j];
//keys are column names
NSArray *keys = [item allKeys];
//values are column values
NSArray *values = [item allValues];
//start constructing insert statement for this item
[dump appendString:[NSString stringWithFormat:@"insert into %@ (",tableName]];
//loop through all keys (aka column names)
NSEnumerator *enumerator = [keys objectEnumerator];
id obj;
while (obj = [enumerator nextObject]) {
[dump appendString:[NSString stringWithFormat:@"%@,",obj]];
}
//delete last comma
NSRange range;
range.length = 1;
range.location = [dump length]-1;
[dump deleteCharactersInRange:range];
[dump appendString:@") values ("];
// loop through all values
// value types could be:
// NSNumber for integer and floats, NSNull for null or NSString for text.
enumerator = [values objectEnumerator];
while (obj = [enumerator nextObject]) {
//if it's a number (integer or float)
if ([obj isKindOfClass:[NSNumber class]]){
[dump appendString:[NSString stringWithFormat:@"%@,",[obj stringValue]]];
}
//if it's a null
else if ([obj isKindOfClass:[NSNull class]]){
[dump appendString:@"null,"];
}
//else is a string ;)
else{
[dump appendString:[NSString stringWithFormat:@"'%@',",obj]];
}
}
//delete last comma again
range.length = 1;
range.location = [dump length]-1;
[dump deleteCharactersInRange:range];
//finish our insert statement
[dump appendString:@");\n"];
}
}
return dump;
}
@end
#pragma mark -
@implementation SQLiteManager (Private)
/**
* Gets the database file path (in NSDocumentDirectory).
*
* @return the path to the db file.
*/
- (NSString *)getDatabasePath{
if([[NSFileManager defaultManager] fileExistsAtPath:databaseName]){
// Already Full Path
return databaseName;
} else {
// Get the documents directory
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
return [docsDir stringByAppendingPathComponent:databaseName];
}
}
/**
* Creates an NSError.
*
* @param description the description wich can be queried with [error localizedDescription];
* @param code the error code (code erors are defined as enum in the header file).
*
* @return the NSError just created.
*
*/
- (NSError *)createDBErrorWithDescription:(NSString*)description andCode:(int)code {
NSDictionary *userInfo = [[NSDictionary alloc] initWithObjectsAndKeys:description, NSLocalizedDescriptionKey, nil];
NSError *error = [NSError errorWithDomain:@"SQLite Error" code:code userInfo:userInfo];
return error;
}
@end