androidx.room.Transaction Java Examples

The following examples show how to use androidx.room.Transaction. 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: OverwriteDao.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
@Transaction
public void revertKeywordOverwrites(final String threadId) {
    final int keywordOverwrites = deleteKeywordOverwritesByThread(threadId);
    final int queryOverwrites = deleteQueryOverwritesByThread(threadId, QueryItemOverwriteEntity.Type.KEYWORD);
    if (keywordOverwrites > 0 || queryOverwrites > 0) {
        LOGGER.info("Deleted {} keyword overwrites and {} query overwrites for thread {}", keywordOverwrites, queryOverwrites, threadId);
    }
}
 
Example #2
Source File: DaoMessage.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
@Transaction
@Query("SELECT message.*" +
        ", account.pop AS accountProtocol, account.name AS accountName, COALESCE(identity.color, folder.color, account.color) AS accountColor" +
        ", account.notify AS accountNotify, account.auto_seen AS accountAutoSeen" +
        ", folder.name AS folderName, folder.color AS folderColor, folder.display AS folderDisplay, folder.type AS folderType, folder.unified AS folderUnified, folder.read_only AS folderReadOnly" +
        ", IFNULL(identity.display, identity.name) AS identityName, identity.email AS identityEmail, identity.synchronize AS identitySynchronize" +
        ", message.`from` AS senders" +
        ", message.`to` AS recipients" +
        ", 1 AS count" +
        ", 1 AS unseen" +
        ", 0 AS unflagged" +
        ", 0 AS drafts" +
        ", (message.ui_encrypt IN (2, 4)) AS signed" +
        ", (message.ui_encrypt IN (1, 3)) AS encrypted" +
        ", 1 AS visible" +
        ", NOT message.ui_seen AS visible_unseen" +
        ", message.total AS totalSize" +
        ", message.priority AS ui_priority" +
        ", message.importance AS ui_importance" +
        " FROM message" +
        " JOIN account_view AS account ON account.id = message.account" +
        " LEFT JOIN identity_view AS identity ON identity.id = message.identity" +
        " JOIN folder_view AS folder ON folder.id = message.folder" +
        " WHERE account.`synchronize`" +
        " AND folder.notify" +
        " AND (account.created IS NULL OR message.received > account.created)" +
        " AND (notifying <> 0 OR NOT (message.ui_seen OR message.ui_hide))" +
        " ORDER BY message.received")
LiveData<List<TupleMessageEx>> liveUnseenNotify();
 
Example #3
Source File: ThreadAndEmailDao.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
@Transaction
public Missing getMissing(String queryString) {
    final List<String> ids = getMissingThreadIds(queryString);
    final String threadState = getState(EntityType.THREAD);
    final String emailState = getState(EntityType.EMAIL);
    return new Missing(threadState, emailState, ids);
}
 
Example #4
Source File: DaoMessage.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
@Transaction
@Query("SELECT account.id AS account, COUNT(message.id) AS unseen, SUM(ABS(notifying)) AS notifying" +
        " FROM message" +
        " JOIN account_view AS account ON account.id = message.account" +
        " JOIN folder_view AS folder ON folder.id = message.folder" +
        " WHERE (:account IS NULL OR account.id = :account)" +
        " AND account.`synchronize`" +
        " AND folder.notify" +
        " AND NOT (message.ui_seen OR message.ui_hide)" +
        " GROUP BY account.id" +
        " ORDER BY account.id")
LiveData<List<TupleMessageStats>> liveWidgetUnseen(Long account);
 
Example #5
Source File: DaoMessage.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
@Transaction
@Query("SELECT folder, COUNT(*) AS total" +
        ", SUM(ui_seen) AS seen" +
        ", SUM(ui_flagged) AS flagged" +
        " FROM message" +
        " WHERE NOT ui_hide" +
        " AND message.ui_snoozed IS NULL" +
        " GROUP BY folder" +
        " ORDER BY folder")
LiveData<List<TupleMessageWidgetCount>> liveWidgetUnified();
 
Example #6
Source File: IdentityDao.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
@Transaction
public void set(Identity[] identities, String state) {
    if (state != null && state.equals(getState(EntityType.IDENTITY))) {
        LOGGER.debug("nothing to do. identities with this state have already been set");
        return;
    }
    deleteAll();
    if (identities.length > 0) {
        insert(identities);
    }
    insert(new EntityStateEntity(EntityType.IDENTITY, state));
}
 
Example #7
Source File: QueryDao.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
@Transaction
public void updateQueryResults(String queryString, QueryUpdate<Email, QueryResultItem> queryUpdate, final TypedState<Email> emailState) {
    final String newState = queryUpdate.getNewTypedState().getState();
    final String oldState = queryUpdate.getOldTypedState().getState();
    if (newState.equals(getQueryState(queryString))) {
        Log.d("lttrs", "nothing to do. query already at newest state");
        return;
    }
    throwOnCacheConflict(EntityType.EMAIL, emailState);
    final QueryEntity queryEntity = getQueryEntity(queryString);

    int count = deleteAllExecuted(queryEntity.id);
    Log.d("lttrs", "deleted " + count + " query overwrites");

    for (String emailId : queryUpdate.getRemoved()) {
        Log.d("lttrs", "deleting emailId=" + emailId + " from queryId=" + queryEntity.id);
        decrementAllPositionsFrom(queryEntity.id, emailId);
        deleteQueryItem(queryEntity.id, emailId);
    }
    for (AddedItem<QueryResultItem> addedItem : queryUpdate.getAdded()) {
        Log.d("lttrs", "adding item " + addedItem);
        Log.d("lttrs", "increment all positions where queryId=" + queryEntity.id + " and position=" + addedItem.getIndex());

        if (incrementAllPositionsFrom(queryEntity.id, addedItem.getIndex()) == 0 && getItemCount(queryEntity.id) != addedItem.getIndex()) {
            Log.d("lttrs", "ignoring query item change at position = " + addedItem.getIndex());
            continue;
        }
        Log.d("lttrs", "insert queryItemEntity on position " + addedItem.getIndex() + " and id=" + queryEntity.id);
        insert(QueryItemEntity.of(queryEntity.id, addedItem.getIndex(), addedItem.getItem()));
    }

    if (updateQueryState(queryEntity.id, newState, oldState) != 1) {
        throw new CacheConflictException("Unable to update query from oldState=" + oldState + " to newState=" + newState);
    }
}
 
Example #8
Source File: QueryDao.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
@Transaction
public void add(String queryString, String afterEmailId, QueryResult queryResult) {

    final QueryEntity queryEntity = get(queryString);


    //TODO not having a state is fine; we still want to be able to page
    //TODO compare queryEntity.state only when it is not null
    if (queryEntity == null || queryEntity.state == null) {
        throw new CacheConflictException("Unable to append items to Query. Cached query state is unknown");
    }

    if (!queryEntity.state.equals(queryResult.queryState.getState())) {
        throw new CacheConflictException("Unable to append to Query. Cached query state did not meet our expectations");
    }

    TypedState<Email> emailState = queryResult.objectState;
    throwOnCacheConflict(EntityType.EMAIL, emailState);

    final QueryItem lastQueryItem = getLastQueryItem(queryEntity.id);

    if (!lastQueryItem.emailId.equals(afterEmailId)) {
        throw new CacheConflictException(String.format("Current last email id in cache (%s) doesn't match afterId (%s) from request", lastQueryItem.emailId, afterEmailId));
    }

    if (lastQueryItem.position != queryResult.position - 1) {
        throw new CorruptCacheException(String.format("Unexpected QueryPage. Cache ends with position %d. Page starts at position %d", lastQueryItem.position, queryResult.position));
    }

    if (queryResult.items.length > 0) {
        insert(QueryItemEntity.of(queryEntity.id, queryResult.items, queryResult.position));
    }
}
 
Example #9
Source File: QueryDao.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
@Transaction
public void set(String queryString, QueryResult queryResult) {
    TypedState<Email> emailState = queryResult.objectState;
    throwOnCacheConflict(EntityType.EMAIL, emailState);

    if (queryResult.items.length == 0) {
        deleteQuery(queryString);
        return;
    }

    long queryId = insert(QueryEntity.of(queryString, queryResult.queryState.getState(), queryResult.canCalculateChanges));
    insert(QueryItemEntity.of(queryId, queryResult.items, 0));
}
 
Example #10
Source File: RoomLocalDataStore.java    From ground-android with Apache License 2.0 5 votes vote down vote up
@Transaction
@Override
public Completable applyAndEnqueue(FeatureMutation mutation) {
  try {
    return apply(mutation).andThen(enqueue(mutation));
  } catch (LocalDataStoreException e) {
    return Completable.error(e);
  }
}
 
Example #11
Source File: MailboxDao.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
@Transaction
public void set(List<MailboxEntity> mailboxEntities, String state) {
    if (state != null && state.equals(getState(EntityType.MAILBOX))) {
        Log.d("lttrs","nothing to do. mailboxes with this state have already been set");
        return;
    }
    deleteAll();
    if (mailboxEntities.size() > 0) {
        insert(mailboxEntities);
    }
    insert(new EntityStateEntity(EntityType.MAILBOX, state));
}
 
Example #12
Source File: OverwriteDao.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
@Transaction
public void revertMoveToTrashOverwrites(final Collection<String> threadIds) {
    final int mailboxOverwrites = deleteMailboxOverwritesByThread(threadIds);
    final int queryOverwrites = deleteQueryOverwritesByThread(threadIds);
    if (mailboxOverwrites > 0 || queryOverwrites > 0) {
        LOGGER.info("Deleted {} mailbox overwrites and {} query overwrites for threads {}", mailboxOverwrites, queryOverwrites, threadIds);
    }
}
 
Example #13
Source File: OverwriteDao.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
@Transaction
public void revertMailboxOverwrites(final String threadId) {
    final int mailboxOverwrites = deleteMailboxOverwritesByThread(threadId);
    final int queryOverwrites = deleteQueryOverwritesByThread(threadId, QueryItemOverwriteEntity.Type.MAILBOX);
    if (mailboxOverwrites > 0 || queryOverwrites > 0) {
        LOGGER.info("Deleted {} mailbox overwrites and {} query overwrites for thread {}", mailboxOverwrites, queryOverwrites, threadId);
    }
}
 
Example #14
Source File: AccountDao.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
@Transaction
public List<AccountWithCredentials> insert(String username,
                                           String password,
                                           HttpUrl sessionResource,
                                           String primaryAccountId,
                                           Map<String, Account> accounts) {
    final ImmutableList.Builder<AccountWithCredentials> builder = ImmutableList.builder();
    final long now = System.currentTimeMillis();
    final Long credentialId = insert(new CredentialsEntity(
            username,
            password,
            sessionResource
    ));
    for (Map.Entry<String, Account> entry : accounts.entrySet()) {
        final String accountId = entry.getKey();
        final String name = entry.getValue().getName();
        Long id = insert(new AccountEntity(
                credentialId,
                accountId,
                name,
                accountId.equals(primaryAccountId) ? now + 1 : now
        ));
        builder.add(new AccountWithCredentials(
                id,
                accountId,
                username,
                password,
                sessionResource
        ));
    }
    return builder.build();
}
 
Example #15
Source File: StateDao.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
@Transaction
public QueryStateWrapper getQueryStateWrapper(String queryString) {
    final QueryState queryState = getQueryState(queryString);
    final ObjectsState objectsState = getObjectsState();
    final QueryStateWrapper.UpTo upTo;
    if (queryState == null) {
        return new QueryStateWrapper(null, false, null, objectsState);
    } else {
        upTo = getUpTo(queryString);
        return new QueryStateWrapper(queryState.state, queryState.canCalculateChanges, upTo, objectsState);
    }
}
 
Example #16
Source File: ThreadAndEmailDao.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
@Transaction
public void updateEmails(Update<Email> update, String[] updatedProperties) {
    final String newState = update.getNewTypedState().getState();
    if (newState != null && newState.equals(getState(EntityType.EMAIL))) {
        Log.d("lttrs", "nothing to do. emails already at newest state");
        return;
    }
    final Email[] created = update.getCreated();
    if (created.length > 0) {
        insertEmails(created);
    }
    if (updatedProperties != null) {
        for (Email email : update.getUpdated()) {
            if (!emailExists(email.getId())) {
                LOGGER.warn("skipping updates to email {} because we don’t have that", email.getId());
                continue;
            }
            for (String property : updatedProperties) {
                switch (property) {
                    case "keywords":
                        deleteKeywords(email.getId());
                        insertKeywords(EmailKeywordEntity.of(email));
                        break;
                    case "mailboxIds":
                        deleteMailboxes(email.getId());
                        insertMailboxes(EmailMailboxEntity.of(email));
                        break;
                    default:
                        throw new IllegalArgumentException("Unable to update property '" + property + "'");
                }
            }
            deleteOverwrites(email.getId());
        }
    }
    for (final String id : update.getDestroyed()) {
        deleteEmail(id);
    }
    throwOnUpdateConflict(EntityType.EMAIL, update.getOldTypedState(), update.getNewTypedState());
}
 
Example #17
Source File: RoomLocalDataStore.java    From ground-android with Apache License 2.0 5 votes vote down vote up
@Transaction
@Override
public Completable updateMutations(ImmutableList<Mutation> mutations) {
  return featureMutationDao
      .updateAll(toFeatureMutationEntities(mutations))
      .andThen(
          observationMutationDao
              .updateAll(toObservationMutationEntities(mutations))
              .subscribeOn(schedulers.io()))
      .subscribeOn(schedulers.io());
}
 
Example #18
Source File: RoomLocalDataStore.java    From ground-android with Apache License 2.0 5 votes vote down vote up
@Transaction
@Override
public Completable removePendingMutations(ImmutableList<Mutation> mutations) {
  return featureMutationDao
      .deleteAll(FeatureMutation.ids(mutations))
      .andThen(
          observationMutationDao
              .deleteAll(ObservationMutation.ids(mutations))
              .subscribeOn(schedulers.io()))
      .subscribeOn(schedulers.io());
}
 
Example #19
Source File: RoomLocalDataStore.java    From ground-android with Apache License 2.0 5 votes vote down vote up
@Transaction
@Override
public Completable mergeFeature(Feature feature) {
  // TODO(#109): Once we user can edit feature locally, apply pending mutations before saving.
  return featureDao
      .insertOrUpdate(FeatureEntity.fromFeature(feature))
      .subscribeOn(schedulers.io());
}
 
Example #20
Source File: RoomLocalDataStore.java    From ground-android with Apache License 2.0 5 votes vote down vote up
@Transaction
@Override
public Completable mergeObservation(Observation observation) {
  ObservationEntity observationEntity = ObservationEntity.fromObservation(observation);
  return observationMutationDao
      .findByObservationId(observation.getId())
      .flatMapCompletable(mutations -> mergeObservation(observationEntity, mutations));
}
 
Example #21
Source File: RoomLocalDataStore.java    From ground-android with Apache License 2.0 5 votes vote down vote up
@Transaction
@Override
public Completable applyAndEnqueue(ObservationMutation mutation) {
  try {
    return apply(mutation).andThen(enqueue(mutation));
  } catch (LocalDataStoreException e) {
    return Completable.error(e);
  }
}
 
Example #22
Source File: DaoOperation.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
@Transaction
@Query("SELECT operation.*" +
        ", " + priority + " AS priority" +
        ", account.name AS accountName, folder.name AS folderName" +
        " ,((account.synchronize IS NULL OR account.synchronize)" +
        " AND (NOT folder.account IS NULL OR identity.synchronize IS NULL OR identity.synchronize)) AS synchronize" +
        " FROM operation" +
        " JOIN folder ON folder.id = operation.folder" +
        " LEFT JOIN message ON message.id = operation.message" +
        " LEFT JOIN account ON account.id = operation.account" +
        " LEFT JOIN identity ON identity.id = message.identity" +
        " ORDER BY " + priority + ", id")
LiveData<List<TupleOperationEx>> liveOperations();
 
Example #23
Source File: BackupDao.java    From SAI with GNU General Public License v3.0 4 votes vote down vote up
@Transaction
@Query("SELECT * FROM BackupEntity WHERE package = :pkg ORDER BY export_timestamp DESC")
List<BackupWithComponents> getAllBackupsForPackage(String pkg);
 
Example #24
Source File: UserDao.java    From ground-android with Apache License 2.0 4 votes vote down vote up
@Transaction
@Query("SELECT * FROM user WHERE id = :id")
Maybe<UserEntity> findById(String id);
 
Example #25
Source File: BackupDao.java    From SAI with GNU General Public License v3.0 4 votes vote down vote up
@Transaction
@Query("SELECT * FROM BackupEntity WHERE package = :pkg ORDER BY export_timestamp DESC")
LiveData<List<BackupWithComponents>> getAllBackupsForPackageLiveData(String pkg);
 
Example #26
Source File: DaoMessage.java    From FairEmail with GNU General Public License v3.0 4 votes vote down vote up
@Transaction
@Query("SELECT message.*" +
        ", account.pop AS accountProtocol, account.name AS accountName, COALESCE(identity.color, folder.color, account.color) AS accountColor" +
        ", account.notify AS accountNotify, account.auto_seen AS accountAutoSeen" +
        ", folder.name AS folderName, folder.color AS folderColor, folder.display AS folderDisplay, folder.type AS folderType, folder.unified AS folderUnified, folder.read_only AS folderReadOnly" +
        ", IFNULL(identity.display, identity.name) AS identityName, identity.email AS identityEmail, identity.synchronize AS identitySynchronize" +
        ", message.`from` AS senders" +
        ", message.`to` AS recipients" +
        ", 1 AS count" +
        ", CASE WHEN message.ui_seen THEN 0 ELSE 1 END AS unseen" +
        ", CASE WHEN message.ui_flagged THEN 0 ELSE 1 END AS unflagged" +
        ", (folder.type = '" + EntityFolder.DRAFTS + "') AS drafts" +
        ", (message.ui_encrypt IN (2, 4)) AS signed" +
        ", (message.ui_encrypt IN (1, 3)) AS encrypted" +
        ", 1 AS visible" +
        ", NOT message.ui_seen AS visible_unseen" +
        ", message.total AS totalSize" +
        ", message.priority AS ui_priority" +
        ", message.importance AS ui_importance" +
        " FROM message" +
        " JOIN account_view AS account ON account.id = message.account" +
        " LEFT JOIN identity_view AS identity ON identity.id = message.identity" +
        " JOIN folder_view AS folder ON folder.id = message.folder" +
        " WHERE message.account = :account" +
        " AND message.thread = :thread" +
        " AND (:id IS NULL OR message.id = :id)" +
        " AND (NOT :filter_archive OR folder.type <> '" + EntityFolder.ARCHIVE +
        "' OR (SELECT COUNT(m.id) FROM message m" +
        "   WHERE m.account = message.account" +
        "   AND (m.hash = message.hash OR m.msgid = message.msgid)" +
        "   AND NOT m.ui_hide) = 1)" +
        " AND (NOT message.ui_hide OR :debug)" +
        " ORDER BY CASE WHEN :ascending THEN message.received ELSE -message.received END" +
        ", CASE" +
        " WHEN folder.type = '" + EntityFolder.INBOX + "' THEN 1" +
        " WHEN folder.type = '" + EntityFolder.OUTBOX + "' THEN 2" +
        " WHEN folder.type = '" + EntityFolder.DRAFTS + "' THEN 3" +
        " WHEN folder.type = '" + EntityFolder.SENT + "' THEN 4" +
        " WHEN folder.type = '" + EntityFolder.TRASH + "' THEN 5" +
        " WHEN folder.type = '" + EntityFolder.JUNK + "' THEN 6" +
        " WHEN folder.type = '" + EntityFolder.SYSTEM + "' THEN 7" +
        " WHEN folder.type = '" + EntityFolder.USER + "' THEN 8" +
        " WHEN folder.type = '" + EntityFolder.ARCHIVE + "' THEN 9" +
        " ELSE 999 END")
    // The folder type sort order should match the duplicate algorithm
DataSource.Factory<Integer, TupleMessageEx> pagedThread(
        long account, String thread, Long id,
        boolean filter_archive,
        boolean ascending, boolean debug);
 
Example #27
Source File: ProjectDao.java    From ground-android with Apache License 2.0 4 votes vote down vote up
@Transaction
@Query("SELECT * FROM project")
Single<List<ProjectEntityAndRelations>> getAllProjects();
 
Example #28
Source File: ProjectDao.java    From ground-android with Apache License 2.0 4 votes vote down vote up
@Transaction
@Query("SELECT * FROM project WHERE id = :id")
Maybe<ProjectEntityAndRelations> getProjectById(String id);
 
Example #29
Source File: MoviesDao.java    From PopularMovies with MIT License 4 votes vote down vote up
@Transaction
@Query("SELECT * FROM movie WHERE movie.id= :movieId")
LiveData<MovieDetails> getMovie(long movieId);
 
Example #30
Source File: StuffStore.java    From cwac-saferoom with Apache License 2.0 4 votes vote down vote up
@Transaction
@Query("SELECT * FROM categories WHERE parentId IS NULL")
CategoryTuple findRootCategoryTuple();