-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathSCSQLite.m
executable file
·383 lines (290 loc) · 11.1 KB
/
SCSQLite.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
//
// SCSQLite.m
//
// Created by Lucas Correa on 21/12/11.
// Copyright (c) 2012 Siriuscode Solutions. All rights reserved.
//
#import "SCSQLite.h"
@interface SCSQLite ()
- (BOOL)openDatabase;
- (BOOL)closeDatabase;
@end
@implementation SCSQLite
@synthesize database = _database;
#pragma mark -
#pragma mark - Singleton
+ (SCSQLite *)shared
{
static SCSQLite * _scsqlite = nil;
@synchronized (self){
static dispatch_once_t pred;
dispatch_once(&pred, ^{
_scsqlite = [[SCSQLite alloc] init];
});
}
return _scsqlite;
}
#pragma mark -
#pragma mark - Public Methods
+ (void)initWithDatabase:(NSString *)database
{
[SCSQLite shared].database = database;
}
+ (BOOL)executeSQL:(NSString *)sql, ...
{
BOOL openDatabase = NO;
va_list arguments;
va_start(arguments, sql);
// NSLogv(sql, arguments);
sql = [[NSString alloc] initWithFormat:sql arguments:arguments];
va_end(arguments);
//Check if database is open and ready.
if ([SCSQLite shared]->db == nil) {
openDatabase = [[SCSQLite shared] openDatabase];
}
if (openDatabase) {
sqlite3_stmt *statement;
const char *query = [sql UTF8String];
// prepare
if (sqlite3_prepare_v2([SCSQLite shared]->db, query, -1, &statement, NULL) != SQLITE_OK) {
NSLog(@"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg([SCSQLite shared]->db));
return NO;
}
id obj;
int idx = 0;
int queryCount = sqlite3_bind_parameter_count(statement);
while (idx < queryCount) {
obj = va_arg(arguments, id);
idx++;
[[SCSQLite shared] bindObject:obj toColumn:idx inStatement:statement];
}
// execute
while (1) {
if(sqlite3_step(statement) == SQLITE_DONE){
sqlite3_finalize(statement);
[[SCSQLite shared] closeDatabase];
return YES;
}else {
NSLog(@" 2. Error %d: '%s' com sql: %@", sqlite3_errcode([SCSQLite shared]->db), sqlite3_errmsg([SCSQLite shared]->db), sql);
if(sqlite3_errcode([SCSQLite shared]->db) != SQLITE_LOCKED){
sqlite3_finalize(statement);
[[SCSQLite shared] closeDatabase];
return NO;
}
[NSThread sleepForTimeInterval:.1];
}
}
}
else {
return NO;
}
return YES;
}
+ (NSArray *)selectRowSQL:(NSString *)sql, ...
{
va_list arguments;
va_start(arguments, sql);
// NSLogv(sql, arguments);
sql = [[NSString alloc] initWithFormat:sql arguments:arguments];
va_end(arguments);
NSMutableArray *resultsArray = [[NSMutableArray alloc] initWithCapacity:1];
if ([SCSQLite shared]->db == nil) {
[[SCSQLite shared] openDatabase];
}
sqlite3_stmt *statement;
const char *query = [sql UTF8String];
sqlite3_prepare_v2([SCSQLite shared]->db, query, -1, &statement, NULL);
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 dataSize = sqlite3_column_bytes(statement, i);
NSMutableData *data = [NSMutableData dataWithLength:dataSize];
memcpy([data mutableBytes], sqlite3_column_blob(statement, i), dataSize);
[result setObject:data 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;
}
}
}
[resultsArray addObject:result];
}
sqlite3_finalize(statement);
[[SCSQLite shared] closeDatabase];
return resultsArray;
}
+ (NSString *)getDatabaseDump
{
NSMutableString *dump = [[NSMutableString alloc] initWithCapacity:256];
// info string ;) please do not remove it
[dump appendString:@";\n; Dump generated with SCSQLite \n;\n"];
[dump appendString:[NSString stringWithFormat:@"; database %@;\n\n", [SCSQLite shared].database]];
// first get all table information
NSArray *rows = [SCSQLite selectRowSQL:@"SELECT * FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%%';"];
//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 = [SCSQLite selectRowSQL:@"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;
}
#pragma mark -
#pragma mark - Private Methods
- (BOOL)openDatabase
{
NSString *databasePath;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (self.database != nil) {
databasePath = [documentsDirectory stringByAppendingPathComponent:self.database];
}else{
[[[UIAlertView alloc] initWithTitle:@"Alert" message:@"It is necessary to initialize the database name of the sqlite" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
return NO;
}
//first check if exist
if(![[NSFileManager defaultManager] fileExistsAtPath:databasePath]) {
// if not, move pro mainbundle root to documents
BOOL success = [[NSFileManager defaultManager] copyItemAtPath:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:self.database] toPath:databasePath error:nil];
if (!success) return NO;
}
BOOL success = YES;
if(!sqlite3_open([databasePath UTF8String], &db) == SQLITE_OK ) success = NO;
return success;
}
- (void)bindObject:(id)obj toColumn:(int)idx inStatement:(sqlite3_stmt*)pStmt
{
if ((!obj) || ((NSNull *)obj == [NSNull null])) {
sqlite3_bind_null(pStmt, idx);
}
// FIXME - someday check the return codes on these binds.
else if ([obj isKindOfClass:[NSData class]]) {
const void *bytes = [obj bytes];
if (!bytes) {
// it's an empty NSData object, aka [NSData data].
// Don't pass a NULL pointer, or sqlite will bind a SQL null instead of a blob.
bytes = "";
}
sqlite3_bind_blob(pStmt, idx, bytes, (int)[obj length], SQLITE_STATIC);
}
else if ([obj isKindOfClass:[NSDate class]]) {
sqlite3_bind_double(pStmt, idx, [obj timeIntervalSince1970]);
}
else if ([obj isKindOfClass:[NSNumber class]]) {
if (strcmp([obj objCType], @encode(BOOL)) == 0) {
sqlite3_bind_int(pStmt, idx, ([obj boolValue] ? 1 : 0));
}
else if (strcmp([obj objCType], @encode(int)) == 0) {
sqlite3_bind_int64(pStmt, idx, [obj longValue]);
}
else if (strcmp([obj objCType], @encode(long)) == 0) {
sqlite3_bind_int64(pStmt, idx, [obj longValue]);
}
else if (strcmp([obj objCType], @encode(long long)) == 0) {
sqlite3_bind_int64(pStmt, idx, [obj longLongValue]);
}
else if (strcmp([obj objCType], @encode(unsigned long long)) == 0) {
sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongLongValue]);
}
else if (strcmp([obj objCType], @encode(float)) == 0) {
sqlite3_bind_double(pStmt, idx, [obj floatValue]);
}
else if (strcmp([obj objCType], @encode(double)) == 0) {
sqlite3_bind_double(pStmt, idx, [obj doubleValue]);
}
else {
sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
}
}
else {
sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
}
}
- (BOOL)closeDatabase
{
if (db != nil) {
if (sqlite3_close(db) != SQLITE_OK){
return NO;
}
db = nil;
}
return YES;
}
@end