-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathSQLiteAssetHelper.java
More file actions
520 lines (455 loc) · 19.6 KB
/
SQLiteAssetHelper.java
File metadata and controls
520 lines (455 loc) · 19.6 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
/*
* Copyright (C) 2011 readyState Software Ltd, 2007 The Android Open Source Project
*
* 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 com.jaus.albertogiunta.justintrain_oraritreni.db.sqliteAsset;
import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.zip.ZipInputStream;
/**
* A helper class to manage database creation and version management using
* an application's raw asset files.
*
* This class provides developers with a simple way to ship their Android app
* with an existing SQLite database (which may be pre-populated with data) and
* to manage its initial creation and any upgrades required with subsequent
* version releases.
*
* <p>This class makes it easy for {@link android.content.ContentProvider}
* implementations to defer opening and upgrading the database until first use,
* to avoid blocking application startup with long-running database upgrades.
*
* <p>For examples see <a href="https://github.com/jgilfelt/android-sqlite-asset-helper">
* https://github.com/jgilfelt/android-sqlite-asset-helper</a>
*
* <p class="note"><strong>Note:</strong> this class assumes
* monotonically increasing version numbers for upgrades. Also, there
* is no concept of a database downgrade; installing a new version of
* your app which uses a lower version number than a
* previously-installed version will result in undefined behavior.</p>
*/
public class SQLiteAssetHelper extends SQLiteOpenHelper {
private static final String TAG = SQLiteAssetHelper.class.getSimpleName();
private static final String ASSET_DB_PATH = "databases";
private final Context mContext;
private final String mName;
private final CursorFactory mFactory;
private final int mNewVersion;
private SQLiteDatabase mDatabase = null;
private boolean mIsInitializing = false;
private String mDatabasePath;
private String mAssetPath;
private String mUpgradePathFormat;
private int mForcedUpgradeVersion = 0;
/**
* Create a helper object to create, open, and/or manage a database in
* a specified location.
* This method always returns very quickly. The database is not actually
* created or opened until one of {@link #getWritableDatabase} or
* {@link #getReadableDatabase} is called.
*
* @param context to use to open or create the database
* @param name of the database file
* @param storageDirectory to store the database file upon creation; caller must
* ensure that the specified absolute path is available and can be written to
* @param factory to use for creating cursor objects, or null for the default
* @param version number of the database (starting at 1); if the database is older,
* SQL file(s) contained within the application assets folder will be used to
* upgrade the database
*/
public SQLiteAssetHelper(Context context, String name, String storageDirectory, CursorFactory factory, int version, DatabaseErrorHandler errorHandler) {
super(context, name, factory, version, errorHandler);
if (version < 1) throw new IllegalArgumentException("Version must be >= 1, was " + version);
if (name == null) throw new IllegalArgumentException("Database name cannot be null");
mContext = context;
mName = name;
mFactory = factory;
mNewVersion = version;
mAssetPath = ASSET_DB_PATH + "/" + name;
if (storageDirectory != null) {
mDatabasePath = storageDirectory;
} else {
mDatabasePath = context.getApplicationInfo().dataDir + "/databases";
}
mUpgradePathFormat = ASSET_DB_PATH + "/" + name + "_upgrade_%s-%s.sql";
}
/**
* Create a helper object to create, open, and/or manage a database in
* the application's default private data directory.
* This method always returns very quickly. The database is not actually
* created or opened until one of {@link #getWritableDatabase} or
* {@link #getReadableDatabase} is called.
*
* @param context to use to open or create the database
* @param name of the database file
* @param factory to use for creating cursor objects, or null for the default
* @param version number of the database (starting at 1); if the database is older,
* SQL file(s) contained within the application assets folder will be used to
* upgrade the database
*/
public SQLiteAssetHelper(Context context, String name, CursorFactory factory, int version) {
this(context, name, null, factory, version, null);
}
/**
* Create and/or open a database that will be used for reading and writing.
* The first time this is called, the database will be extracted and copied
* from the application's assets folder.
*
* <p>Once opened successfully, the database is cached, so you can
* call this method every time you need to write to the database.
* (Make sure to call {@link #close} when you no longer need the database.)
* Errors such as bad permissions or a full disk may cause this method
* to fail, but future attempts may succeed if the problem is fixed.</p>
*
* <p class="caution">Database upgrade may take a long time, you
* should not call this method from the application main thread, including
* from {@link android.content.ContentProvider#onCreate ContentProvider.onCreate()}.
*
* @return a read/write database object valid until {@link #close} is called
* @throws SQLiteException if the database cannot be opened for writing
*/
@Override
public synchronized SQLiteDatabase getWritableDatabase() {
if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) {
return mDatabase; // The database is already open for business
}
if (mIsInitializing) {
throw new IllegalStateException("getWritableDatabase called recursively");
}
// If we have a read-only database open, someone could be using it
// (though they shouldn't), which would cause a lock to be held on
// the file, and our attempts to open the database read-write would
// fail waiting for the file lock. To prevent that, we acquire the
// lock on the read-only database, which shuts out other users.
boolean success = false;
SQLiteDatabase db = null;
//if (mDatabase != null) mDatabase.lock();
try {
mIsInitializing = true;
//if (mName == null) {
// db = SQLiteDatabase.create(null);
//} else {
// db = mContext.openOrCreateDatabase(mName, 0, mFactory);
//}
db = createOrOpenDatabase(false);
int version = db.getVersion();
// do force upgrade
if (version != 0 && version < mForcedUpgradeVersion) {
db = createOrOpenDatabase(true);
db.setVersion(mNewVersion);
version = db.getVersion();
}
if (version != mNewVersion) {
db.beginTransaction();
try {
if (version == 0) {
onCreate(db);
} else {
if (version > mNewVersion) {
Log.w(TAG, "Can't downgrade read-only database from version " +
version + " to " + mNewVersion + ": " + db.getPath());
}
onUpgrade(db, version, mNewVersion);
}
db.setVersion(mNewVersion);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
onOpen(db);
success = true;
return db;
} finally {
mIsInitializing = false;
if (success) {
if (mDatabase != null) {
try {
mDatabase.close();
} catch (Exception e) {
}
//mDatabase.unlock();
}
mDatabase = db;
} else {
//if (mDatabase != null) mDatabase.unlock();
if (db != null) db.close();
}
}
}
/**
* Create and/or open a database. This will be the same object returned by
* {@link #getWritableDatabase} unless some problem, such as a full disk,
* requires the database to be opened read-only. In that case, a read-only
* database object will be returned. If the problem is fixed, a future call
* to {@link #getWritableDatabase} may succeed, in which case the read-only
* database object will be closed and the read/write object will be returned
* in the future.
*
* <p class="caution">Like {@link #getWritableDatabase}, this method may
* take a long time to return, so you should not call it from the
* application main thread, including from
* {@link android.content.ContentProvider#onCreate ContentProvider.onCreate()}.
*
* @return a database object valid until {@link #getWritableDatabase}
* or {@link #close} is called.
* @throws SQLiteException if the database cannot be opened
*/
@Override
public synchronized SQLiteDatabase getReadableDatabase() {
if (mDatabase != null && mDatabase.isOpen()) {
return mDatabase; // The database is already open for business
}
if (mIsInitializing) {
throw new IllegalStateException("getReadableDatabase called recursively");
}
try {
return getWritableDatabase();
} catch (SQLiteException e) {
if (mName == null) throw e; // Can't open a temp database read-only!
Log.e(TAG, "Couldn't open " + mName + " for writing (will try read-only):", e);
}
SQLiteDatabase db = null;
try {
mIsInitializing = true;
String path = mContext.getDatabasePath(mName).getPath();
db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY);
if (db.getVersion() != mNewVersion) {
throw new SQLiteException("Can't upgrade read-only database from version " +
db.getVersion() + " to " + mNewVersion + ": " + path);
}
onOpen(db);
Log.w(TAG, "Opened " + mName + " in read-only mode");
mDatabase = db;
return mDatabase;
} finally {
mIsInitializing = false;
if (db != null && db != mDatabase) db.close();
}
}
/**
* Close any open database object.
*/
@Override
public synchronized void close() {
if (mIsInitializing) throw new IllegalStateException("Closed during initialization");
if (mDatabase != null && mDatabase.isOpen()) {
mDatabase.close();
mDatabase = null;
}
}
@Override
public void onConfigure(SQLiteDatabase db) {
// not supported!
}
@Override
public void onCreate(SQLiteDatabase db) {
// do nothing - createOrOpenDatabase() is called in
// getWritableDatabase() to handle database creation.
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database " + mName + " from version " + oldVersion + " to " + newVersion + "...");
ArrayList<String> paths = new ArrayList<String>();
getUpgradeFilePaths(oldVersion, newVersion - 1, newVersion, paths);
if (paths.isEmpty()) {
Log.e(TAG, "no upgrade script path from " + oldVersion + " to " + newVersion);
throw new SQLiteAssetException("no upgrade script path from " + oldVersion + " to " + newVersion);
}
Collections.sort(paths, new VersionComparator());
for (String path : paths) {
try {
Log.w(TAG, "processing upgrade: " + path);
InputStream is = mContext.getAssets().open(path);
String sql = com.jaus.albertogiunta.justintrain_oraritreni.db.sqliteAsset.Utils.convertStreamToString(is);
if (sql != null) {
List<String> cmds = com.jaus.albertogiunta.justintrain_oraritreni.db.sqliteAsset.Utils.splitSqlScript(sql, ';');
for (String cmd : cmds) {
if (cmd.trim().length() > 0) {
db.execSQL(cmd);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
Log.w(TAG, "Successfully upgraded database " + mName + " from version " + oldVersion + " to " + newVersion);
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// not supported!
}
/**
* Bypass the upgrade process (for each increment up to a given version) and simply
* overwrite the existing database with the supplied asset file.
*
* @param version bypass upgrade up to this version number - should never be greater than the
* latest database version.
* @deprecated use {@link #setForcedUpgrade} instead.
*/
@Deprecated
public void setForcedUpgradeVersion(int version) {
setForcedUpgrade(version);
}
/**
* Bypass the upgrade process (for each increment up to a given version) and simply
* overwrite the existing database with the supplied asset file.
*
* @param version bypass upgrade up to this version number - should never be greater than the
* latest database version.
*/
public void setForcedUpgrade(int version) {
mForcedUpgradeVersion = version;
}
/**
* Bypass the upgrade process for every version increment and simply overwrite the existing
* database with the supplied asset file.
*/
public void setForcedUpgrade() {
setForcedUpgrade(mNewVersion);
}
private SQLiteDatabase createOrOpenDatabase(boolean force) throws SQLiteAssetException {
// test for the existence of the db file first and don't attempt open
// to prevent the error trace in log on API 14+
SQLiteDatabase db = null;
File file = new File(mDatabasePath + "/" + mName);
if (file.exists()) {
db = returnDatabase();
}
//SQLiteDatabase db = returnDatabase();
if (db != null) {
// database already exists
if (force) {
Log.w(TAG, "forcing database upgrade!");
copyDatabaseFromAssets();
db = returnDatabase();
}
return db;
} else {
// database does not exist, copy it from assets and return it
copyDatabaseFromAssets();
db = returnDatabase();
return db;
}
}
private SQLiteDatabase returnDatabase() {
try {
SQLiteDatabase db = SQLiteDatabase.openDatabase(mDatabasePath + "/" + mName, mFactory, SQLiteDatabase.OPEN_READWRITE);
Log.i(TAG, "successfully opened database " + mName);
return db;
} catch (SQLiteException e) {
Log.w(TAG, "could not open database " + mName + " - " + e.getMessage());
return null;
}
}
private void copyDatabaseFromAssets() throws SQLiteAssetException {
Log.w(TAG, "copying database from assets...");
String path = mAssetPath;
String dest = mDatabasePath + "/" + mName;
InputStream is;
boolean isZip = false;
try {
// try uncompressed
is = mContext.getAssets().open(path);
} catch (IOException e) {
// try zip
try {
is = mContext.getAssets().open(path + ".zip");
isZip = true;
} catch (IOException e2) {
// try gzip
try {
is = mContext.getAssets().open(path + ".gz");
} catch (IOException e3) {
SQLiteAssetException se = new SQLiteAssetException("Missing " + mAssetPath + " file (or .zip, .gz archive) in assets, or target folder not writable");
se.setStackTrace(e3.getStackTrace());
throw se;
}
}
}
try {
File f = new File(mDatabasePath + "/");
if (!f.exists()) {
f.mkdir();
}
if (isZip) {
ZipInputStream zis = com.jaus.albertogiunta.justintrain_oraritreni.db.sqliteAsset.Utils.getFileFromZip(is);
if (zis == null) {
throw new SQLiteAssetException("Archive is missing a SQLite database file");
}
com.jaus.albertogiunta.justintrain_oraritreni.db.sqliteAsset.Utils.writeExtractedFileToDisk(zis, new FileOutputStream(dest));
} else {
com.jaus.albertogiunta.justintrain_oraritreni.db.sqliteAsset.Utils.writeExtractedFileToDisk(is, new FileOutputStream(dest));
}
Log.w(TAG, "database copy complete");
} catch (IOException e) {
SQLiteAssetException se = new SQLiteAssetException("Unable to write " + dest + " to data directory");
se.setStackTrace(e.getStackTrace());
throw se;
}
}
private InputStream getUpgradeSQLStream(int oldVersion, int newVersion) {
String path = String.format(mUpgradePathFormat, oldVersion, newVersion);
try {
return mContext.getAssets().open(path);
} catch (IOException e) {
Log.w(TAG, "missing database upgrade script: " + path);
return null;
}
}
private void getUpgradeFilePaths(int baseVersion, int start, int end, ArrayList<String> paths) {
int a;
int b;
InputStream is = getUpgradeSQLStream(start, end);
if (is != null) {
String path = String.format(mUpgradePathFormat, start, end);
paths.add(path);
a = start - 1;
b = start;
is = null;
} else {
a = start - 1;
b = end;
}
if (a < baseVersion) {
return;
} else {
getUpgradeFilePaths(baseVersion, a, b, paths); // recursive call
}
}
/**
* An exception that indicates there was an error with SQLite asset retrieval or parsing.
*/
@SuppressWarnings("serial")
public static class SQLiteAssetException extends SQLiteException {
public SQLiteAssetException() {
}
public SQLiteAssetException(String error) {
super(error);
}
}
}