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

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

  db.beginTransaction();
  try {
    for (Map.Entry<AttachmentId, Integer> entry : orderMap.entrySet()) {
      ContentValues values = new ContentValues(1);
      values.put(DISPLAY_ORDER, entry.getValue());

      databaseHelper.getWritableDatabase().update(TABLE_NAME, values, PART_ID_WHERE, entry.getKey().toStrings());
    }

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

}
 
Example 2
Source File: IndexedFixturePathUtils.java    From commcare-android with Apache License 2.0 6 votes vote down vote up
public static void insertIndexedFixturePathBases(SQLiteDatabase db, String fixtureName,
                                                 String baseName, String childName, TreeElement attrs) {
    ContentValues contentValues = new ContentValues();
    contentValues.put(INDEXED_FIXTURE_PATHS_COL_BASE, baseName);
    contentValues.put(INDEXED_FIXTURE_PATHS_COL_CHILD, childName);
    contentValues.put(INDEXED_FIXTURE_PATHS_COL_NAME, fixtureName);
    contentValues.put(INDEXED_FIXTURE_PATHS_COL_ATTRIBUTES, SerializationUtil.serialize(attrs));

    db.beginTransaction();
    try {
        long ret = db.insertWithOnConflict(
                INDEXED_FIXTURE_PATHS_TABLE,
                INDEXED_FIXTURE_PATHS_COL_BASE,
                contentValues,
                SQLiteDatabase.CONFLICT_REPLACE);

        if (ret > Integer.MAX_VALUE) {
            throw new RuntimeException("Waaaaaaaaaay too many values");
        }

        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}
 
Example 3
Source File: StickerDatabase.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private void deleteStickersInPack(@NonNull SQLiteDatabase db, @NonNull String packId) {
  String   selection = PACK_ID + " = ?";
  String[] args      = new String[] { packId };

  db.beginTransaction();

  try {
    try (Cursor cursor = db.query(TABLE_NAME, null, selection, args, null, null, null)) {
      while (cursor != null && cursor.moveToNext()) {
        String  filePath = cursor.getString(cursor.getColumnIndexOrThrow(FILE_PATH));
        long    rowId    = cursor.getLong(cursor.getColumnIndexOrThrow(_ID));

        deleteSticker(db, rowId, filePath);
      }
    }

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

  db.delete(TABLE_NAME, selection, args);
}
 
Example 4
Source File: AndroidCaseXmlParser.java    From commcare-android with Apache License 2.0 6 votes vote down vote up
@Override
public void commit(Case parsed) throws IOException {
    SQLiteDatabase db;
    db = getDbHandle();
    db.beginTransaction();
    try {
        super.commit(parsed);
        if (mEntityCache != null) {
            mEntityCache.invalidateCache(String.valueOf(parsed.getID()));
        }
        mCaseIndexTable.clearCaseIndices(parsed);
        mCaseIndexTable.indexCase(parsed);
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}
 
Example 5
Source File: FixtureSerializationMigration.java    From commcare-android with Apache License 2.0 6 votes vote down vote up
public static void stageFixtureTables(SQLiteDatabase db) {
    db.beginTransaction();
    try {
        boolean resumingMigration = doesTempFixtureTableExist(db);

        DbUtil.createOrphanedFileTable(db);
        if (resumingMigration) {
            db.execSQL("DROP TABLE IF EXISTS fixture;");
        } else {
            db.execSQL("ALTER TABLE fixture RENAME TO oldfixture;");
        }

        // make new fixture db w/ filepath and encryption key columns
        TableBuilder builder = new TableBuilder("fixture");
        builder.addFileBackedData(new FormInstance());
        db.execSQL(builder.getTableCreateString());
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}
 
Example 6
Source File: SmsDatabase.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void markExpireStarted(Collection<Long> ids, long startedAtTimestamp) {
  SQLiteDatabase db       = databaseHelper.getWritableDatabase();
  long           threadId = -1;

  db.beginTransaction();
  try {
    for (long id : ids) {
      ContentValues contentValues = new ContentValues();
      contentValues.put(EXPIRE_STARTED, startedAtTimestamp);

      db.update(TABLE_NAME, contentValues, ID_WHERE, new String[]{String.valueOf(id)});

      if (threadId < 0) {
        threadId = getThreadIdForMessage(id);
      }
    }

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

  DatabaseFactory.getThreadDatabase(context).update(threadId, false);
  notifyConversationListeners(threadId);
}
 
Example 7
Source File: MessagingDatabase.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public void addReaction(long messageId, @NonNull ReactionRecord reaction) {
  SQLiteDatabase db = databaseHelper.getWritableDatabase();

  db.beginTransaction();

  try {
    ReactionList          reactions   = getReactions(db, messageId).or(ReactionList.getDefaultInstance());
    ReactionList.Reaction newReaction = ReactionList.Reaction.newBuilder()
                                                             .setEmoji(reaction.getEmoji())
                                                             .setAuthor(reaction.getAuthor().toLong())
                                                             .setSentTime(reaction.getDateSent())
                                                             .setReceivedTime(reaction.getDateReceived())
                                                             .build();

    ReactionList updatedList = pruneByAuthor(reactions, reaction.getAuthor()).toBuilder()
                                                                             .addReactions(newReaction)
                                                                             .build();

    setReactions(db, messageId, updatedList);

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

  notifyConversationListeners(getThreadId(db, messageId));
}
 
Example 8
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 9
Source File: IndexedFixturePathUtils.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
public static void buildFixtureIndices(SQLiteDatabase database,
                                       String tableName,
                                       Set<String> indices) {
    database.beginTransaction();
    try {
        for (String indexStmt : DatabaseIndexingUtils.getIndexStatements(tableName, indices)) {
            database.execSQL(indexStmt);
        }
        database.setTransactionSuccessful();
    } finally {
        database.endTransaction();
    }
}
 
Example 10
Source File: UserDatabaseUpgrader.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
private boolean upgradeOneTwo(final SQLiteDatabase db) {
    db.beginTransaction();
    try {
        markSenseIncompleteUnsent(db);
        db.setTransactionSuccessful();
        return true;
    } finally {
        db.endTransaction();
    }
}
 
Example 11
Source File: UserDatabaseUpgrader.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
private boolean upgradeTwentyFiveTwentySix(SQLiteDatabase db) {
    db.beginTransaction();
    try {
        db.execSQL(DbUtil.addColumnToTable(
                INDEXED_FIXTURE_PATHS_TABLE,
                INDEXED_FIXTURE_PATHS_COL_ATTRIBUTES,
                "BLOB"));

        db.setTransactionSuccessful();
        return true;
    } finally {
        db.endTransaction();
    }
}
 
Example 12
Source File: AppDatabaseUpgrader.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
private boolean upgradeTenEleven(SQLiteDatabase db) {
    db.beginTransaction();
    try {
        SqlStorage<FormDefRecordV12> formDefRecordStorage = new SqlStorage<>(
                FormDefRecord.STORAGE_KEY,
                FormDefRecordV12.class,
                new ConcreteAndroidDbHelper(context, db));
        for (FormDefRecordV12 formDefRecord : formDefRecordStorage) {
            String filePath = formDefRecord.getFilePath();
            File formFile = new File(filePath);

            // update the path for the record if it points to a non existent upgrade path and corresponding install path exists
            if (!formFile.exists() && filePath.contains(GlobalConstants.FILE_CC_UPGRADE)) {
                String newFilePath = filePath.replace(GlobalConstants.FILE_CC_UPGRADE, GlobalConstants.FILE_CC_INSTALL + "/");
                if (new File(newFilePath).exists()) {
                    formDefRecord.updateFilePath(formDefRecordStorage, newFilePath);
                } else {
                    Logger.log(LogTypes.SOFT_ASSERT, "File not found at both upgrade and install path for form " + formDefRecord.getJrFormId());
                }
            }
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
    return true;
}
 
Example 13
Source File: ImpsProvider.java    From Zom-Android-XMPP with GNU General Public License v3.0 5 votes vote down vote up
@Override
public final Uri insert(final Uri url, final ContentValues values) {
    Uri result = null;

    if (getDBHelper() != null)
    {
        try
        {
            SQLiteDatabase db = getDBHelper().getWritableDatabase();

            if (db.isOpen())
            {
                db.beginTransaction();
                try {
                    result = insertInternal(url, values);
                    db.setTransactionSuccessful();
                } finally {
                    db.endTransaction();
                }
                if (result != null) {
                    getContext().getContentResolver()
                            .notifyChange(url, null /* observer */, false /* sync */);
                }
            }

        }
        catch (IllegalStateException ise)
        {
            log("database closed when insert attempted: " + url.toString());
        }
    }
    return result;
}
 
Example 14
Source File: JobDatabase.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public synchronized void updateJobs(@NonNull List<JobSpec> jobs) {
  SQLiteDatabase db = databaseHelper.getWritableDatabase();

  db.beginTransaction();

  try {
    for (JobSpec job : jobs) {
      ContentValues values = new ContentValues();
      values.put(Jobs.JOB_SPEC_ID, job.getId());
      values.put(Jobs.FACTORY_KEY, job.getFactoryKey());
      values.put(Jobs.QUEUE_KEY, job.getQueueKey());
      values.put(Jobs.CREATE_TIME, job.getCreateTime());
      values.put(Jobs.NEXT_RUN_ATTEMPT_TIME, job.getNextRunAttemptTime());
      values.put(Jobs.RUN_ATTEMPT, job.getRunAttempt());
      values.put(Jobs.MAX_ATTEMPTS, job.getMaxAttempts());
      values.put(Jobs.MAX_BACKOFF, job.getMaxBackoff());
      values.put(Jobs.MAX_INSTANCES, job.getMaxInstances());
      values.put(Jobs.LIFESPAN, job.getLifespan());
      values.put(Jobs.SERIALIZED_DATA, job.getSerializedData());
      values.put(Jobs.SERIALIZED_INPUT_DATA, job.getSerializedInputData());
      values.put(Jobs.IS_RUNNING, job.isRunning() ? 1 : 0);

      String   query = Jobs.JOB_SPEC_ID + " = ?";
      String[] args  = new String[]{ job.getId() };

      db.update(Jobs.TABLE_NAME, values, query, args);
    }

    db.setTransactionSuccessful();
  } finally {
    db.endTransaction();
  }
}
 
Example 15
Source File: StickerDatabase.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public void uninstallPack(@NonNull String packId) {
  SQLiteDatabase db = databaseHelper.getWritableDatabase();

  db.beginTransaction();
  try {
    updatePackInstalled(db, packId, false, false);
    deleteStickersInPackExceptCover(db, packId);

    db.setTransactionSuccessful();
    notifyStickerPackListeners();
    notifyStickerListeners();
  } finally {
    db.endTransaction();
  }
}
 
Example 16
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 17
Source File: UserDatabaseUpgrader.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
private boolean upgradeFourFive(SQLiteDatabase db) {
    db.beginTransaction();
    try {
        db.execSQL(DatabaseIndexingUtils.indexOnTableCommand("ledger_entity_id", "ledger", "entity_id"));
        db.setTransactionSuccessful();
        return true;
    } finally {
        db.endTransaction();
    }
}
 
Example 18
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 19
Source File: AppDatabaseUpgrader.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
private boolean upgradeEightTen(SQLiteDatabase db) {
    boolean success;
    db.beginTransaction();
    try {
        upgradeXFormAndroidInstallerV8(GLOBAL_RESOURCE_TABLE_NAME, db);
        upgradeXFormAndroidInstallerV8(UPGRADE_RESOURCE_TABLE_NAME, db);
        upgradeXFormAndroidInstallerV8(RECOVERY_RESOURCE_TABLE_NAME, db);

        // Create FormDef table
        TableBuilder builder = new TableBuilder(FormDefRecordV12.class);
        db.execSQL(builder.getTableCreateString());

        migrateFormProvider(db);
        db.setTransactionSuccessful();
        success = true;
    } finally {
        db.endTransaction();
    }


    // Delete entries from FormsProvider if migration has been successful
    if (success) {
        try {
            context.getContentResolver().delete(FormsProviderAPI.FormsColumns.CONTENT_URI, null, null);
        } catch (Exception e) {
            // Failure here won't cause any problems in app operations. So fail silently.
            e.printStackTrace();
            Logger.exception("Error while deleting FormsProvider entries during app db migration", e);
        }
    }
    return success;
}
 
Example 20
Source File: UserDatabaseUpgrader.java    From commcare-android with Apache License 2.0 4 votes vote down vote up
/**
 * Adding an appId field to FormRecords, for compatibility with multiple apps functionality
 */
private boolean upgradeNineTen(SQLiteDatabase db) {
    db.beginTransaction();
    try {

        if (UserDbUpgradeUtils.multipleInstalledAppRecords()) {
            // Cannot migrate FormRecords once this device has already started installing
            // multiple applications, because there is no way to know which of those apps the
            // existing FormRecords belong to
            UserDbUpgradeUtils.deleteExistingFormRecordsAndWarnUser(c, db);
            UserDbUpgradeUtils.addAppIdColumnToTable(db);
            db.setTransactionSuccessful();
            return true;
        }

        SqlStorage<FormRecordV1> oldStorage = new SqlStorage<>(
                FormRecord.STORAGE_KEY,
                FormRecordV1.class,
                new ConcreteAndroidDbHelper(c, db));

        String appId = UserDbUpgradeUtils.getInstalledAppRecord().getApplicationId();
        Vector<FormRecordV2> upgradedRecords = new Vector<>();
        // Create all of the updated records, based upon the existing ones
        for (FormRecordV1 oldRecord : oldStorage) {
            FormRecordV2 newRecord = new FormRecordV2(
                    oldRecord.getInstanceURIString(),
                    oldRecord.getStatus(),
                    oldRecord.getFormNamespace(),
                    oldRecord.getAesKey(),
                    oldRecord.getInstanceID(),
                    oldRecord.lastModified(),
                    appId);
            newRecord.setID(oldRecord.getID());
            upgradedRecords.add(newRecord);
        }

        UserDbUpgradeUtils.addAppIdColumnToTable(db);

        // Write all of the new records to the updated table
        SqlStorage<FormRecordV2> newStorage = new SqlStorage<>(
                FormRecord.STORAGE_KEY,
                FormRecordV2.class,
                new ConcreteAndroidDbHelper(c, db));
        for (FormRecordV2 r : upgradedRecords) {
            newStorage.write(r);
        }

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