forked from johndpope/egodatabase
-
Notifications
You must be signed in to change notification settings - Fork 2
/
EGODatabase.m
440 lines (358 loc) · 13.2 KB
/
EGODatabase.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
//
// EGODatabase.m
// EGODatabase
//
// Created by Shaun Harrison on 3/6/09.
// Copyright (c) 2009 enormego
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/*
* Some of the code below is based on code from FMDB
* (Mostly bindObject, and the error checking)
*
* We've reworked it, rewritten a lot of it, and feel we've improved on it.
* However credit is still due to FMDB.
*
* @see http://code.google.com/p/flycode/soureturnCodee/browse/#svn/trunk/fmdb
*/
#define WARNING_MSG "FATAL: object is not an NSObject subclass. Are you using int? use [NSNumber numberWithInt:1] \n"
#define VAToArray(firstarg) ({\
NSMutableArray* valistArray = [NSMutableArray array];\
id obj = nil;\
va_list arguments;\
va_start(arguments, sql);\
@try { \
while ((obj = va_arg(arguments, id))) {\
if([obj isKindOfClass:[NSObject class]]) [valistArray addObject:obj];\
else printf(WARNING_MSG); \
}\
} \
@catch(NSException *exception){ \
printf(WARNING_MSG); \
} \
va_end(arguments);\
valistArray;\
})
#import "EGODatabase.h"
@interface EGODatabase ()
- (BOOL)bindStatement:(sqlite3_stmt*)statement toParameters:(NSArray*)parameters;
- (void)bindObject:(id)obj toColumn:(int)idx inStatement:(sqlite3_stmt*)pStmt;
@end
@implementation EGODatabase
@synthesize sqliteHandle=handle;
+ (id)databaseWithPath:(NSString*)aPath {
return [[[self class] alloc] initWithPath:aPath];
}
- (id)initWithPath:(NSString*)aPath {
if((self = [super init])) {
databasePath = aPath;
executeLock = [[NSLock alloc] init];
}
return self;
}
- (EGODatabaseRequest*)requestWithQueryAndParameters:(NSString*)sql, ... {
return [self requestWithQuery:sql parameters:VAToArray(sql)];
}
- (EGODatabaseRequest*)requestWithQuery:(NSString*)sql {
return [self requestWithQuery:sql parameters:nil];
}
- (EGODatabaseRequest*)requestWithQuery:(NSString*)sql parameters:(NSArray*)parameters {
EGODatabaseRequest* request = [[EGODatabaseRequest alloc] initWithQuery:sql parameters:parameters];
request.database = self;
request.requestKind = EGODatabaseSelectRequest;
return request;
}
- (EGODatabaseRequest*)requestWithUpdateAndParameters:(NSString*)sql, ... {
return [self requestWithUpdate:sql parameters:VAToArray(sql)];
}
- (EGODatabaseRequest*)requestWithUpdate:(NSString*)sql {
return [self requestWithUpdate:sql parameters:nil];
}
- (EGODatabaseRequest*)requestWithUpdate:(NSString*)sql parameters:(NSArray*)parameters {
EGODatabaseRequest* request = [[EGODatabaseRequest alloc] initWithQuery:sql parameters:parameters];
request.database = self;
request.requestKind = EGODatabaseUpdateRequest;
return request;
}
/*- (void)test:(NSString*)sql,... {
NSLog(@"VAToArray :%@",VAToArray(sql));
}*/
- (BOOL)open {
//[self test:@"str",2,nil];
if(opened) return YES;
int err = sqlite3_open([databasePath fileSystemRepresentation], &handle);
if(err != SQLITE_OK) {
EGODBDebugLog(@"[EGODatabase] Error opening DB: %d", err);
return NO;
}
opened = YES;
return YES;
}
- (void)close {
if(!handle) return;
sqlite3_close(handle);
opened = NO;
}
- (BOOL)executeUpdateWithParameters:(NSString*)sql,... {
return [self executeUpdate:sql parameters:VAToArray(sql)];
}
- (BOOL)executeUpdate:(NSString*)sql {
return [self executeUpdate:sql parameters:nil];
}
- (BOOL)executeUpdate:(NSString*)sql parameters:(NSArray*)parameters {
EGODBLockLog(@"[Update] Waiting for Lock (%@): %@ %@", [sql md5], sql, [NSThread isMainThread] ? @"** Alert: Attempting to lock on main thread **" : @"");
[executeLock lock];
EGODBLockLog(@"[Update] Got Lock (%@)", [sql md5]);
if(![self open]) {
EGODBLockLog(@"%@ released lock", [sql md5]);
[executeLock unlock];
return NO;
}
int returnCode = 0;
sqlite3_stmt* statement = NULL;
returnCode = sqlite3_prepare(handle, [sql UTF8String], -1, &statement, 0);
if (SQLITE_BUSY == returnCode) {
EGODBLockLog(@"[EGODatabase] Query Failed, Database Busy:\n%@\n\n", sql);
EGODBLockLog(@"%@ released lock", [sql md5]);
[executeLock unlock];
return NO;
} else if (SQLITE_OK != returnCode) {
EGODBDebugLog(@"[EGODatabase] Query Failed, Error: %d \"%@\"\n%@\n\n", [self lastErrorCode], [self lastErrorMessage], sql);
sqlite3_finalize(statement);
EGODBLockLog(@"%@ released lock", [sql md5]);
[executeLock unlock];
return NO;
}
if (![self bindStatement:statement toParameters:parameters]) {
EGODBDebugLog(@"[EGODatabase] Invalid bind cound for number of arguments.");
sqlite3_finalize(statement);
EGODBLockLog(@"%@ released lock", [sql md5]);
[executeLock unlock];
return NO;
}
returnCode = sqlite3_step(statement);
if (SQLITE_BUSY == returnCode) {
EGODBDebugLog(@"[EGODatabase] Query Failed, Database Busy:\n%@\n\n", sql);
} else if (SQLITE_DONE == returnCode || SQLITE_ROW == returnCode) {
} else if (SQLITE_ERROR == returnCode) {
EGODBDebugLog(@"[EGODatabase] sqlite3_step Failed: (%d: %@) SQLITE_ERROR\n%@\n\n", returnCode, [self lastErrorMessage], sql);
} else if (SQLITE_MISUSE == returnCode) {
EGODBDebugLog(@"[EGODatabase] sqlite3_step Failed: (%d: %@) SQLITE_MISUSE\n%@\n\n", returnCode, [self lastErrorMessage], sql);
} else {
EGODBDebugLog(@"[EGODatabase] sqlite3_step Failed: (%d: %@) UNKNOWN_ERROR\n%@\n\n", returnCode, [self lastErrorMessage], sql);
}
returnCode = sqlite3_finalize(statement);
EGODBLockLog(@"%@ released lock", [sql md5]);
[executeLock unlock];
return (returnCode == SQLITE_OK);
}
- (sqlite3_int64)last_insert_rowid
{
if (handle) {
return sqlite3_last_insert_rowid(handle);
} else {
EGODBDebugLog(@"[EGODatabase] Can't get last rowid of nil sqlite");
return 0;
}
}
- (EGODatabaseResult*)executeQueryWithParameters:(NSString*)sql,... {
return [self executeQuery:sql parameters:VAToArray(sql)];
}
- (EGODatabaseResult*)executeQuery:(NSString*)sql {
return [self executeQuery:sql parameters:nil];
}
- (EGODatabaseResult*)executeQuery:(NSString*)sql parameters:(NSArray*)parameters {
EGODBLockLog(@"[Query] Waiting for Lock (%@): %@", [sql md5], sql);
[executeLock lock];
EGODBLockLog(@"[Query] Got Lock (%@)", [sql md5]);
EGODatabaseResult* result = [[EGODatabaseResult alloc] init];
if(![self open]) {
EGODBLockLog(@"%@ released lock", [sql md5]);
[executeLock unlock];
return result;
}
int returnCode = 0;
sqlite3_stmt* statement = NULL;
returnCode = sqlite3_prepare(handle, [sql UTF8String], -1, &statement, 0);
result.errorCode = [self lastErrorCode];
result.errorMessage = [self lastErrorMessage];
if (SQLITE_BUSY == returnCode) {
EGODBDebugLog(@"[EGODatabase] Query Failed, Database Busy:\n%@\n\n", sql);
EGODBLockLog(@"%@ released lock", [sql md5]);
[executeLock unlock];
return result;
} else if (SQLITE_OK != returnCode) {
EGODBDebugLog(@"[EGODatabase] Query Failed, Error: %d \"%@\"\n%@\n\n", [self lastErrorCode], [self lastErrorMessage], sql);
sqlite3_finalize(statement);
EGODBLockLog(@"%@ released lock", [sql md5]);
[executeLock unlock];
return result;
}
if (![self bindStatement:statement toParameters:parameters]) {
EGODBDebugLog(@"[EGODatabase] Invalid bind cound for number of arguments.");
sqlite3_finalize(statement);
EGODBLockLog(@"%@ released lock", [sql md5]);
[executeLock unlock];
return result;
}
int columnCount = sqlite3_column_count(statement);
int x;
for(x=0;x<columnCount;x++) {
if(sqlite3_column_name(statement,x) != NULL) {
[result.columnNames addObject:[NSString stringWithUTF8String:sqlite3_column_name(statement,x)]];
} else {
[result.columnNames addObject:[NSString stringWithFormat:@"%d", x]];
}
if(sqlite3_column_decltype(statement,x) != NULL) {
[result.columnTypes addObject:[NSString stringWithUTF8String:sqlite3_column_decltype(statement,x)]];
} else {
[result.columnTypes addObject:@""];
}
}
while(sqlite3_step(statement) == SQLITE_ROW) {
EGODatabaseRow* row = [[EGODatabaseRow alloc] initWithDatabaseResult:result];
for(x=0;x<columnCount;x++) {
if (SQLITE_BLOB == sqlite3_column_type(statement, x)) {
[row.columnData addObject:[NSData dataWithBytes:sqlite3_column_blob(statement,x)
length:sqlite3_column_bytes(statement,x)]];
} else if (sqlite3_column_text(statement,x) != NULL) {
[row.columnData addObject:[[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement,x)]];
} else {
[row.columnData addObject:@""];
}
}
[result addRow:row];
}
sqlite3_finalize(statement);
EGODBLockLog(@"%@ released lock", [sql md5]);
[executeLock unlock];
return result;
}
- (NSString*)lastErrorMessage {
if([self hadError]) {
return [NSString stringWithUTF8String:sqlite3_errmsg(handle)];
} else {
return nil;
}
}
// Transaction helpers
- (BOOL)rollback {
BOOL b = [self executeUpdate:@"ROLLBACK TRANSACTION;"];
if (b) {
inTransaction = NO;
}
return b;
}
- (BOOL)commit {
BOOL b = [self executeUpdate:@"COMMIT TRANSACTION;"];
if (b) {
inTransaction = NO;
}
return b;
}
- (BOOL)beginDeferredTransaction {
BOOL b = [self executeUpdate:@"BEGIN DEFERRED TRANSACTION;"];
if (b) {
inTransaction = YES;
}
return b;
}
- (BOOL)beginTransaction {
BOOL b = [self executeUpdate:@"BEGIN EXCLUSIVE TRANSACTION;"];
if (b) {
inTransaction = YES;
}
return b;
}
- (BOOL)inTransaction {
return inTransaction;
}
- (void)setInTransaction:(BOOL)flag {
inTransaction = flag;
}
- (BOOL)hadError {
return [self lastErrorCode] != SQLITE_OK;
}
- (int)lastErrorCode {
return sqlite3_errcode(handle);
}
- (BOOL)bindStatement:(sqlite3_stmt*)statement toParameters:(NSArray*)parameters {
int index = 0;
int queryCount = sqlite3_bind_parameter_count(statement);
for(id obj in parameters) {
index++;
[self bindObject:obj toColumn:index inStatement:statement];
}
return index == queryCount;
}
- (void)bindObject:(id)obj toColumn:(int)idx inStatement:(sqlite3_stmt*)pStmt {
if ((!obj) || ((NSNull *)obj == [NSNull null])) {
sqlite3_bind_null(pStmt, idx);
} else if ([obj isKindOfClass:[NSData class]]) {
sqlite3_bind_blob(pStmt, idx, [obj 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(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);
}
}
#define DEG2RAD(degrees) (degrees * 0.01745327) // degrees * pi over 180
static void distanceFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
{
// check that we have four arguments (lat1, lon1, lat2, lon2)
assert(argc == 4);
// check that all four arguments are non-null
if (sqlite3_value_type(argv[0]) == SQLITE_NULL || sqlite3_value_type(argv[1]) == SQLITE_NULL || sqlite3_value_type(argv[2]) == SQLITE_NULL || sqlite3_value_type(argv[3]) == SQLITE_NULL) {
sqlite3_result_null(context);
return;
}
// get the four argument values
double lat1 = sqlite3_value_double(argv[0]);
double lon1 = sqlite3_value_double(argv[1]);
double lat2 = sqlite3_value_double(argv[2]);
double lon2 = sqlite3_value_double(argv[3]);
// convert lat1 and lat2 into radians now, to avoid doing it twice below
double lat1rad = DEG2RAD(lat1);
double lat2rad = DEG2RAD(lat2);
// apply the spherical law of cosines to our latitudes and longitudes, and set the result appropriately
// 6378.1 is the approximate radius of the earth in kilometres
sqlite3_result_double(context, acos(sin(lat1rad) * sin(lat2rad) + cos(lat1rad) * cos(lat2rad) * cos(DEG2RAD(lon2) - DEG2RAD(lon1))) * 6378.1);
}
-(void)createDistanceFunc{
sqlite3_create_function(handle, "distance", 4, SQLITE_UTF8, NULL, &distanceFunc, NULL, NULL);
}
- (void)dealloc {
[self close];
}
@end