/
AndroidSqlTemplate.java
369 lines (320 loc) · 12.2 KB
/
AndroidSqlTemplate.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
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
/**
* Licensed to JumpMind Inc under one or more contributor
* license agreements. See the NOTICE file distributed
* with this work for additional information regarding
* copyright ownership. JumpMind Inc licenses this file
* to you under the GNU General Public License, version 3.0 (GPLv3)
* (the "License"); you may not use this file except in compliance
* with the License.
*
* You should have received a copy of the GNU General Public License,
* version 3.0 (GPLv3) along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*
* 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 org.jumpmind.symmetric.android;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.NotImplementedException;
import org.jumpmind.db.model.TypeMap;
import org.jumpmind.db.sql.AbstractSqlTemplate;
import org.jumpmind.db.sql.ISqlReadCursor;
import org.jumpmind.db.sql.ISqlResultsListener;
import org.jumpmind.db.sql.ISqlRowMapper;
import org.jumpmind.db.sql.ISqlStatementSource;
import org.jumpmind.db.sql.ISqlTransaction;
import org.jumpmind.db.sql.ListSqlStatementSource;
import org.jumpmind.db.sql.Row;
import org.jumpmind.db.sql.UniqueKeyException;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class AndroidSqlTemplate extends AbstractSqlTemplate {
protected SQLiteOpenHelper databaseHelper;
protected Context androidContext;
public AndroidSqlTemplate(SQLiteOpenHelper databaseHelper, Context androidContext) {
this.databaseHelper = databaseHelper;
this.androidContext = androidContext;
}
public SQLiteOpenHelper getDatabaseHelper() {
return databaseHelper;
}
public byte[] queryForBlob(String sql, int jdbcTypeCode, String jdbcTypeName, Object... params) {
return queryForBlob(sql, params);
}
public byte[] queryForBlob(String sql, Object... params) {
return queryForObject(sql, byte[].class, params);
}
@Override
public String queryForClob(String sql, Object... args) {
return queryForClob(sql, Types.CLOB, TypeMap.CLOB, args);
}
public String queryForClob(String sql, int jdbcTypeCode, String jdbcTypeName, Object... params) {
return queryForString(sql, params);
}
public <T> T queryForObject(String sql, Class<T> clazz, Object... params) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
try {
return queryForObject(database, sql, clazz, params);
} catch (Exception ex) {
throw translate(ex);
} finally {
close(database);
}
}
protected <T> T queryForObject(SQLiteDatabase database, String sql, Class<T> clazz,
Object... params) {
Cursor cursor = null;
try {
T result = null;
cursor = database.rawQuery(sql, toStringArray(params));
if (cursor.moveToFirst()) {
result = get(cursor, clazz, 0);
}
return result;
} catch (Exception ex) {
throw translate(ex);
} finally {
close(cursor);
}
}
public Map<String, Object> queryForMap(final String sql, final Object... args) {
return queryForObject(sql, new ISqlRowMapper<Map<String, Object>>() {
public Map<String, Object> mapRow(Row rs) {
return rs;
}
}, args);
}
public <T> ISqlReadCursor<T> queryForCursor(String sql, ISqlRowMapper<T> mapper,
Object[] params, int[] types) {
return new AndroidSqlReadCursor<T>(sql, toStringArray(params), mapper, this);
}
public int update(boolean autoCommit, boolean failOnError, int commitRate,
ISqlResultsListener resultsListener, String... sql) {
return this.update(autoCommit, failOnError, true, true,
commitRate, resultsListener, new ListSqlStatementSource(sql));
}
public int update(final boolean autoCommit, final boolean failOnError, boolean failOnDrops,
boolean failOnSequenceCreate, final int commitRate, final ISqlResultsListener resultsListener, final ISqlStatementSource source) {
int row = 0;
SQLiteDatabase database = this.databaseHelper.getWritableDatabase();
String currentStatement = null;
try {
if (!autoCommit) {
database.beginTransaction();
}
for (String statement = source.readSqlStatement(); statement != null; statement = source
.readSqlStatement()) {
currentStatement = statement;
update(statement);
row++;
if (!autoCommit && row % commitRate == 0) {
database.setTransactionSuccessful();
database.endTransaction();
database.beginTransaction();
}
if (resultsListener != null) {
resultsListener.sqlApplied(statement, row, 0, row);
}
}
if (!autoCommit) {
database.setTransactionSuccessful();
}
} catch (RuntimeException ex) {
if (resultsListener != null) {
resultsListener.sqlErrored(currentStatement, translate(currentStatement, ex), row, false, false);
}
throw ex;
} finally {
if (!autoCommit) {
database.endTransaction();
}
close(database);
}
return row;
}
public int update(boolean autoCommit, boolean failOnError, int commitRate, String... sql) {
return update(autoCommit, failOnError, commitRate, (ISqlResultsListener) null, sql);
}
public int update(String sql, Object[] values, int[] types) {
SQLiteDatabase database = this.databaseHelper.getWritableDatabase();
try {
return update(database, sql, values, types);
} finally {
close(database);
}
}
protected int update(SQLiteDatabase database, String sql, Object[] values, int[] types) {
try {
if (values != null) {
database.execSQL(sql, toStringArray(values));
} else {
database.execSQL(sql);
}
return queryForObject(database, "select changes()", Integer.class);
} catch (Exception ex) {
throw translate(ex);
}
}
/**
* Translate an array of {@link Object} to an array of {@link String} by
* creating a new array of {@link String} and putting each of the objects
* into the array by calling {@link Object#toString()}
*
* @param orig
* the original array
* @return a newly constructed string array
*/
public static String[] toStringArray(Object[] orig) {
String[] array = null;
if (orig != null) {
array = new String[orig.length];
for (int i = 0; i < orig.length; i++) {
if (orig[i] != null) {
if (orig[i] instanceof Date) {
array[i] = new Timestamp(((Date) orig[i]).getTime()).toString();
} else {
array[i] = orig[i].toString();
}
}
}
}
return array;
}
public void testConnection() {
SQLiteDatabase database = this.databaseHelper.getWritableDatabase();
close(database);
}
public boolean isUniqueKeyViolation(Throwable ex) {
return ex instanceof SQLiteConstraintException || ex instanceof UniqueKeyException;
}
public boolean isForeignKeyViolation(Throwable ex) {
return false;
}
@Override
public ISqlTransaction startSqlTransaction(boolean autoCommit) {
return new AndroidSqlTransaction(this, autoCommit);
}
public ISqlTransaction startSqlTransaction() {
return startSqlTransaction(false);
}
public int getDatabaseMajorVersion() {
SQLiteDatabase database = this.databaseHelper.getWritableDatabase();
try {
return database.getVersion();
} catch (Exception ex) {
throw translate(ex);
} finally {
close(database);
}
}
public int getDatabaseMinorVersion() {
return 0;
}
public String getDatabaseProductName() {
return "sqlite";
}
public String getDatabaseProductVersion() {
return Integer.toString(getDatabaseMajorVersion());
}
public String getDriverName() {
return "android";
}
public String getDriverVersion() {
try {
return androidContext.getPackageManager().getPackageInfo(
androidContext.getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
return "?";
}
}
public Set<String> getSqlKeywords() {
throw new NotImplementedException();
}
public boolean supportsGetGeneratedKeys() {
return false;
}
public boolean isStoresUpperCaseIdentifiers() {
return false;
}
public boolean isStoresLowerCaseIdentifiers() {
return true;
}
public boolean isStoresMixedCaseQuotedIdentifiers() {
return false;
}
public long insertWithGeneratedKey(String sql, String column, String sequenceName,
Object[] params, int[] types) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
try {
return insertWithGeneratedKey(database, sql, column, sequenceName, params, types);
} finally {
close(database);
}
}
protected long insertWithGeneratedKey(SQLiteDatabase database, String sql, String column,
String sequenceName, Object[] params, int[] types) {
int updateCount = update(database, sql, params, types);
if (updateCount > 0) {
long rowId = queryForObject(database, "SELECT last_insert_rowid()", Integer.class);
return rowId;
} else {
return -1;
}
}
protected void close(SQLiteDatabase database) {
}
protected void close(Cursor cursor) {
try {
if (cursor != null) {
cursor.close();
}
} catch (Exception ex) {
}
}
@SuppressWarnings("unchecked")
protected <T> T get(Cursor cursor, Class<T> clazz, int columnIndex) {
Object result = null;
if (clazz.equals(String.class)) {
result = (String) cursor.getString(columnIndex);
} else if (clazz.equals(Integer.class)) {
result = (Integer) cursor.getInt(columnIndex);
} else if (clazz.equals(Integer.class)) {
result = (Double) cursor.getDouble(columnIndex);
} else if (clazz.equals(Float.class)) {
result = (Float) cursor.getFloat(columnIndex);
} else if (clazz.equals(Long.class)) {
result = (Long) cursor.getLong(columnIndex);
} else if (clazz.equals(Date.class) || clazz.equals(Timestamp.class)) {
String dateString = cursor.getString(columnIndex);
if (dateString.contains("-")) {
result = Timestamp.valueOf(dateString);
} else {
result = new Timestamp(Long.parseLong(dateString));
}
} else if (clazz.equals(Short.class)) {
result = (Short) cursor.getShort(columnIndex);
} else if (clazz.equals(byte[].class)) {
result = (byte[]) cursor.getBlob(columnIndex);
} else {
throw new IllegalArgumentException("Unsupported class: " + clazz.getName());
}
return (T) result;
}
@Override
public boolean isDataTruncationViolation(Throwable ex) {
return false;
}
}