This repository was archived by the owner on Dec 22, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathSQLitePlugin.m
More file actions
executable file
·597 lines (509 loc) · 21.8 KB
/
SQLitePlugin.m
File metadata and controls
executable file
·597 lines (509 loc) · 21.8 KB
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
/*
* Copyright (c) 2012-2016: Christopher J. Brody (aka Chris Brody)
* Copyright (C) 2011 Davide Bertola
*
* This library is available under the terms of the MIT License (2008).
* See http://opensource.org/licenses/alphabetical for full text.
*/
#import "SQLitePlugin.h"
#import "sqlite3.h"
// NOTE: This is now broken by cordova-ios 4.0, see:
// https://issues.apache.org/jira/browse/CB-9638
// Solution is to use NSJSONSerialization instead.
#ifdef READ_BLOB_AS_BASE64
#import <Cordova/NSData+Base64.h>
#endif
@implementation SQLitePlugin
@synthesize openDBs;
@synthesize appDBPaths;
@synthesize commandCache;
@synthesize processingCache;
-(void)pluginInitialize
{
NSLog(@"Initializing SQLitePlugin");
{
openDBs = [NSMutableDictionary dictionaryWithCapacity:0];
appDBPaths = [NSMutableDictionary dictionaryWithCapacity:0];
commandCache = [NSMutableArray arrayWithCapacity:0];
processingCache = NO;
#if !__has_feature(objc_arc)
[openDBs retain];
[appDBPaths retain];
#endif
NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex: 0];
NSLog(@"Detected docs path: %@", docs);
[appDBPaths setObject: docs forKey:@"docs"];
NSString *libs = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex: 0];
NSLog(@"Detected Library path: %@", libs);
[appDBPaths setObject: libs forKey:@"libs"];
NSString *nosync = [libs stringByAppendingPathComponent:@"LocalDatabase"];
NSError *err;
if ([[NSFileManager defaultManager] fileExistsAtPath: nosync])
{
NSLog(@"no cloud sync at path: %@", nosync);
[appDBPaths setObject: nosync forKey:@"nosync"];
}
else
{
if ([[NSFileManager defaultManager] createDirectoryAtPath: nosync withIntermediateDirectories:NO attributes: nil error:&err])
{
NSURL *nosyncURL = [ NSURL fileURLWithPath: nosync];
if (![nosyncURL setResourceValue: [NSNumber numberWithBool: YES] forKey: NSURLIsExcludedFromBackupKey error: &err])
{
NSLog(@"IGNORED: error setting nobackup flag in LocalDatabase directory: %@", err);
}
NSLog(@"no cloud sync at path: %@", nosync);
[appDBPaths setObject: nosync forKey:@"nosync"];
}
else
{
// fallback:
NSLog(@"WARNING: error adding LocalDatabase directory: %@", err);
[appDBPaths setObject: libs forKey:@"nosync"];
}
}
}
}
-(id) getDBPath:(NSString *)dbFile at:(NSString *)atkey {
if (dbFile == NULL) {
return NULL;
}
NSString *dbdir = [appDBPaths objectForKey:atkey];
NSString *dbPath = [dbdir stringByAppendingPathComponent: dbFile];
return dbPath;
}
-(void)echoStringValue: (CDVInvokedUrlCommand*)command
{
CDVPluginResult * pluginResult = nil;
NSMutableDictionary * options = [command.arguments objectAtIndex:0];
NSString * string_value = [options objectForKey:@"value"];
NSLog(@"echo string value: %@", string_value);
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:string_value];
[self.commandDelegate sendPluginResult:pluginResult callbackId: command.callbackId];
}
-(void)open: (CDVInvokedUrlCommand*)command
{
[self.commandDelegate runInBackground:^{
[self openNow: command];
}];
}
-(void)openNow: (CDVInvokedUrlCommand*)command
{
CDVPluginResult* pluginResult = nil;
NSMutableDictionary *options = [command.arguments objectAtIndex:0];
NSString *dbfilename = [options objectForKey:@"name"];
NSString *dblocation = [options objectForKey:@"dblocation"];
if (dblocation == NULL) dblocation = @"docs";
//NSLog(@"using db location: %@", dblocation);
NSString *dbname = [self getDBPath:dbfilename at:dblocation];
if (dbname == NULL) {
NSLog(@"No db name specified for open");
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"You must specify database name"];
}
else {
NSValue *dbPointer = [openDBs objectForKey:dbfilename];
if (dbPointer != NULL) {
NSLog(@"Reusing existing database connection for db name %@", dbfilename);
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"Database opened"];
} else {
const char *name = [dbname UTF8String];
sqlite3 *db;
NSLog(@"open full db path: %@", dbname);
if (sqlite3_open(name, &db) != SQLITE_OK) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Unable to open DB"];
return;
} else {
// for SQLCipher version:
// NSString *dbkey = [options objectForKey:@"key"];
// const char *key = NULL;
// if (dbkey != NULL) key = [dbkey UTF8String];
// if (key != NULL) sqlite3_key(db, key, strlen(key));
// Attempt to read the SQLite master table [to support SQLCipher version]:
if(sqlite3_exec(db, (const char*)"SELECT count(*) FROM sqlite_master;", NULL, NULL, NULL) == SQLITE_OK) {
dbPointer = [NSValue valueWithPointer:db];
[openDBs setObject: dbPointer forKey: dbfilename];
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"Database opened"];
} else {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Unable to open DB with key"];
// XXX TODO: close the db handle & [perhaps] remove from openDBs!!
}
}
}
}
if (sqlite3_threadsafe()) {
NSLog(@"Good news: SQLite is thread safe!");
}
else {
NSLog(@"Warning: SQLite is not thread safe.");
}
[self.commandDelegate sendPluginResult:pluginResult callbackId: command.callbackId];
// NSLog(@"open cb finished ok");
}
-(void) close: (CDVInvokedUrlCommand*)command
{
[self.commandDelegate runInBackground:^{
[self closeNow: command];
}];
}
-(void)closeNow: (CDVInvokedUrlCommand*)command
{
CDVPluginResult* pluginResult = nil;
NSMutableDictionary *options = [command.arguments objectAtIndex:0];
NSString *dbFileName = [options objectForKey:@"path"];
if (dbFileName == NULL) {
// Should not happen:
NSLog(@"No db name specified for close");
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"You must specify database path"];
} else {
NSValue *val = [openDBs objectForKey:dbFileName];
sqlite3 *db = [val pointerValue];
if (db == NULL) {
// Should not happen:
NSLog(@"close: db name was not open: %@", dbFileName);
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Specified db was not open"];
}
else {
NSLog(@"close db name: %@", dbFileName);
sqlite3_close (db);
[openDBs removeObjectForKey:dbFileName];
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"DB closed"];
}
}
[self.commandDelegate sendPluginResult:pluginResult callbackId: command.callbackId];
}
-(void) delete: (CDVInvokedUrlCommand*)command
{
[self.commandDelegate runInBackground:^{
[self deleteNow: command];
}];
}
-(void)deleteNow: (CDVInvokedUrlCommand*)command
{
CDVPluginResult* pluginResult = nil;
NSMutableDictionary *options = [command.arguments objectAtIndex:0];
NSString *dbFileName = [options objectForKey:@"path"];
NSString *dblocation = [options objectForKey:@"dblocation"];
if (dblocation == NULL) dblocation = @"docs";
if (dbFileName==NULL) {
// Should not happen:
NSLog(@"No db name specified for delete");
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"You must specify database path"];
} else {
NSString *dbPath = [self getDBPath:dbFileName at:dblocation];
if ([[NSFileManager defaultManager]fileExistsAtPath:dbPath]) {
NSLog(@"delete full db path: %@", dbPath);
[[NSFileManager defaultManager]removeItemAtPath:dbPath error:nil];
[openDBs removeObjectForKey:dbFileName];
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"DB deleted"];
} else {
NSLog(@"delete: db was not found: %@", dbPath);
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"The database does not exist on that path"];
}
}
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
-(void) processCache
{
processingCache = YES;
[self.commandDelegate runInBackground:^{
@synchronized (self) {
if (commandCache.count) {
CDVInvokedUrlCommand* cachedCmd = [commandCache objectAtIndex:0];
[commandCache removeObjectAtIndex:0];
[self executeSqlBatchNow: cachedCmd];
}
else {
processingCache = NO;
}
}
}];
}
-(void) backgroundExecuteSqlBatch: (CDVInvokedUrlCommand*)command
{
@synchronized (self) {
[commandCache addObject:command];
if (!processingCache)
[self processCache];
}
}
-(void) executeSqlBatchNow: (CDVInvokedUrlCommand*)command
{
NSMutableDictionary *options = [command.arguments objectAtIndex:0];
NSMutableArray *results = [NSMutableArray arrayWithCapacity:0];
NSMutableDictionary *dbargs = [options objectForKey:@"dbargs"];
NSMutableArray *executes = [options objectForKey:@"executes"];
CDVPluginResult* pluginResult;
@synchronized(self) {
for (NSMutableDictionary *dict in executes) {
CDVPluginResult *result = [self executeSqlWithDict:dict andArgs:dbargs];
if ([result.status intValue] == CDVCommandStatus_ERROR) {
/* add error with result.message: */
NSMutableDictionary *r = [NSMutableDictionary dictionaryWithCapacity:0];
[r setObject:[dict objectForKey:@"qid"] forKey:@"qid"];
[r setObject:@"error" forKey:@"type"];
[r setObject:result.message forKey:@"error"];
[r setObject:result.message forKey:@"result"];
[results addObject: r];
} else {
/* add result with result.message: */
NSMutableDictionary *r = [NSMutableDictionary dictionaryWithCapacity:0];
[r setObject:[dict objectForKey:@"qid"] forKey:@"qid"];
[r setObject:@"success" forKey:@"type"];
[r setObject:result.message forKey:@"result"];
[results addObject: r];
}
}
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:results];
}
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
[self processCache];
}
-(void) backgroundExecuteSql: (CDVInvokedUrlCommand*)command
{
[self.commandDelegate runInBackground:^{
[self executeSql:command];
}];
}
-(void) executeSql: (CDVInvokedUrlCommand*)command
{
NSMutableDictionary *options = [command.arguments objectAtIndex:0];
NSMutableDictionary *dbargs = [options objectForKey:@"dbargs"];
NSMutableDictionary *ex = [options objectForKey:@"ex"];
CDVPluginResult* pluginResult;
@synchronized (self) {
pluginResult = [self executeSqlWithDict: ex andArgs: dbargs];
}
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
-(CDVPluginResult*) executeSqlWithDict: (NSMutableDictionary*)options andArgs: (NSMutableDictionary*)dbargs
{
NSString *dbFileName = [dbargs objectForKey:@"dbname"];
if (dbFileName == NULL) {
return [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"You must specify database path"];
}
NSMutableArray *params = [options objectForKey:@"params"]; // optional
NSValue *dbPointer = [openDBs objectForKey:dbFileName];
if (dbPointer == NULL) {
return [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No such database, you must open it first"];
}
sqlite3 *db = [dbPointer pointerValue];
NSString *sql = [options objectForKey:@"sql"];
if (sql == NULL) {
return [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"You must specify a sql query to execute"];
}
const char *sql_stmt = [sql UTF8String];
NSDictionary *error = nil;
sqlite3_stmt *statement;
int result, i, column_type, count;
int previousRowsAffected, nowRowsAffected, diffRowsAffected;
long long previousInsertId, nowInsertId;
BOOL keepGoing = YES;
BOOL hasInsertId;
NSMutableDictionary *resultSet = [NSMutableDictionary dictionaryWithCapacity:0];
NSMutableArray *resultRows = [NSMutableArray arrayWithCapacity:0];
NSMutableDictionary *entry;
NSObject *columnValue;
NSString *columnName;
NSObject *insertId;
NSObject *rowsAffected;
hasInsertId = NO;
previousRowsAffected = sqlite3_total_changes(db);
previousInsertId = sqlite3_last_insert_rowid(db);
if (sqlite3_prepare_v2(db, sql_stmt, -1, &statement, NULL) != SQLITE_OK) {
error = [SQLitePlugin captureSQLiteErrorFromDb:db];
keepGoing = NO;
} else if (params != NULL) {
for (int b = 0; b < params.count; b++) {
[self bindStatement:statement withArg:[params objectAtIndex:b] atIndex:(b+1)];
}
}
while (keepGoing) {
result = sqlite3_step (statement);
switch (result) {
case SQLITE_ROW:
i = 0;
entry = [NSMutableDictionary dictionaryWithCapacity:0];
count = sqlite3_column_count(statement);
while (i < count) {
columnValue = nil;
columnName = [NSString stringWithFormat:@"%s", sqlite3_column_name(statement, i)];
column_type = sqlite3_column_type(statement, i);
switch (column_type) {
case SQLITE_INTEGER:
columnValue = [NSNumber numberWithLongLong: sqlite3_column_int64(statement, i)];
break;
case SQLITE_FLOAT:
columnValue = [NSNumber numberWithDouble: sqlite3_column_double(statement, i)];
break;
case SQLITE_BLOB:
#ifdef READ_BLOB_AS_BASE64
columnValue = [SQLitePlugin getBlobAsBase64String: sqlite3_column_blob(statement, i)
withLength: sqlite3_column_bytes(statement, i)];
#ifdef INCLUDE_SQL_BLOB_BINDING // TBD subjet to change:
columnValue = [@"sqlblob:;base64," stringByAppendingString:columnValue];
#endif
break;
#endif // else
case SQLITE_TEXT:
columnValue = [[NSString alloc] initWithBytes:(char *)sqlite3_column_text(statement, i)
length:sqlite3_column_bytes(statement, i)
encoding:NSUTF8StringEncoding];
#if !__has_feature(objc_arc)
[columnValue autorelease];
#endif
break;
case SQLITE_NULL:
// just in case (should not happen):
default:
columnValue = [NSNull null];
break;
}
if (columnValue) {
[entry setObject:columnValue forKey:columnName];
}
i++;
}
[resultRows addObject:entry];
break;
case SQLITE_DONE:
nowRowsAffected = sqlite3_total_changes(db);
diffRowsAffected = nowRowsAffected - previousRowsAffected;
rowsAffected = [NSNumber numberWithInt:diffRowsAffected];
nowInsertId = sqlite3_last_insert_rowid(db);
if (nowRowsAffected > 0 && nowInsertId != 0) {
hasInsertId = YES;
insertId = [NSNumber numberWithLongLong:sqlite3_last_insert_rowid(db)];
}
keepGoing = NO;
break;
default:
error = [SQLitePlugin captureSQLiteErrorFromDb:db];
keepGoing = NO;
}
}
sqlite3_finalize (statement);
if (error) {
return [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:error];
}
[resultSet setObject:resultRows forKey:@"rows"];
[resultSet setObject:rowsAffected forKey:@"rowsAffected"];
if (hasInsertId) {
[resultSet setObject:insertId forKey:@"insertId"];
}
return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:resultSet];
}
-(void)bindStatement:(sqlite3_stmt *)statement withArg:(NSObject *)arg atIndex:(int)argIndex
{
if ([arg isEqual:[NSNull null]]) {
sqlite3_bind_null(statement, argIndex);
} else if ([arg isKindOfClass:[NSNumber class]]) {
NSNumber *numberArg = (NSNumber *)arg;
const char *numberType = [numberArg objCType];
if (strcmp(numberType, @encode(int)) == 0 ||
strcmp(numberType, @encode(long long int)) == 0) {
sqlite3_bind_int64(statement, argIndex, [numberArg longLongValue]);
} else if (strcmp(numberType, @encode(double)) == 0) {
sqlite3_bind_double(statement, argIndex, [numberArg doubleValue]);
} else {
sqlite3_bind_text(statement, argIndex, [[arg description] UTF8String], -1, SQLITE_TRANSIENT);
}
} else { // NSString
NSString *stringArg;
if ([arg isKindOfClass:[NSString class]]) {
stringArg = (NSString *)arg;
} else {
stringArg = [arg description]; // convert to text
}
#ifdef INCLUDE_SQL_BLOB_BINDING // TBD subjet to change:
// If the string is a sqlblob URI then decode it and store the binary directly.
//
// A sqlblob URI is formatted similar to a data URI which makes it easy to convert:
// sqlblob:[<mime type>][;charset=<charset>][;base64],<encoded data>
//
// The reason the `sqlblob` prefix is used instead of `data` is because
// applications may want to use data URI strings directly, so the
// `sqlblob` prefix disambiguates the desired behavior.
if ([stringArg hasPrefix:@"sqlblob:"]) {
// convert to data URI, decode, store as blob
stringArg = [stringArg stringByReplacingCharactersInRange:NSMakeRange(0,7) withString:@"data"];
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:stringArg]];
sqlite3_bind_blob(statement, argIndex, data.bytes, data.length, SQLITE_TRANSIENT);
}
else
#endif
{
NSData *data = [stringArg dataUsingEncoding:NSUTF8StringEncoding];
sqlite3_bind_text(statement, argIndex, data.bytes, (int)data.length, SQLITE_TRANSIENT);
}
}
}
-(void)dealloc
{
int i;
NSArray *keys = [openDBs allKeys];
NSValue *pointer;
NSString *key;
sqlite3 *db;
/* close db the user forgot */
for (i=0; i<[keys count]; i++) {
key = [keys objectAtIndex:i];
pointer = [openDBs objectForKey:key];
db = [pointer pointerValue];
sqlite3_close (db);
}
#if !__has_feature(objc_arc)
[openDBs release];
[appDBPaths release];
[super dealloc];
#endif
}
+(NSDictionary *)captureSQLiteErrorFromDb:(struct sqlite3 *)db
{
int code = sqlite3_errcode(db);
int webSQLCode = [SQLitePlugin mapSQLiteErrorCode:code];
#if INCLUDE_SQLITE_ERROR_INFO
int extendedCode = sqlite3_extended_errcode(db);
#endif
const char *message = sqlite3_errmsg(db);
NSMutableDictionary *error = [NSMutableDictionary dictionaryWithCapacity:4];
[error setObject:[NSNumber numberWithInt:webSQLCode] forKey:@"code"];
[error setObject:[NSString stringWithUTF8String:message] forKey:@"message"];
#if INCLUDE_SQLITE_ERROR_INFO
[error setObject:[NSNumber numberWithInt:code] forKey:@"sqliteCode"];
[error setObject:[NSNumber numberWithInt:extendedCode] forKey:@"sqliteExtendedCode"];
[error setObject:[NSString stringWithUTF8String:message] forKey:@"sqliteMessage"];
#endif
return error;
}
+(int)mapSQLiteErrorCode:(int)code
{
// map the sqlite error code to
// the websql error code
switch(code) {
case SQLITE_ERROR:
return SYNTAX_ERR;
case SQLITE_FULL:
return QUOTA_ERR;
case SQLITE_CONSTRAINT:
return CONSTRAINT_ERR;
default:
return UNKNOWN_ERR;
}
}
#ifdef READ_BLOB_AS_BASE64
+(NSString*)getBlobAsBase64String:(const char*)blob_chars
withLength:(int)blob_length
{
size_t outputLength = 0;
char* outputBuffer = CDVNewBase64Encode(blob_chars, blob_length, true, &outputLength);
NSString* result = [[NSString alloc] initWithBytesNoCopy:outputBuffer
length:outputLength
encoding:NSASCIIStringEncoding
freeWhenDone:YES];
#if !__has_feature(objc_arc)
[result autorelease];
#endif
return result;
}
#endif
@end /* vim: set expandtab : */