Java Code Examples for net.sqlcipher.database.SQLiteDatabase#endTransaction()

The following examples show how to use net.sqlcipher.database.SQLiteDatabase#endTransaction() . 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: AttachmentDatabase.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public void updateMessageId(@NonNull Collection<AttachmentId> attachmentIds, long mmsId) {
  SQLiteDatabase db = databaseHelper.getWritableDatabase();

  db.beginTransaction();
  try {
    ContentValues values = new ContentValues(1);
    values.put(MMS_ID, mmsId);

    for (AttachmentId attachmentId : attachmentIds) {
      db.update(TABLE_NAME, values, PART_ID_WHERE, attachmentId.toStrings());
    }

    db.setTransactionSuccessful();
  } finally {
    db.endTransaction();
  }
}
 
Example 2
Source File: GlobalDatabaseUpgrader.java    From commcare-android with Apache License 2.0 6 votes vote down vote up
private static boolean addTableForNewModel(SQLiteDatabase db, String storageKey,
                                           Persistable modelToAdd) {
    db.beginTransaction();
    try {
        TableBuilder builder = new TableBuilder(storageKey);
        builder.addData(modelToAdd);
        db.execSQL(builder.getTableCreateString());

        db.setTransactionSuccessful();
        return true;
    } catch (Exception e) {
        return false;
    } finally {
        db.endTransaction();
    }
}
 
Example 3
Source File: HybridFileBackedSqlStorage.java    From commcare-android with Apache License 2.0 6 votes vote down vote up
@Override
public void remove(List<Integer> ids) {
    if (ids.size() > 0) {
        SQLiteDatabase db = getDbOrThrow();
        List<String> filesToRemove;
        db.beginTransaction();
        try {
            filesToRemove = HybridFileBackedSqlHelpers.getFilesToRemove(ids, helper, table);
            List<Pair<String, String[]>> whereParamList = TableBuilder.sqlList(ids);
            for (Pair<String, String[]> whereParams : whereParamList) {
                String whereClause = DatabaseHelper.ID_COL + " IN " + whereParams.first;
                db.delete(table, whereClause, whereParams.second);
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }

        HybridFileBackedSqlHelpers.removeFiles(filesToRemove);
    }
}
 
Example 4
Source File: SqlStorage.java    From commcare-android with Apache License 2.0 6 votes vote down vote up
public void remove(List<Integer> ids) {
    if (ids.size() == 0) {
        return;
    }
    SQLiteDatabase db = helper.getHandle();
    db.beginTransaction();
    try {
        List<Pair<String, String[]>> whereParamList = TableBuilder.sqlList(ids);
        for (Pair<String, String[]> whereParams : whereParamList) {
            db.delete(table, DatabaseHelper.ID_COL + " IN " + whereParams.first, whereParams.second);
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}
 
Example 5
Source File: UserDatabaseUpgrader.java    From commcare-android with Apache License 2.0 6 votes vote down vote up
private boolean upgradeTenEleven(SQLiteDatabase db) {
    db.beginTransaction();
    try {
        // add table for dedicated xpath error logging for reporting xpath
        // errors on specific cc app builds.
        TableBuilder builder = new TableBuilder(XPathErrorEntry.STORAGE_KEY);
        builder.addData(new XPathErrorEntry());
        db.execSQL(builder.getTableCreateString());
        db.setTransactionSuccessful();
        return true;
    } catch (Exception e) {
        return false;
    } finally {
        db.endTransaction();
    }
}
 
Example 6
Source File: SqlStorage.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
public static void wipeTable(SQLiteDatabase db, String table) {
    db.beginTransaction();
    try {
        if (isTableExist(db, table)) {
            db.delete(table, null, null);
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}
 
Example 7
Source File: UserDatabaseUpgrader.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
private boolean upgradeTwoThree(final SQLiteDatabase db) {
    db.beginTransaction();
    try {
        markSenseIncompleteUnsent(db);
        db.setTransactionSuccessful();
        return true;
    } finally {
        db.endTransaction();
    }
}
 
Example 8
Source File: UserDatabaseUpgrader.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
/**
 * Add a metadata field to all form records for "form number" that will be used for ordering
 * submissions. Since submissions were previously ordered by the last modified property,
 * set the new form numbers in this order.
 */
private boolean upgradeSixteenSeventeen(SQLiteDatabase db) {
    db.beginTransaction();
    try {
        SqlStorage<FormRecordV2> oldStorage = new SqlStorage<>(
                FormRecord.STORAGE_KEY,
                FormRecordV2.class,
                new ConcreteAndroidDbHelper(c, db));

        Set<String> idsOfAppsWithOldFormRecords =
                UserDbUpgradeUtils.getAppIdsForRecords(oldStorage);
        Vector<FormRecordV3> upgradedRecords = new Vector<>();

        for (String appId : idsOfAppsWithOldFormRecords) {
            migrateV2FormRecordsForSingleApp(appId, oldStorage, upgradedRecords);
        }

        // Add new column to db and then write all of the new records
        UserDbUpgradeUtils.addFormNumberColumnToTable(db);
        SqlStorage<FormRecordV3> newStorage = new SqlStorage<>(
                FormRecord.STORAGE_KEY,
                FormRecordV3.class,
                new ConcreteAndroidDbHelper(c, db));
        for (FormRecordV3 r : upgradedRecords) {
            newStorage.write(r);
        }

        db.setTransactionSuccessful();
        return true;
    } finally {
        db.endTransaction();
    }
}
 
Example 9
Source File: StickerDatabase.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public void deleteOrphanedPacks() {
  SQLiteDatabase db    = databaseHelper.getWritableDatabase();
  String         query = "SELECT " + PACK_ID + " FROM " + TABLE_NAME + " WHERE " + INSTALLED + " = ? AND " +
                         PACK_ID + " NOT IN (" +
                           "SELECT DISTINCT " + AttachmentDatabase.STICKER_PACK_ID + " FROM " + AttachmentDatabase.TABLE_NAME + " " +
                           "WHERE " + AttachmentDatabase.STICKER_PACK_ID + " NOT NULL" +
                         ")";
  String[]      args = new String[] { "0" };

  db.beginTransaction();

  try {
    boolean performedDelete = false;

    try (Cursor cursor = db.rawQuery(query, args)) {
      while (cursor != null && cursor.moveToNext()) {
        String packId = cursor.getString(cursor.getColumnIndexOrThrow(PACK_ID));

        if (!BlessedPacks.contains(packId)) {
          deletePack(db, packId);
          performedDelete = true;
        }
      }
    }

    db.setTransactionSuccessful();

    if (performedDelete) {
      notifyStickerPackListeners();
      notifyStickerListeners();
    }
  } finally {
    db.endTransaction();
  }
}
 
Example 10
Source File: UserDatabaseUpgrader.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
private boolean upgradeElevenTwelve(SQLiteDatabase db) {
    db.beginTransaction();
    try {
        db.execSQL("DROP TABLE IF EXISTS " + GeocodeCacheModel.STORAGE_KEY);
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
    return true;
}
 
Example 11
Source File: SqlStorage.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
@Override
public void remove(int id) {
    SQLiteDatabase db = helper.getHandle();
    db.beginTransaction();
    try {
        db.delete(table, DatabaseHelper.ID_COL + "=?", new String[]{String.valueOf(id)});
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}
 
Example 12
Source File: AndroidBulkCaseXmlParser.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
@Override
protected void performBulkRead(Set<String> currentBulkReadSet, Map<String, Case> currentOperatingSet) throws InvalidStructureException, IOException, XmlPullParserException {
    SQLiteDatabase db;
    db = getDbHandle();
    db.beginTransaction();
    try {
        for (ACase c : storage.getBulkRecordsForIndex(Case.INDEX_CASE_ID, currentBulkReadSet)) {
            currentOperatingSet.put(c.getCaseId(), c);
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}
 
Example 13
Source File: UserDatabaseUpgrader.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
private boolean upgradeTwentyOneTwentyTwo(SQLiteDatabase db) {
    //drop the existing table and recreate using current definition
    db.beginTransaction();
    try {
        db.execSQL("DROP TABLE IF EXISTS " + EntityStorageCache.TABLE_NAME);
        db.execSQL(EntityStorageCache.getTableDefinition());
        db.setTransactionSuccessful();
        return true;
    } finally {
        db.endTransaction();
    }
}
 
Example 14
Source File: AppDatabaseUpgrader.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
private boolean upgradeTwoThree(SQLiteDatabase db) {
    db.beginTransaction();
    try {
        TableBuilder builder = new TableBuilder("RECOVERY_RESOURCE_TABLE");
        builder.addData(new ResourceV13());
        db.execSQL(builder.getTableCreateString());
        db.setTransactionSuccessful();
        return true;
    } finally {
        db.endTransaction();
    }
}
 
Example 15
Source File: FixtureSerializationMigration.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
public static void dropTempFixtureTable(SQLiteDatabase db) {
    db.beginTransaction();
    try {
        db.execSQL("DROP TABLE oldfixture;");
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}
 
Example 16
Source File: AppDatabaseUpgrader.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
private boolean upgradeTwelveThirteen(SQLiteDatabase db) {
    db.beginTransaction();
    try {
        db.execSQL(DbUtil.addColumnToTable(
                FormDefRecord.STORAGE_KEY,
                FormDefRecord.META_RESOURCE_VERSION,
                "INTEGER"));

        SqlStorage<FormDefRecordV12> oldFormDefRecordStorage = new SqlStorage<>(
                FormDefRecord.STORAGE_KEY,
                FormDefRecordV12.class,
                new ConcreteAndroidDbHelper(context, db));

        SqlStorage<FormDefRecord> formDefRecordStorage = new SqlStorage<>(
                FormDefRecord.STORAGE_KEY,
                FormDefRecord.class,
                new ConcreteAndroidDbHelper(context, db));

        for (FormDefRecordV12 oldFormDefRecord : oldFormDefRecordStorage) {
            FormDefRecord formDefRecord = new FormDefRecord(oldFormDefRecord);
            formDefRecordStorage.update(oldFormDefRecord.getID(), formDefRecord);
        }

        db.setTransactionSuccessful();
        return true;
    } finally {
        db.endTransaction();
    }
}
 
Example 17
Source File: KeyValueDatabase.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
public void writeDataSet(@NonNull KeyValueDataSet dataSet, @NonNull Collection<String> removes) {
  SQLiteDatabase db = databaseHelper.getWritableDatabase();

  db.beginTransaction();
  try {
    for (Map.Entry<String, Object> entry : dataSet.getValues().entrySet()) {
      String key   = entry.getKey();
      Object value = entry.getValue();
      Class  type  = dataSet.getType(key);

      ContentValues contentValues = new ContentValues(3);
      contentValues.put(KEY, key);

      if (type == byte[].class) {
        contentValues.put(VALUE, (byte[]) value);
        contentValues.put(TYPE, Type.BLOB.getId());
      } else if (type == Boolean.class) {
        contentValues.put(VALUE, (boolean) value);
        contentValues.put(TYPE, Type.BOOLEAN.getId());
      } else if (type == Float.class) {
        contentValues.put(VALUE, (float) value);
        contentValues.put(TYPE, Type.FLOAT.getId());
      } else if (type == Integer.class) {
        contentValues.put(VALUE, (int) value);
        contentValues.put(TYPE, Type.INTEGER.getId());
      } else if (type == Long.class) {
        contentValues.put(VALUE, (long) value);
        contentValues.put(TYPE, Type.LONG.getId());
      } else if (type == String.class) {
        contentValues.put(VALUE, (String) value);
        contentValues.put(TYPE, Type.STRING.getId());
      } else {
        throw new AssertionError("Unknown type: " + type);
      }

      db.insertWithOnConflict(TABLE_NAME, null, contentValues, SQLiteDatabase.CONFLICT_REPLACE);
    }

    String deleteQuery = KEY + " = ?";
    for (String remove : removes) {
      db.delete(TABLE_NAME, deleteQuery, new String[] { remove });
    }

    db.setTransactionSuccessful();
  } finally {
    db.endTransaction();
  }
}
 
Example 18
Source File: HybridFileBackedSqlStorage.java    From commcare-android with Apache License 2.0 4 votes vote down vote up
@Override
public Vector<Integer> removeAll(EntityFilter ef) {
    Vector<Integer> removed = new Vector<>();
    for (IStorageIterator iterator = this.iterate(); iterator.hasMore(); ) {
        int id = iterator.nextID();
        switch (ef.preFilter(id, null)) {
            case EntityFilter.PREFILTER_INCLUDE:
                removed.add(id);
                continue;
            case EntityFilter.PREFILTER_EXCLUDE:
                continue;
            case EntityFilter.PREFILTER_FILTER:
                if (ef.matches(read(id))) {
                    removed.add(id);
                }
        }
    }

    if (removed.size() > 0) {
        List<Pair<String, String[]>> whereParamList =
                TableBuilder.sqlList(removed);

        SQLiteDatabase db = getDbOrThrow();

        List<String> filesToRemove;
        db.beginTransaction();
        try {
            filesToRemove = HybridFileBackedSqlHelpers.getFilesToRemove(removed, helper, table);
            for (Pair<String, String[]> whereParams : whereParamList) {
                String whereClause = DatabaseHelper.ID_COL + " IN " + whereParams.first;
                db.delete(table, whereClause, whereParams.second);
            }

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

        HybridFileBackedSqlHelpers.removeFiles(filesToRemove);
    }

    return removed;
}
 
Example 19
Source File: GlobalDatabaseUpgrader.java    From commcare-android with Apache License 2.0 4 votes vote down vote up
private boolean upgradeTwoThree(SQLiteDatabase db) {
    db.beginTransaction();

    //First, migrate the old ApplicationRecord in storage to the new version being used for
    // multiple apps.
    try {
        SqlStorage<Persistable> storage = new SqlStorage<Persistable>(
                ApplicationRecord.STORAGE_KEY,
                ApplicationRecordV1.class,
                new ConcreteAndroidDbHelper(c, db));

        if (multipleInstalledAppRecords(storage)) {
            // If a device has multiple installed ApplicationRecords before the multiple apps
            // db upgrade has occurred, something has definitely gone wrong
            throw new MigrationException(true);
        }

        for (Persistable r : storage) {
            ApplicationRecordV1 oldRecord = (ApplicationRecordV1) r;
            ApplicationRecord newRecord =
                    new ApplicationRecord(oldRecord.getApplicationId(), oldRecord.getStatus());
            //set this new record to have same ID as the old one
            newRecord.setID(oldRecord.getID());
            //set default values for the new fields
            newRecord.setResourcesStatus(true);
            newRecord.setArchiveStatus(false);
            newRecord.setUniqueId("");
            newRecord.setDisplayName("");
            newRecord.setVersionNumber(-1);
            newRecord.setConvertedByDbUpgrader(true);
            newRecord.setPreMultipleAppsProfile(true);
            storage.write(newRecord);
        }

        // Then migrate the databases for both providers
        if (upgradeProviderDb(db, ProviderUtils.ProviderType.FORMS) &&
                upgradeProviderDb(db, ProviderUtils.ProviderType.INSTANCES)) {
            db.setTransactionSuccessful();
            return true;
        }
        return false;
    } finally {
        db.endTransaction();
    }
}
 
Example 20
Source File: RecipientDatabase.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
public void applyBlockedUpdate(@NonNull List<SignalServiceAddress> blocked, List<byte[]> groupIds) {
  List<String> blockedE164 = Stream.of(blocked)
                                   .filter(b -> b.getNumber().isPresent())
                                   .map(b -> b.getNumber().get())
                                   .toList();
  List<String> blockedUuid = Stream.of(blocked)
                                   .filter(b -> b.getUuid().isPresent())
                                   .map(b -> b.getUuid().get().toString().toLowerCase())
                                   .toList();

  SQLiteDatabase db = databaseHelper.getWritableDatabase();

  db.beginTransaction();
  try {
    ContentValues resetBlocked = new ContentValues();
    resetBlocked.put(BLOCKED, 0);
    db.update(TABLE_NAME, resetBlocked, null, null);

    ContentValues setBlocked = new ContentValues();
    setBlocked.put(BLOCKED, 1);
    setBlocked.put(PROFILE_SHARING, 0);

    for (String e164 : blockedE164) {
      db.update(TABLE_NAME, setBlocked, PHONE + " = ?", new String[] { e164 });
    }

    for (String uuid : blockedUuid) {
      db.update(TABLE_NAME, setBlocked, UUID + " = ?", new String[] { uuid });
    }

    List<GroupId.V1> groupIdStrings = Stream.of(groupIds).map(GroupId::v1orThrow).toList();

    for (GroupId.V1 groupId : groupIdStrings) {
      db.update(TABLE_NAME, setBlocked, GROUP_ID + " = ?", new String[] { groupId.toString() });
    }

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

  ApplicationDependencies.getRecipientCache().clear();
}