-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
SQLiteModule.java
304 lines (273 loc) · 9.99 KB
/
SQLiteModule.java
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
// Copyright 2015-present 650 Industries. All rights reserved.
package versioned.host.exp.exponent.modules.api;
import com.facebook.react.bridge.NativeArray;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.WritableNativeArray;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.Handler;
import android.os.HandlerThread;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import host.exp.exponent.utils.ExpFileUtils;
import host.exp.exponent.utils.ScopedContext;
public class SQLiteModule extends ReactContextBaseJavaModule {
private static final boolean DEBUG_MODE = false;
private static final String TAG = SQLiteModule.class.getSimpleName();
private static final Object[][] EMPTY_ROWS = new Object[][]{};
private static final String[] EMPTY_COLUMNS = new String[]{};
private static final SQLitePluginResult EMPTY_RESULT = new SQLitePluginResult(EMPTY_ROWS, EMPTY_COLUMNS, 0, 0, null);
private static final Map<String, SQLiteDatabase> DATABASES = new HashMap<String, SQLiteDatabase>();
private ScopedContext mScopedContext;
public SQLiteModule(ReactApplicationContext reactContext, ScopedContext scopedContext) {
super(reactContext);
mScopedContext = scopedContext;
}
@Override
public String getName() {
return "ExponentSQLite";
}
private Handler createBackgroundHandler() {
HandlerThread thread = new HandlerThread("SQLitePlugin BG Thread");
thread.start();
return new Handler(thread.getLooper());
}
@ReactMethod
public void exec(String dbName, ReadableArray queries, Boolean readOnly, Promise promise) {
try {
int numQueries = queries.size();
SQLitePluginResult[] results = new SQLitePluginResult[numQueries];
SQLiteDatabase db = getDatabase(dbName);
for (int i = 0; i < numQueries; i++) {
ReadableArray sqlQuery = queries.getArray(i);
String sql = sqlQuery.getString(0);
String[] bindArgs = jsonArrayToStringArray(sqlQuery.getString(1));
try {
if (isSelect(sql)) {
results[i] = doSelectInBackgroundAndPossiblyThrow(sql, bindArgs, db);
} else { // update/insert/delete
if (readOnly) {
results[i] = new SQLitePluginResult(EMPTY_ROWS, EMPTY_COLUMNS, 0, 0, new ReadOnlyException());
} else {
results[i] = doUpdateInBackgroundAndPossiblyThrow(sql, bindArgs, db);
}
}
} catch (Throwable e) {
if (DEBUG_MODE) {
e.printStackTrace();
}
results[i] = new SQLitePluginResult(EMPTY_ROWS, EMPTY_COLUMNS, 0, 0, e);
}
}
NativeArray data = pluginResultsToPrimitiveData(results);
promise.resolve(data);
} catch (Exception e) {
promise.reject("SQLiteError", e);
}
}
// do a update/delete/insert operation
private SQLitePluginResult doUpdateInBackgroundAndPossiblyThrow(String sql, String[] bindArgs,
SQLiteDatabase db) {
SQLiteStatement statement = null;
try {
statement = db.compileStatement(sql);
if (bindArgs != null) {
statement.bindAllArgsAsStrings(bindArgs);
}
if (isInsert(sql)) {
long insertId = statement.executeInsert();
int rowsAffected = insertId >= 0 ? 1 : 0;
return new SQLitePluginResult(EMPTY_ROWS, EMPTY_COLUMNS, rowsAffected, insertId, null);
} else if (isDelete(sql) || isUpdate(sql)) {
int rowsAffected = statement.executeUpdateDelete();
return new SQLitePluginResult(EMPTY_ROWS, EMPTY_COLUMNS, rowsAffected, 0, null);
} else {
// in this case, we don't need rowsAffected or insertId, so we can have a slight
// perf boost by just executing the query
statement.execute();
return EMPTY_RESULT;
}
} finally {
if (statement != null) {
statement.close();
}
}
}
// do a select operation
private SQLitePluginResult doSelectInBackgroundAndPossiblyThrow(String sql, String[] bindArgs,
SQLiteDatabase db) {
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, bindArgs);
int numRows = cursor.getCount();
if (numRows == 0) {
return EMPTY_RESULT;
}
int numColumns = cursor.getColumnCount();
Object[][] rows = new Object[numRows][];
String[] columnNames = cursor.getColumnNames();
for (int i = 0; cursor.moveToNext(); i++) {
Object[] row = new Object[numColumns];
for (int j = 0; j < numColumns; j++) {
row[j] = getValueFromCursor(cursor, j, cursor.getType(j));
}
rows[i] = row;
}
return new SQLitePluginResult(rows, columnNames, 0, 0, null);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private Object getValueFromCursor(Cursor cursor, int index, int columnType) {
switch (columnType) {
case Cursor.FIELD_TYPE_FLOAT:
return cursor.getFloat(index);
case Cursor.FIELD_TYPE_INTEGER:
return cursor.getInt(index);
case Cursor.FIELD_TYPE_BLOB:
// convert byte[] to binary string; it's good enough, because
// WebSQL doesn't support blobs anyway
return new String(cursor.getBlob(index));
case Cursor.FIELD_TYPE_STRING:
return cursor.getString(index);
}
return null;
}
private SQLiteDatabase getDatabase(String name) throws IOException {
SQLiteDatabase database = DATABASES.get(name);
if (database == null) {
if (":memory:".equals(name)) {
database = SQLiteDatabase.openOrCreateDatabase(name, null);
} else {
ExpFileUtils.ensureDirExists(new File(mScopedContext.toScopedPath("SQLite")));
File file = new File(mScopedContext.toScopedPath("SQLite/" + name));
database = SQLiteDatabase.openOrCreateDatabase(file, null);
}
DATABASES.put(name, database);
}
return database;
}
private static NativeArray pluginResultsToPrimitiveData(SQLitePluginResult[] results) {
WritableNativeArray list = new WritableNativeArray();
for (int i = 0; i < results.length; i++) {
SQLitePluginResult result = results[i];
WritableNativeArray arr = convertPluginResultToArray(result);
list.pushArray(arr);
}
return list;
}
private static WritableNativeArray convertPluginResultToArray(SQLitePluginResult result) {
WritableNativeArray data = new WritableNativeArray();
if (result.error != null) {
data.pushString(result.error.getMessage());
} else {
data.pushNull();
}
data.pushInt((int) result.insertId);
data.pushInt(result.rowsAffected);
// column names
WritableNativeArray columnNames = new WritableNativeArray();
for (int i = 0; i < result.columns.length; i++) {
columnNames.pushString(result.columns[i]);
}
data.pushArray(columnNames);
// rows
WritableNativeArray rows = new WritableNativeArray();
for (int i = 0; i < result.rows.length; i++) {
Object[] values = result.rows[i];
// row content
WritableNativeArray rowContent = new WritableNativeArray();
for (int j = 0; j < values.length; j++) {
Object value = values[j];
if (value == null) {
rowContent.pushNull();
} else if (value instanceof String) {
rowContent.pushString((String)value);
} else if (value instanceof Boolean) {
rowContent.pushBoolean((Boolean)value);
} else {
Number v = (Number)value;
rowContent.pushDouble(v.doubleValue());
}
}
rows.pushArray(rowContent);
}
data.pushArray(rows);
return data;
}
private static boolean isSelect(String str) {
return startsWithCaseInsensitive(str, "select");
}
private static boolean isInsert(String str) {
return startsWithCaseInsensitive(str, "insert");
}
private static boolean isUpdate(String str) {
return startsWithCaseInsensitive(str, "update");
}
private static boolean isDelete(String str) {
return startsWithCaseInsensitive(str, "delete");
}
// identify an "insert"/"select" query more efficiently than with a Pattern
private static boolean startsWithCaseInsensitive(String str, String substr) {
int i = -1;
int len = str.length();
while (++i < len) {
char ch = str.charAt(i);
if (!Character.isWhitespace(ch)) {
break;
}
}
int j = -1;
int substrLen = substr.length();
while (++j < substrLen) {
if (j + i >= len) {
return false;
}
char ch = str.charAt(j + i);
if (Character.toLowerCase(ch) != substr.charAt(j)) {
return false;
}
}
return true;
}
private static String[] jsonArrayToStringArray(String jsonArray) throws JSONException {
JSONArray array = new JSONArray(jsonArray);
int len = array.length();
String[] res = new String[len];
for (int i = 0; i < len; i++) {
res[i] = array.getString(i);
}
return res;
}
private static class SQLitePluginResult {
public final Object[][] rows;
public final String[] columns;
public final int rowsAffected;
public final long insertId;
public final Throwable error;
public SQLitePluginResult(Object[][] rows, String[] columns,
int rowsAffected, long insertId, Throwable error) {
this.rows = rows;
this.columns = columns;
this.rowsAffected = rowsAffected;
this.insertId = insertId;
this.error = error;
}
}
private static class ReadOnlyException extends Exception {
public ReadOnlyException() {
super("could not prepare statement (23 not authorized)");
}
}
}