forked from craftzdog/react-native-sqlite-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RNSqlite2.m
314 lines (279 loc) · 10.2 KB
/
RNSqlite2.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
#import "RNSqlite2.h"
#import "sqlite3.h"
@implementation RNSqlite2
@synthesize cachedDatabases;
@synthesize dbQueues;
- (dispatch_queue_t)methodQueue
{
return dispatch_queue_create("dog.craftz.sqlite2", DISPATCH_QUEUE_SERIAL);
}
RCT_EXPORT_MODULE()
+ (BOOL)requiresMainQueueSetup {
return NO;
}
- (id) init {
self = [super init];
if (self!=nil) {
[self pluginInitialize];
}
return self;
}
-(void)pluginInitialize {
logDebug(@"pluginInitialize()");
cachedDatabases = [NSMutableDictionary dictionaryWithCapacity:0];
dbQueues = [NSMutableDictionary dictionaryWithCapacity:0];
NSString *dbDir = [self getDatabaseDir];
// create "NoCloud" if it doesn't exist
[[NSFileManager defaultManager] createDirectoryAtPath: dbDir
withIntermediateDirectories: NO
attributes: nil
error: nil];
// make it non-syncable to iCloud
NSURL *url = [ NSURL fileURLWithPath: dbDir];
[url setResourceValue: [NSNumber numberWithBool: YES]
forKey: NSURLIsExcludedFromBackupKey
error: nil];
}
- (dispatch_queue_t)getDatabaseQueue:(NSString *)dbName {
dispatch_queue_t q = [dbQueues objectForKey:dbName];
if (q == nil) {
q = dispatch_queue_create([[@"dog.craftz.sqlite2." stringByAppendingString:dbName] UTF8String], DISPATCH_QUEUE_SERIAL);
[dbQueues setObject:q forKey:dbName];
}
return q;
}
-(NSString*) getDatabaseDir {
NSString *libDir = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex: 0];
return [libDir stringByAppendingPathComponent:@"NoCloud"];
}
-(id) getPathForDB:(NSString *)dbName {
// special case for in-memory databases
if ([dbName isEqualToString:@":memory:"]) {
return dbName;
}
// otherwise use this location, which matches the old SQLite Plugin behavior
// and ensures no iCloud backup, which is apparently disallowed for SQLite dbs
return [[self getDatabaseDir] stringByAppendingPathComponent: dbName];
}
-(NSValue*)openDatabase: (NSString*)dbName {
logDebug(@"opening DB: %@", dbName);
NSValue *cachedDB = [cachedDatabases objectForKey:dbName];
if (cachedDB == nil) {
logDebug(@"opening new db");
NSString *fullDbPath = [self getPathForDB: dbName];
logDebug(@"full path: %@", fullDbPath);
const char *sqliteName = [fullDbPath UTF8String];
sqlite3 *db;
if (sqlite3_open(sqliteName, &db) != SQLITE_OK) {
logDebug(@"cannot open database: %@", dbName); // shouldn't happen
};
cachedDB = [NSValue valueWithPointer:db];
sqlite3_exec(db, "PRAGMA foreign_keys = ON;", NULL, NULL, NULL);
@synchronized(cachedDatabases) {
[cachedDatabases setObject: cachedDB forKey: dbName];
}
} else {
logDebug(@"re-using existing db");
}
return cachedDB;
}
RCT_EXPORT_METHOD(exec:(NSString *)dbName
queries: (NSArray *)sqlQueries
readOnly:(BOOL)readOnly
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) {
logDebug(@"exec()");
logDebug(@"queries: %@", sqlQueries);
logDebug(@"readOnly: %@", readOnly ? @"true" : @"false");
dispatch_queue_t q = [self getDatabaseQueue:dbName];
dispatch_async(q, ^{
long numQueries = [sqlQueries count];
NSArray *sqlResult;
int i;
logDebug(@"dbName: %@", dbName);
NSValue *databasePointer = [self openDatabase:dbName];
sqlite3 *db = [databasePointer pointerValue];
NSMutableArray *sqlResults = [NSMutableArray arrayWithCapacity:numQueries];
// execute queries
for (i = 0; i < numQueries; i++) {
NSArray *sqlQueryObject = [sqlQueries objectAtIndex:i];
NSString *sql = [sqlQueryObject objectAtIndex:0];
NSArray *sqlArgs = [sqlQueryObject objectAtIndex:1];
logDebug(@"sql: %@", sql);
logDebug(@"sqlArgs: %@", sqlArgs);
sqlResult = [self executeSql:sql withSqlArgs:sqlArgs withDb: db withReadOnly: readOnly];
logDebug(@"sqlResult: %@", sqlResult);
[sqlResults addObject:sqlResult];
}
resolve(sqlResults);
});
}
-(NSObject*) getSqlValueForColumnType: (int)columnType withStatement: (sqlite3_stmt*)statement withIndex: (int)i {
switch (columnType) {
case SQLITE_INTEGER:
return [NSNumber numberWithLongLong: sqlite3_column_int64(statement, i)];
case SQLITE_FLOAT:
return [NSNumber numberWithDouble: sqlite3_column_double(statement, i)];
case SQLITE_BLOB:
case SQLITE_TEXT: {
NSString* value = [[NSString alloc] initWithBytes:(char *)sqlite3_column_text(statement, i)
length:sqlite3_column_bytes(statement, i)
encoding:NSUTF8StringEncoding];
return [RNSqlite2 escapeBlob:value];
}
}
return [NSNull null];
}
-(NSArray*) executeSql: (NSString*)sql
withSqlArgs: (NSArray*)sqlArgs
withDb: (sqlite3*)db
withReadOnly: (BOOL)readOnly {
logDebug(@"executeSql sql: %@", sql);
NSString *error = nil;
sqlite3_stmt *statement;
NSMutableArray *resultRows = [NSMutableArray arrayWithCapacity:0];
NSMutableArray *entry;
long insertId = 0;
int rowsAffected = 0;
int i;
// compile the statement, throw an error if necessary
logDebug(@"sqlite3_prepare_v2");
if (sqlite3_prepare_v2(db, [sql UTF8String], -1, &statement, NULL) != SQLITE_OK) {
error = [RNSqlite2 convertSQLiteErrorToString:db];
logDebug(@"prepare error!");
logDebug(@"error: %@", error);
return @[error];
}
bool queryIsReadOnly = sqlite3_stmt_readonly(statement);
if (readOnly && !queryIsReadOnly) {
error = [NSString stringWithFormat:@"could not prepare %@", sql];
return @[error];
}
// bind any arguments
if (sqlArgs != nil) {
for (i = 0; i < sqlArgs.count; i++) {
[self bindStatement:statement withArg:[sqlArgs objectAtIndex:i] atIndex:(i + 1)];
}
}
int previousRowsAffected = 0;
if (!queryIsReadOnly) {
// calculate the total changes in order to diff later
previousRowsAffected = sqlite3_total_changes(db);
}
// iterate through sql results
int columnCount = 0;
NSMutableArray *columnNames = [NSMutableArray arrayWithCapacity:0];
NSString *columnName;
int columnType;
BOOL fetchedColumns = NO;
int result;
NSObject *columnValue;
BOOL hasMore = YES;
while (hasMore) {
logDebug(@"sqlite3_step");
result = sqlite3_step (statement);
switch (result) {
case SQLITE_ROW:
if (!fetchedColumns) {
// get all column names once at the beginning
columnCount = sqlite3_column_count(statement);
for (i = 0; i < columnCount; i++) {
columnName = [NSString stringWithFormat:@"%s", sqlite3_column_name(statement, i)];
[columnNames addObject:columnName];
}
fetchedColumns = YES;
}
entry = [NSMutableArray arrayWithCapacity:columnCount];
for (i = 0; i < columnCount; i++) {
columnType = sqlite3_column_type(statement, i);
columnValue = [self getSqlValueForColumnType:columnType withStatement:statement withIndex: i];
[entry addObject:columnValue];
}
[resultRows addObject:entry];
break;
case SQLITE_DONE:
hasMore = NO;
break;
default:
error = [RNSqlite2 convertSQLiteErrorToString:db];
hasMore = NO;
break;
}
}
if (!queryIsReadOnly) {
rowsAffected = (sqlite3_total_changes(db) - previousRowsAffected);
if (rowsAffected > 0) {
insertId = sqlite3_last_insert_rowid(db);
}
}
logDebug(@"sqlite3_finalize");
sqlite3_finalize (statement);
if (error) {
return @[error];
}
return @[
[NSNull null],
[NSNumber numberWithLong:insertId],
[NSNumber numberWithInt:rowsAffected],
columnNames,
resultRows
];
}
-(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 = [RNSqlite2 unescapeBlob:(NSString *)arg];
} else {
stringArg = [arg description]; // convert to text
}
NSData *data = [stringArg dataUsingEncoding:NSUTF8StringEncoding];
sqlite3_bind_text(statement, argIndex, data.bytes, (int)data.length, SQLITE_TRANSIENT);
}
}
-(void)dealloc {
[self disposeDatabaseCaches];
}
-(void)disposeDatabaseCaches {
int i;
NSArray *keys = [cachedDatabases allKeys];
NSValue *pointer;
NSString *key;
sqlite3 *db;
for (i = 0; i < [keys count]; i++) {
key = [keys objectAtIndex:i];
pointer = [cachedDatabases objectForKey:key];
db = [pointer pointerValue];
sqlite3_close (db);
}
}
+(NSString *)convertSQLiteErrorToString:(struct sqlite3 *)db {
int code = sqlite3_errcode(db);
const char *cMessage = sqlite3_errmsg(db);
NSString *message = [[NSString alloc] initWithUTF8String: cMessage];
return [NSString stringWithFormat:@"Error code %i: %@", code, message];
}
+(NSString *)unescapeBlob:(NSString*)str {
return [[[str stringByReplacingOccurrencesOfString:@"\x01\x01" withString:@"\x00"]
stringByReplacingOccurrencesOfString:@"\x01\x02" withString:@"\x01"]
stringByReplacingOccurrencesOfString:@"\x02\x02" withString:@"\x02"];
}
+(NSString *)escapeBlob:(NSString*)str {
return [[[str stringByReplacingOccurrencesOfString:@"\x02" withString:@"\x02\x02"]
stringByReplacingOccurrencesOfString:@"\x01" withString:@"\x01\x02"]
stringByReplacingOccurrencesOfString:@"\x00" withString:@"\x01\x01"];
}
@end