Java Code Examples for androidx.sqlite.db.SupportSQLiteDatabase#beginTransaction()

The following examples show how to use androidx.sqlite.db.SupportSQLiteDatabase#beginTransaction() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RoomDatabase.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Wrapper for {@link SupportSQLiteDatabase#beginTransaction()}.
 *
 * @deprecated Use {@link #runInTransaction(Runnable)}
 */
@Deprecated
public void beginTransaction() {
    assertNotMainThread();
    SupportSQLiteDatabase database = mOpenHelper.getWritableDatabase();
    mInvalidationTracker.syncTriggers(database);
    database.beginTransaction();
}
 
Example 2
Source File: AppDatabase.java    From openScale with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void migrate(SupportSQLiteDatabase database) {
    database.beginTransaction();
    try {
        // Drop old index on datetime only
        database.execSQL("DROP INDEX index_scaleMeasurements_datetime");

        // Rename old table
        database.execSQL("ALTER TABLE scaleMeasurements RENAME TO scaleMeasurementsOld");

        // Create new table with foreign key
        database.execSQL("CREATE TABLE scaleMeasurements"
                + " (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
                + " userId INTEGER NOT NULL, enabled INTEGER NOT NULL,"
                + " datetime INTEGER, weight REAL NOT NULL, fat REAL NOT NULL,"
                + " water REAL NOT NULL, muscle REAL NOT NULL, lbw REAL NOT NULL,"
                + " waist REAL NOT NULL, hip REAL NOT NULL, bone REAL NOT NULL,"
                + " comment TEXT, FOREIGN KEY(userId) REFERENCES scaleUsers(id)"
                + " ON UPDATE NO ACTION ON DELETE CASCADE)");

        // Create new index on datetime + userId
        database.execSQL("CREATE UNIQUE INDEX index_scaleMeasurements_userId_datetime"
                + " ON scaleMeasurements (userId, datetime)");

        // Copy data from the old table, ignoring those with invalid userId (if any)
        database.execSQL("INSERT INTO scaleMeasurements"
                + " SELECT * FROM scaleMeasurementsOld"
                + " WHERE userId IN (SELECT id from scaleUsers)");

        // Delete old table
        database.execSQL("DROP TABLE scaleMeasurementsOld");

        database.setTransactionSuccessful();
    }
    finally {
        database.endTransaction();
    }
}
 
Example 3
Source File: AppDatabase.java    From openScale with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void migrate(SupportSQLiteDatabase database) {
    database.beginTransaction();
    try {
        // Add assisted weighing and left/right amputation level to table
        database.execSQL("ALTER TABLE scaleUsers ADD assistedWeighing INTEGER NOT NULL default 0");
        database.execSQL("ALTER TABLE scaleUsers ADD leftAmputationLevel INTEGER NOT NULL default 0");
        database.execSQL("ALTER TABLE scaleUsers ADD rightAmputationLevel INTEGER NOT NULL default 0");

        database.setTransactionSuccessful();
    }
    finally {
        database.endTransaction();
    }
}
 
Example 4
Source File: InvalidationTracker.java    From FairEmail with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void run() {
    final Lock closeLock = mDatabase.getCloseLock();
    Set<Integer> invalidatedTableIds = null;
    try {
        closeLock.lock();

        if (!ensureInitialization()) {
            return;
        }

        if (!mPendingRefresh.compareAndSet(true, false)) {
            // no pending refresh
            return;
        }

        if (mDatabase.inTransaction()) {
            // current thread is in a transaction. when it ends, it will invoke
            // refreshRunnable again. mPendingRefresh is left as false on purpose
            // so that the last transaction can flip it on again.
            return;
        }

        if (mDatabase.mWriteAheadLoggingEnabled) {
            // This transaction has to be on the underlying DB rather than the RoomDatabase
            // in order to avoid a recursive loop after endTransaction.
            SupportSQLiteDatabase db = mDatabase.getOpenHelper().getWritableDatabase();
            db.beginTransaction();
            try {
                invalidatedTableIds = checkUpdatedTable();
                db.setTransactionSuccessful();
            } finally {
                db.endTransaction();
            }
        } else {
            invalidatedTableIds = checkUpdatedTable();
        }
    } catch (IllegalStateException | SQLiteException exception) {
        // may happen if db is closed. just log.
        Log.e(Room.LOG_TAG, "Cannot run invalidation tracker. Is the db closed?",
                exception);
    } finally {
        closeLock.unlock();
    }
    if (invalidatedTableIds != null && !invalidatedTableIds.isEmpty()) {
        synchronized (mObserverMap) {
            for (Map.Entry<Observer, ObserverWrapper> entry : mObserverMap) {
                entry.getValue().notifyByTableInvalidStatus(invalidatedTableIds);
            }
        }
    }
}
 
Example 5
Source File: InvalidationTracker.java    From FairEmail with GNU General Public License v3.0 4 votes vote down vote up
void syncTriggers(SupportSQLiteDatabase database) {
    if (database.inTransaction()) {
        // we won't run this inside another transaction.
        return;
    }
    try {
        // This method runs in a while loop because while changes are synced to db, another
        // runnable may be skipped. If we cause it to skip, we need to do its work.
        while (true) {
            Lock closeLock = mDatabase.getCloseLock();
            closeLock.lock();
            try {
                // there is a potential race condition where another mSyncTriggers runnable
                // can start running right after we get the tables list to sync.
                final int[] tablesToSync = mObservedTableTracker.getTablesToSync();
                if (tablesToSync == null) {
                    return;
                }
                final int limit = tablesToSync.length;
                database.beginTransaction();
                try {
                    for (int tableId = 0; tableId < limit; tableId++) {
                        switch (tablesToSync[tableId]) {
                            case ObservedTableTracker.ADD:
                                startTrackingTable(database, tableId);
                                break;
                            case ObservedTableTracker.REMOVE:
                                stopTrackingTable(database, tableId);
                                break;
                        }
                    }
                    database.setTransactionSuccessful();
                } finally {
                    database.endTransaction();
                }
                mObservedTableTracker.onSyncCompleted();
            } finally {
                closeLock.unlock();
            }
        }
    } catch (IllegalStateException | SQLiteException exception) {
        // may happen if db is closed. just log.
        Log.e(Room.LOG_TAG, "Cannot run invalidation tracker. Is the db closed?",
                exception);
    }
}
 
Example 6
Source File: AppDatabase.java    From openScale with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void migrate(SupportSQLiteDatabase database) {
    database.beginTransaction();
    try {
        // Drop old index
        database.execSQL("DROP INDEX index_scaleMeasurements_userId_datetime");

        // Rename old table
        database.execSQL("ALTER TABLE scaleMeasurements RENAME TO scaleMeasurementsOld");
        database.execSQL("ALTER TABLE scaleUsers RENAME TO scaleUsersOld");

        // Create new table with foreign key
        database.execSQL("CREATE TABLE scaleMeasurements"
                + " (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
                + " userId INTEGER NOT NULL, enabled INTEGER NOT NULL,"
                + " datetime INTEGER, weight REAL NOT NULL, fat REAL NOT NULL,"
                + " water REAL NOT NULL, muscle REAL NOT NULL, visceralFat REAL NOT NULL,"
                + " lbm REAL NOT NULL, waist REAL NOT NULL, hip REAL NOT NULL,"
                + " bone REAL NOT NULL, chest REAL NOT NULL, thigh REAL NOT NULL,"
                + " biceps REAL NOT NULL, neck REAL NOT NULL, caliper1 REAL NOT NULL,"
                + " caliper2 REAL NOT NULL, caliper3 REAL NOT NULL, comment TEXT,"
                + " FOREIGN KEY(userId) REFERENCES scaleUsers(id)"
                + " ON UPDATE NO ACTION ON DELETE CASCADE)");

        database.execSQL("CREATE TABLE scaleUsers "
                + "(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
                + "username TEXT NOT NULL, birthday INTEGER NOT NULL, bodyHeight REAL NOT NULL, "
                + "scaleUnit INTEGER NOT NULL, gender INTEGER NOT NULL, initialWeight REAL NOT NULL, "
                + "goalWeight REAL NOT NULL, goalDate INTEGER, measureUnit INTEGER NOT NULL, activityLevel INTEGER NOT NULL)");

        // Create new index on datetime + userId
        database.execSQL("CREATE UNIQUE INDEX index_scaleMeasurements_userId_datetime"
                + " ON scaleMeasurements (userId, datetime)");

        // Copy data from the old table
        database.execSQL("INSERT INTO scaleMeasurements"
                + " SELECT id, userId, enabled, datetime, weight, fat, water, muscle,"
                + " 0 AS visceralFat, lbw AS lbm, waist, hip, bone, 0 AS chest,"
                + " 0 as thigh, 0 as biceps, 0 as neck, 0 as caliper1,"
                + " 0 as caliper2, 0 as caliper3, comment FROM scaleMeasurementsOld");

        database.execSQL("INSERT INTO scaleUsers"
                + " SELECT id, username, birthday, bodyHeight, scaleUnit, gender, initialWeight, goalWeight,"
                + " goalDate, 0 AS measureUnit, 0 AS activityLevel FROM scaleUsersOld");

        // Delete old table
        database.execSQL("DROP TABLE scaleMeasurementsOld");
        database.execSQL("DROP TABLE scaleUsersOld");

        database.setTransactionSuccessful();
    }
    finally {
        database.endTransaction();
    }
}
 
Example 7
Source File: AppDatabase.java    From openScale with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void migrate(SupportSQLiteDatabase database) {
    database.beginTransaction();
    try {
        // Drop old index
        database.execSQL("DROP INDEX index_scaleMeasurements_userId_datetime");

        // Rename old table
        database.execSQL("ALTER TABLE scaleMeasurements RENAME TO scaleMeasurementsOld");

        // Create new table with foreign key
        database.execSQL("CREATE TABLE scaleMeasurements"
                + " (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
                + " userId INTEGER NOT NULL, enabled INTEGER NOT NULL,"
                + " datetime INTEGER, weight REAL NOT NULL, fat REAL NOT NULL,"
                + " water REAL NOT NULL, muscle REAL NOT NULL, visceralFat REAL NOT NULL,"
                + " lbm REAL NOT NULL, waist REAL NOT NULL, hip REAL NOT NULL,"
                + " bone REAL NOT NULL, chest REAL NOT NULL, thigh REAL NOT NULL,"
                + " biceps REAL NOT NULL, neck REAL NOT NULL, caliper1 REAL NOT NULL,"
                + " caliper2 REAL NOT NULL, caliper3 REAL NOT NULL, calories REAL NOT NULL, comment TEXT,"
                + " FOREIGN KEY(userId) REFERENCES scaleUsers(id)"
                + " ON UPDATE NO ACTION ON DELETE CASCADE)");

        // Create new index on datetime + userId
        database.execSQL("CREATE UNIQUE INDEX index_scaleMeasurements_userId_datetime"
                + " ON scaleMeasurements (userId, datetime)");

        // Copy data from the old table
        database.execSQL("INSERT INTO scaleMeasurements"
                + " SELECT id, userId, enabled, datetime, weight, fat, water, muscle,"
                + " visceralFat, lbm, waist, hip, bone, chest,"
                + " thigh, biceps, neck, caliper1,"
                + " caliper2, caliper3, 0 as calories, comment FROM scaleMeasurementsOld");

        // Delete old table
        database.execSQL("DROP TABLE scaleMeasurementsOld");

        database.setTransactionSuccessful();
    }
    finally {
        database.endTransaction();
    }
}