下面列出了android.database.sqlite.SQLiteDatabase#beginTransactionNonExclusive ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void ensureInitialized() throws DatabaseIOException {
if (initialized) {
return;
}
try {
SQLiteDatabase readableDatabase = databaseProvider.getReadableDatabase();
int version = VersionTable.getVersion(readableDatabase, VersionTable.FEATURE_OFFLINE, name);
if (version != TABLE_VERSION) {
SQLiteDatabase writableDatabase = databaseProvider.getWritableDatabase();
writableDatabase.beginTransactionNonExclusive();
try {
VersionTable.setVersion(
writableDatabase, VersionTable.FEATURE_OFFLINE, name, TABLE_VERSION);
writableDatabase.execSQL("DROP TABLE IF EXISTS " + tableName);
writableDatabase.execSQL("CREATE TABLE " + tableName + " " + TABLE_SCHEMA);
writableDatabase.setTransactionSuccessful();
} finally {
writableDatabase.endTransaction();
}
}
initialized = true;
} catch (SQLException e) {
throw new DatabaseIOException(e);
}
}
public void addForward(int protocol, int dport, String raddr, int rport, int ruid) {
lock.writeLock().lock();
try {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransactionNonExclusive();
try {
ContentValues cv = new ContentValues();
cv.put("protocol", protocol);
cv.put("dport", dport);
cv.put("raddr", raddr);
cv.put("rport", rport);
cv.put("ruid", ruid);
if (db.insert("forward", null, cv) < 0)
Log.e(TAG, "Insert forward failed");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} finally {
lock.writeLock().unlock();
}
notifyForwardChanged();
}
public void deleteForward() {
lock.writeLock().lock();
try {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransactionNonExclusive();
try {
db.delete("forward", null, null);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} finally {
lock.writeLock().unlock();
}
notifyForwardChanged();
}
private static void delete(DatabaseProvider databaseProvider, String hexUid)
throws DatabaseIOException {
try {
String tableName = getTableName(hexUid);
SQLiteDatabase writableDatabase = databaseProvider.getWritableDatabase();
writableDatabase.beginTransactionNonExclusive();
try {
VersionTable.removeVersion(
writableDatabase, VersionTable.FEATURE_CACHE_CONTENT_METADATA, hexUid);
dropTable(writableDatabase, tableName);
writableDatabase.setTransactionSuccessful();
} finally {
writableDatabase.endTransaction();
}
} catch (SQLException e) {
throw new DatabaseIOException(e);
}
}
/**
* Deletes index data for the specified cache.
*
* <p>This method may be slow and shouldn't normally be called on the main thread.
*
* @param databaseProvider Provides the database in which the index is stored.
* @param uid The cache UID.
* @throws DatabaseIOException If an error occurs deleting the index data.
*/
@WorkerThread
public static void delete(DatabaseProvider databaseProvider, long uid)
throws DatabaseIOException {
String hexUid = Long.toHexString(uid);
try {
String tableName = getTableName(hexUid);
SQLiteDatabase writableDatabase = databaseProvider.getWritableDatabase();
writableDatabase.beginTransactionNonExclusive();
try {
VersionTable.removeVersion(
writableDatabase, VersionTable.FEATURE_CACHE_FILE_METADATA, hexUid);
dropTable(writableDatabase, tableName);
writableDatabase.setTransactionSuccessful();
} finally {
writableDatabase.endTransaction();
}
} catch (SQLException e) {
throw new DatabaseIOException(e);
}
}
public void cleanupLog(long time) {
lock.writeLock().lock();
try {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransactionNonExclusive();
try {
// There an index on time
int rows = db.delete("log", "time < ?", new String[]{Long.toString(time)});
Log.i(TAG, "Cleanup log" +
" before=" + SimpleDateFormat.getDateTimeInstance().format(new Date(time)) +
" rows=" + rows);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} finally {
lock.writeLock().unlock();
}
}
public void deleteForward(int protocol, int dport) {
lock.writeLock().lock();
try {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransactionNonExclusive();
try {
db.delete("forward", "protocol = ? AND dport = ?",
new String[]{Integer.toString(protocol), Integer.toString(dport)});
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} finally {
lock.writeLock().unlock();
}
notifyForwardChanged();
}
public void cleanupLog(long time) {
lock.writeLock().lock();
try {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransactionNonExclusive();
try {
// There an index on time
int rows = db.delete("log", "time < ?", new String[]{Long.toString(time)});
Log.i(TAG, "Cleanup log" +
" before=" + SimpleDateFormat.getDateTimeInstance().format(new Date(time)) +
" rows=" + rows);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} finally {
lock.writeLock().unlock();
}
}
public void clearAccess() {
lock.writeLock().lock();
try {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransactionNonExclusive();
try {
db.delete("access", null, null);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} finally {
lock.writeLock().unlock();
}
notifyAccessChanged();
}
public void setAccess(long id, int block) {
lock.writeLock().lock();
try {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransactionNonExclusive();
try {
ContentValues cv = new ContentValues();
cv.put("block", block);
cv.put("allowed", -1);
if (db.update("access", cv, "ID = ?", new String[]{Long.toString(id)}) != 1)
Log.e(TAG, "Set access failed");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} finally {
lock.writeLock().unlock();
}
notifyAccessChanged();
}
public void clearAccess(int uid, boolean keeprules) {
lock.writeLock().lock();
try {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransactionNonExclusive();
try {
// There is a segmented index on uid
// There is an index on block
if (keeprules)
db.delete("access", "uid = ? AND block < 0", new String[]{Integer.toString(uid)});
else
db.delete("access", "uid = ?", new String[]{Integer.toString(uid)});
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} finally {
lock.writeLock().unlock();
}
notifyAccessChanged();
}
/**
* Initializes the index for the given cache UID.
*
* <p>This method may be slow and shouldn't normally be called on the main thread.
*
* @param uid The cache UID.
* @throws DatabaseIOException If an error occurs initializing the index.
*/
@WorkerThread
public void initialize(long uid) throws DatabaseIOException {
try {
String hexUid = Long.toHexString(uid);
tableName = getTableName(hexUid);
SQLiteDatabase readableDatabase = databaseProvider.getReadableDatabase();
int version =
VersionTable.getVersion(
readableDatabase, VersionTable.FEATURE_CACHE_FILE_METADATA, hexUid);
if (version != TABLE_VERSION) {
SQLiteDatabase writableDatabase = databaseProvider.getWritableDatabase();
writableDatabase.beginTransactionNonExclusive();
try {
VersionTable.setVersion(
writableDatabase, VersionTable.FEATURE_CACHE_FILE_METADATA, hexUid, TABLE_VERSION);
dropTable(writableDatabase, tableName);
writableDatabase.execSQL("CREATE TABLE " + tableName + " " + TABLE_SCHEMA);
writableDatabase.setTransactionSuccessful();
} finally {
writableDatabase.endTransaction();
}
}
} catch (SQLException e) {
throw new DatabaseIOException(e);
}
}
@Override
public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
int length = values.length;
if (length == 0)
return 0;
TableDetails tableDetails = uriMatcherHelper.getTableDetails(uri);
SQLiteDatabase db = database.getWritableDatabase();
if (debugEnabled) {
CPOrmLog.d("********* Bulk Insert **********");
CPOrmLog.d("Uri: " + uri);
}
int count = 0;
try {
db.beginTransactionNonExclusive();
String tableName = tableDetails.getTableName();
for (int i = 0; i < length; i++) {
db.insertOrThrow(tableName, null, values[i]);
count++;
if (count % 100 == 0)
db.yieldIfContendedSafely();
}
db.setTransactionSuccessful();
notifyChanges(uri.buildUpon().appendQueryParameter(PARAMETER_CHANGE_TYPE, CPOrm.ChangeType.INSERT.toString()).build(), tableDetails);
} finally {
db.endTransaction();
}
return count;
}
public void clearApps() {
lock.writeLock().lock();
try {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransactionNonExclusive();
try {
db.delete("app", null, null);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} finally {
lock.writeLock().unlock();
}
}
public static void runInNonExclusiveTx(DaoSession session, Consumer<DaoSession> runnable) {
SQLiteDatabase db = (SQLiteDatabase) session.getDatabase().getRawDatabase();
db.beginTransactionNonExclusive();
try {
runnable.accept(session);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
public void addApp(String packageName, String label, boolean system, boolean internet, boolean enabled) {
lock.writeLock().lock();
try {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransactionNonExclusive();
try {
ContentValues cv = new ContentValues();
cv.put("package", packageName);
if (label == null)
cv.putNull("label");
else
cv.put("label", label);
cv.put("system", system ? 1 : 0);
cv.put("internet", internet ? 1 : 0);
cv.put("enabled", enabled ? 1 : 0);
if (db.insert("app", null, cv) < 0)
Log.e(TAG, "Insert app failed");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} finally {
lock.writeLock().unlock();
}
}
public void clearApps() {
lock.writeLock().lock();
try {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransactionNonExclusive();
try {
db.delete("app", null, null);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} finally {
lock.writeLock().unlock();
}
}
public static <T> T callInNonExclusiveTx(DaoSession session, Callable<T> callable) {
SQLiteDatabase db = (SQLiteDatabase) session.getDatabase().getRawDatabase();
db.beginTransactionNonExclusive();
try {
T result = callable.call(session);
db.setTransactionSuccessful();
return result;
} finally {
db.endTransaction();
}
}
/**
* Marks a downloading entry as having successfully downloaded and being installed.
*
* The metadata database contains information about ongoing processes, typically ongoing
* downloads. This marks such an entry as having finished and having installed successfully,
* so it becomes INSTALLED.
*
* @param db the metadata database.
* @param r content values about the entry to mark as processed.
*/
public static void markEntryAsFinishedDownloadingAndInstalled(final SQLiteDatabase db,
final ContentValues r) {
switch (r.getAsInteger(TYPE_COLUMN)) {
case TYPE_BULK:
DebugLogUtils.l("Ended processing a wordlist");
// Updating a bulk word list is a three-step operation:
// - Add the new entry to the table
// - Remove the old entry from the table
// - Erase the old file
// We start by gathering the names of the files we should delete.
final List<String> filenames = new LinkedList<>();
final Cursor c = db.query(METADATA_TABLE_NAME,
new String[] { LOCAL_FILENAME_COLUMN },
LOCALE_COLUMN + " = ? AND " +
WORDLISTID_COLUMN + " = ? AND " + STATUS_COLUMN + " = ?",
new String[] { r.getAsString(LOCALE_COLUMN),
r.getAsString(WORDLISTID_COLUMN),
Integer.toString(STATUS_INSTALLED) },
null, null, null);
try {
if (c.moveToFirst()) {
// There should never be more than one file, but if there are, it's a bug
// and we should remove them all. I think it might happen if the power of
// the phone is suddenly cut during an update.
final int filenameIndex = c.getColumnIndex(LOCAL_FILENAME_COLUMN);
do {
DebugLogUtils.l("Setting for removal", c.getString(filenameIndex));
filenames.add(c.getString(filenameIndex));
} while (c.moveToNext());
}
} finally {
c.close();
}
r.put(STATUS_COLUMN, STATUS_INSTALLED);
db.beginTransactionNonExclusive();
// Delete all old entries. There should never be any stalled entries, but if
// there are, this deletes them.
db.delete(METADATA_TABLE_NAME,
WORDLISTID_COLUMN + " = ?",
new String[] { r.getAsString(WORDLISTID_COLUMN) });
db.insert(METADATA_TABLE_NAME, null, r);
db.setTransactionSuccessful();
db.endTransaction();
for (String filename : filenames) {
try {
final File f = new File(filename);
f.delete();
} catch (SecurityException e) {
// No permissions to delete. Um. Can't do anything.
} // I don't think anything else can be thrown
}
break;
default:
// Unknown type: do nothing.
break;
}
}
public void updateUsage(Usage usage, String dname) {
lock.writeLock().lock();
try {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransactionNonExclusive();
try {
// There is a segmented index on uid, version, protocol, daddr and dport
String selection = "uid = ? AND version = ? AND protocol = ? AND daddr = ? AND dport = ?";
String[] selectionArgs = new String[]{
Integer.toString(usage.Uid),
Integer.toString(usage.Version),
Integer.toString(usage.Protocol),
dname == null ? usage.DAddr : dname,
Integer.toString(usage.DPort)
};
try (Cursor cursor = db.query("access", new String[]{"sent", "received", "connections"}, selection, selectionArgs, null, null, null)) {
long sent = 0;
long received = 0;
int connections = 0;
int colSent = cursor.getColumnIndex("sent");
int colReceived = cursor.getColumnIndex("received");
int colConnections = cursor.getColumnIndex("connections");
if (cursor.moveToNext()) {
sent = cursor.isNull(colSent) ? 0 : cursor.getLong(colSent);
received = cursor.isNull(colReceived) ? 0 : cursor.getLong(colReceived);
connections = cursor.isNull(colConnections) ? 0 : cursor.getInt(colConnections);
}
ContentValues cv = new ContentValues();
cv.put("sent", sent + usage.Sent);
cv.put("received", received + usage.Received);
cv.put("connections", connections + 1);
int rows = db.update("access", cv, selection, selectionArgs);
if (rows != 1)
Log.e(TAG, "Update usage failed rows=" + rows);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} finally {
lock.writeLock().unlock();
}
notifyAccessChanged();
}