/
SQLCipher.java
341 lines (327 loc) · 11.7 KB
/
SQLCipher.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
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
/*
* Copyright 2010 - 2020 Anywhere Software (www.b4x.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package anyhwheresoftware.b4a.objects.sqlcipher;
//don't forget the native libs in the additional folder!!!
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import net.sqlcipher.DatabaseUtils;
import net.sqlcipher.database.SQLiteDatabase;
import net.sqlcipher.database.SQLiteStatement;
import android.content.Context;
import android.database.Cursor;
import anywheresoftware.b4a.AbsObjectWrapper;
import anywheresoftware.b4a.BA;
import anywheresoftware.b4a.BA.DependsOn;
import anywheresoftware.b4a.BA.ShortName;
import anywheresoftware.b4a.BA.Version;
import anywheresoftware.b4a.keywords.Common;
import anywheresoftware.b4a.objects.collections.List;
import anywheresoftware.b4a.objects.streams.File;
import anywheresoftware.b4a.sql.SQL;
/**
* SQLCipher type is an extension to SQL which supports encryption.
*See the <link>tutorial|http://www.basic4ppc.com/forum/basic4android-getting-started-tutorials/14965-android-database-encryption-sqlcipher-library.html</link> for more information.
*/
@ShortName("SQLCipher")
@Version(1.70f)
@DependsOn(values={"android-database-sqlcipher-4.5.4.aar", "sqlite-2.4.0.aar"})
public class SQLCipher extends SQL{
private SQLiteDatabase db;
private volatile ArrayList<Object[]> nonQueryStatementsList = new ArrayList<Object[]>();
private static SQLCipher cloneMe(SQLCipher sql) {
SQLCipher ret = new SQLCipher();
ret.db = sql.db;
ret.nonQueryStatementsList = sql.nonQueryStatementsList;
return ret;
}
/**
* Opens the database file. A new database will be created if it does not exist and CreateIfNecessary is true.
*/
public void Initialize(String Dir, String FileName, boolean CreateIfNecessary, String Password, String Unused) throws IOException, InterruptedException {
SQLiteDatabase.loadLibs(BA.applicationContext);
db = SQLiteDatabase.openDatabase(new java.io.File(Dir, FileName).toString(), Password, null,
(CreateIfNecessary ? SQLiteDatabase.CREATE_IF_NECESSARY : 0) | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
}
private void checkNull() {
if (db == null)
throw new RuntimeException("Object should first be initialized.");
}
/**
* Tests whether the database is initialized and opened.
*/
@Override
public boolean IsInitialized() {
if (db == null)
return false;
return db.isOpen();
}
/**
* Executes a single non query SQL statement.
*Example:<code>
*SQL1.ExecNonQuery("CREATE TABLE table1 (col1 TEXT , col2 INTEGER, col3 INTEGER)")</code>
*If you plan to do many "writing" queries one after another, then you should consider using BeginTransaction / EndTransaction.
*It will execute significantly faster.
*/
@Override
public void ExecNonQuery(String Statement) {
checkNull();
db.execSQL(Statement);
}
/**
* Executes a single non query SQL statement.
*The statement can include question marks which will be replaced by the items in the given list.
*Note that Basic4android converts arrays to lists implicitly.
*The values in the list should be strings, numbers or bytes arrays.
*Example:<code>
*SQL1.ExecNonQuery2("INSERT INTO table1 VALUES (?, ?, 0)", Array As Object("some text", 2))</code>
*/
@Override
public void ExecNonQuery2(String Statement, List Args) {
checkNull();
SQLiteStatement s = db.compileStatement(Statement);
try {
int numArgs = Args.getSize();
for (int i = 0; i < numArgs; i++) {
DatabaseUtils.bindObjectToProgram(s, i + 1, Args.Get(i));
}
s.execute();
} finally {
s.close();
}
}
/**
* Adds a non-query statement to the batch of statements.
*The statements are (asynchronously) executed when you call ExecNonQueryBatch.
*Args parameter can be Null if it is not needed.
*Example:<code>
*For i = 1 To 1000
* sql.AddNonQueryToBatch("INSERT INTO table1 VALUES (?)", Array(Rnd(0, 100000)))
*Next
*Dim SenderFilter As Object = sql.ExecNonQueryBatch("SQL")
*Wait For (SenderFilter) SQL_NonQueryComplete (Success As Boolean)
*Log("NonQuery: " & Success)</code>
*/
@Override
public void AddNonQueryToBatch(String Statement, List Args) {
nonQueryStatementsList.add(new Object[] {Statement, Args});
}
/**
* Asynchronously executes a batch of non-query statements (such as INSERT).
*The NonQueryComplete event is raised after the statements are completed.
*You should call AddNonQueryToBatch one or more times before calling this method to add statements to the batch.
*Note that this method internally begins and ends a transaction.
*Returns an object that can be used as the sender filter for Wait For calls.
*Example:<code>
*For i = 1 To 1000
* sql.AddNonQueryToBatch("INSERT INTO table1 VALUES (?)", Array(Rnd(0, 100000)))
*Next
*Dim SenderFilter As Object = sql.ExecNonQueryBatch("SQL")
*Wait For (SenderFilter) SQL_NonQueryComplete (Success As Boolean)
*Log("NonQuery: " & Success)</code>
*/
@Override
public Object ExecNonQueryBatch(final BA ba, final String EventName) {
final ArrayList<Object[]> myList = nonQueryStatementsList;
nonQueryStatementsList = new ArrayList<Object[]>();
final SQLCipher ret = SQLCipher.cloneMe(this);
BA.submitRunnable(new Runnable() {
@Override
public void run() {
synchronized (db) {
try {
BeginTransaction();
for (Object[] o: myList) {
ExecNonQuery2((String)o[0], (List)o[1]);
}
TransactionSuccessful();
EndTransaction();
ba.raiseEventFromDifferentThread(ret, SQLCipher.this, 0, EventName.toLowerCase(BA.cul) + "_nonquerycomplete",
true, new Object[] {true});
} catch (Exception e) {
EndTransaction();
e.printStackTrace();
ba.setLastException(e);
ba.raiseEventFromDifferentThread(ret, SQLCipher.this, 0, EventName.toLowerCase(BA.cul) + "_nonquerycomplete",
true, new Object[] {false});
}
}
}
}, this, 1);
return ret;
}
/**
* Asynchronously executes the given query. The QueryComplete event will be raised when the results are ready.
*Note that ResultSet extends Cursor. You can use Cursor if preferred.
*Returns an object that can be used as the sender filter for Wait For calls.
*Example:<code>
*Dim SenderFilter As Object = sql.ExecQueryAsync("SQL", "SELECT * FROM table1", Null)
*Wait For (SenderFilter) SQL_QueryComplete (Success As Boolean, rs As ResultSet)
*If Success Then
* Do While rs.NextRow
* Log(rs.GetInt2(0))
* Loop
* rs.Close
*Else
* Log(LastException)
*End If</code>
*/
@Override
public Object ExecQueryAsync(final BA ba, final String EventName, final String Query, final List Args) {
final SQLCipher ret = SQLCipher.cloneMe(this);
ba.submitRunnable(new Runnable() {
@Override
public void run() {
synchronized (db) {
try {
String[] s = null;
if (Args != null && Args.IsInitialized()) {
s = new String[Args.getSize()];
for (int i = 0;i < s.length;i++) {
Object o = Args.Get(i);
s[i] = o == null ? null : String.valueOf(o);
}
}
Cursor c = ExecQuery2(Query, s);
ba.raiseEventFromDifferentThread(ret, SQLCipher.this, 0, EventName.toLowerCase(BA.cul) + "_querycomplete",
true, new Object[] {true, AbsObjectWrapper.ConvertToWrapper(new ResultSetWrapper(), c)});
} catch (Exception e) {
e.printStackTrace();
ba.setLastException(e);
ba.raiseEventFromDifferentThread(ret, SQLCipher.this, 0, EventName.toLowerCase(BA.cul) + "_querycomplete",
true, new Object[] {false, AbsObjectWrapper.ConvertToWrapper(new ResultSetWrapper(), null)});
}
}
}
}, this, 0);
return ret;
}
/**
* Executes the query and returns a cursor which is used to go over the results.
*Example:<code>
*Dim Cursor As Cursor
*Cursor = SQL1.ExecQuery("SELECT col1, col2 FROM table1")
*For i = 0 To Cursor.RowCount - 1
* Cursor.Position = i
* Log(Cursor.GetString("col1"))
* Log(Cursor.GetInt("col2"))
*Next</code>
*/
@Override
public Cursor ExecQuery(String Query) {
checkNull();
return ExecQuery2(Query, null);
}
/**
* Executes the query and returns a cursor which is used to go over the results.
*The query can include question marks which will be replaced with the values in the array.
*Example:<code>
*Dim Cursor As Cursor
*Cursor = sql1.ExecQuery2("SELECT col1 FROM table1 WHERE col3 = ?", Array As String(22))</code>
*SQLite will try to convert the string values based on the columns types.
*/
@Override
public Cursor ExecQuery2(String Query, String[] StringArgs) {
checkNull();
return db.rawQuery(Query, StringArgs);
}
/**
* Executes the query and returns the value in the first column and the first row (in the result set).
*Returns Null if no results were found.
*Example:<code>
*Dim NumberOfMatches As Int
*NumberOfMatches = SQL1.ExecQuerySingleResult("SELECT count(*) FROM table1 WHERE col2 > 300")</code>
*/
@Override
public String ExecQuerySingleResult(String Query) {
return ExecQuerySingleResult2(Query, null);
}
/**
* Executes the query and returns the value in the first column and the first row (in the result set).
*Returns Null if no results were found.
*Example:<code>
*Dim NumberOfMatches As Int
*NumberOfMatches = SQL1.ExecQuerySingleResult2("SELECT count(*) FROM table1 WHERE col2 > ?", Array As String(300))</code>
*/
@Override
public String ExecQuerySingleResult2(String Query, String[] StringArgs) {
checkNull();
Cursor cursor = db.rawQuery(Query, StringArgs);
try {
if (!cursor.moveToFirst())
return null;
if (cursor.getColumnCount() == 0)
return null;
return cursor.getString(0);
} finally {
cursor.close();
}
}
/**
* Begins a transaction. A transaction is a set of multiple "writing" statements that are atomically committed,
*hence all changes will be made or no changes will be made.
*As a side effect those statements will be executed significantly faster (in the default case a transaction is implicitly created for
*each statement).
*It is very important to handle transaction carefully and close them.
*The transaction is considered successful only if TransactionSuccessful is called. Otherwise no changes will be made.
*Typical usage:<code>
*SQL1.BeginTransaction
*Try
* 'block of statements like:
* For i = 1 to 1000
* SQL1.ExecNonQuery("INSERT INTO table1 VALUES(...)
* Next
* SQL1.TransactionSuccessful
*Catch
* Log(LastException.Message) 'no changes will be made
*End Try
*SQL1.EndTransaction</code>
*/
@Override
public void BeginTransaction() {
checkNull();
db.beginTransaction();
}
/**
* Marks the transaction as a successful transaction. No further statements should be executed till calling EndTransaction.
*/
@Override
public void TransactionSuccessful() {
db.setTransactionSuccessful();
}
/**
* Ends the transaction.
*/
@Override
public void EndTransaction() {
db.endTransaction();
}
/**
* Closes the database.
*Does not do anything if the database is not opened or was closed before.
*/
@Override
public void Close() {
if (db != null && db.isOpen())
db.close();
}
}