@Override
  protected Cursor loadCursor() throws Exception {
    // Log.i("RiaService", "chats base loads cursor");
    String messages = Cache.getTableInfo(MessageContainer.class).getTableName();
    String req =
        "SELECT "
            + BaseColumns._ID
            + ","
            + DbColumns.ThreadIdCol
            + ","
            + DbColumns.MsgBodyCol
            + ","
            + DbColumns.FromJidCol
            + ","
            + "MAX("
            + DbColumns.CreatedCol
            + ") AS "
            + DbColumns.CreatedCol
            + " FROM "
            + messages
            + " WHERE "
            + DbColumns.ChatTypeCol
            + "="
            + MessageContainer.CHAT_SIMPLE
            + " GROUP BY "
            + DbColumns.ThreadIdCol
            + " ORDER BY "
            + DbColumns.CreatedCol
            + " DESC ";
    /*boolean isMoved = resultCursor.moveToPosition(0);
    int count = resultCursor.getCount();*/

    return Cache.openDatabase().rawQuery(req, null);
  }
Example #2
0
  @SuppressWarnings("unchecked")
  public static <T extends Model> List<T> processCursor(
      Class<? extends Model> type, Cursor cursor) {
    final List<T> entities = new ArrayList<T>();

    try {
      Constructor<?> entityConstructor = type.getConstructor();

      if (cursor.moveToFirst()) {
        do {
          Model entity = Cache.getEntity(type, cursor.getLong(cursor.getColumnIndex("Id")));
          if (entity == null) {
            entity = (T) entityConstructor.newInstance();
          }

          entity.loadFromCursor(cursor);
          entities.add((T) entity);
        } while (cursor.moveToNext());
      }

    } catch (Exception e) {
      Log.e("Failed to process cursor.", e);
    }

    return entities;
  }
Example #3
0
  private boolean executeMigrations(SQLiteDatabase db, int oldVersion, int newVersion) {
    boolean migrationExecuted = false;
    try {
      final List<String> files = Arrays.asList(Cache.getContext().getAssets().list(MIGRATION_PATH));
      Collections.sort(files, new NaturalOrderComparator());

      db.beginTransaction();
      try {
        for (String file : files) {
          try {
            final int version = Integer.valueOf(file.replace(".sql", ""));

            if (version > oldVersion && version <= newVersion) {
              executeSqlScript(db, file);
              migrationExecuted = true;

              Log.i(file + " executed succesfully.");
            }
          } catch (NumberFormatException e) {
            Log.w("Skipping invalidly named file: " + file, e);
          }
        }
        db.setTransactionSuccessful();
      } finally {
        db.endTransaction();
      }
    } catch (IOException e) {
      Log.e("Failed to execute migrations.", e);
    }

    return migrationExecuted;
  }
Example #4
0
  public static <T extends Model> List<T> rawQuery(
      Class<? extends Model> type, String sql, String[] selectionArgs) {
    Cursor cursor = Cache.openDatabase().rawQuery(sql, selectionArgs);
    List<T> entities = processCursor(type, cursor);
    cursor.close();

    return entities;
  }
Example #5
0
 private void executeCreate(SQLiteDatabase db) {
   db.beginTransaction();
   try {
     for (TableInfo tableInfo : Cache.getTableInfos()) {
       db.execSQL(SQLiteUtils.createTableDefinition(tableInfo));
     }
     db.setTransactionSuccessful();
   } finally {
     db.endTransaction();
   }
 }
Example #6
0
  private void executeCreateIndex(SQLiteDatabase db) {
    db.beginTransaction();
    try {
      for (TableInfo tableInfo : Cache.getTableInfos()) {
        String[] definitions = SQLiteUtils.createIndexDefinition(tableInfo);

        for (String definition : definitions) {
          db.execSQL(definition);
        }
      }
      db.setTransactionSuccessful();
    } finally {
      db.endTransaction();
    }
  }
Example #7
0
  private void executeSqlScript(SQLiteDatabase db, String file) {

    InputStream stream = null;

    try {
      stream = Cache.getContext().getAssets().open(MIGRATION_PATH + "/" + file);

      if (Configuration.SQL_PARSER_DELIMITED.equalsIgnoreCase(mSqlParser)) {
        executeDelimitedSqlScript(db, stream);

      } else {
        executeLegacySqlScript(db, stream);
      }

    } catch (IOException e) {
      Log.e("Failed to execute " + file, e);

    } finally {
      IOUtils.closeQuietly(stream);
    }
  }
  Cursor retrieveDataFromRoster() {

    String resultRecords;
    Cursor resultCursor = null;

    BaseTabFragment.FragIds fragIds = BaseTabFragment.FragIds.values()[tabIdloader];

    switch (fragIds) {
      case CONTACTS_FRAGMENT:
        {
          String groupToExcludeRequest =
              new Select()
                  .from(RosterGroupModel.class)
                  .where(DbColumns.NameCol + "='" + SmackRosterManager.FIRST_SORTED_GROUP + "'")
                  .toSql();
          Cursor groupCursor = Cache.openDatabase().rawQuery(groupToExcludeRequest, null);
          List<RosterGroupModel> groupModelList =
              SQLiteUtils.processCursor(RosterGroupModel.class, groupCursor);
          groupCursor.close();
          long groupToExcludeId = 0;
          if (groupModelList != null && groupModelList.size() > 0) {
            groupToExcludeId = groupModelList.get(0).getId();
          }
          From from = new Select().from(RosterEntryModel.class);

          String sqlReqText = "";
          if (groupToExcludeId != 0) {
            sqlReqText += " RosterGroupModel != " + groupToExcludeId;
          }

          if (!TextUtils.isEmpty(title_to_search)) {
            if (!TextUtils.isEmpty(sqlReqText)) {
              sqlReqText += " and ";
            }
            sqlReqText += "Name LIKE '%" + title_to_search.toLowerCase(Locale.getDefault()) + "%'";
          }

          if (jidToExcludeList != null && jidToExcludeList.size() > 0) {
            for (String jid : jidToExcludeList) {
              sqlReqText += " and " + DbColumns.FromJidCol + " != '" + jid + "'";
            }
          }

          if (!TextUtils.isEmpty(sqlReqText)) {
            from.where(sqlReqText);
          }

          String queryResults = from.orderBy("Name ASC").toSql();
          resultCursor = Cache.openDatabase().rawQuery(queryResults, null);

          // listCursor = getContactsList(queryResults);
          // listCursor = fetchResultCursor(RosterEntryModel.class);
          // SQLiteUtils.processCursor(RosterEntryModel.class, listCursor);
        }
        break;
      case ROBOTS_FRAGMENT:
        {
          //  List<RosterEntry> rosterEntries =
          /*RosterGroupModel rosterGroupModel = new Select().from(RosterGroupModel.class)//.where("name = ?", getContext().getString(R.string.robots))
                  .orderBy("name ASC")
                  .executeSingle();
          if (rosterGroupModel != null) {
              listCursor = rosterGroupModel.items();
          }*/
          String groupTableName = Cache.getTableInfo(RosterGroupModel.class).getTableName();
          resultRecords =
              new Select()
                  .from(RosterEntryModel.class)
                  .where(
                      "RosterEntryModels.RosterGroupModel IN (SELECT _id"
                          + " FROM "
                          + groupTableName
                          + " WHERE name ='"
                          + SmackRosterManager.FIRST_SORTED_GROUP
                          + "')")
                  .orderBy("name ASC")
                  .toSql();

          //  tableName = Cache.getTableInfo(RosterGroupModel.class).getTableName();
          //  resultRecords = new Select().from(RosterGroupModel.class).where("name = ?",
          // getContext().getString(R.string.robots)).toSql();
          resultCursor = Cache.openDatabase().rawQuery(resultRecords, null);
        }
        break;
      case GROUPS_FRAGMENT:
        {
          /*List<RosterGroupModel> queryResults = new Select().from(RosterGroupModel.class)
                  .orderBy("name ASC").execute();

          for (RosterGroupModel group : queryResults) {
              group.items()
              Collections.sort(group.getEntries(), new EntrySortBasedOnName());
          }*/
          String tableName = Cache.getTableInfo(RosterGroupModel.class).getTableName();
          resultRecords = new Select("*").from(RosterGroupModel.class).toSql();
          resultCursor = Cache.openDatabase().rawQuery(resultRecords, null);
        }
        break;
    }

    return resultCursor;
  }
Example #9
0
 public static void execSql(String sql, Object[] bindArgs) {
   Cache.openDatabase().execSQL(sql, bindArgs);
 }
Example #10
0
 public static void execSql(String sql) {
   Cache.openDatabase().execSQL(sql);
 }
Example #11
0
  @SuppressWarnings("unchecked")
  public static String createColumnDefinition(TableInfo tableInfo, Field field) {
    StringBuilder definition = new StringBuilder();

    Class<?> type = field.getType();
    final String name = tableInfo.getColumnName(field);
    final TypeSerializer typeSerializer = Cache.getParserForType(field.getType());
    final Column column = field.getAnnotation(Column.class);

    if (typeSerializer != null) {
      type = typeSerializer.getSerializedType();
    }

    if (TYPE_MAP.containsKey(type)) {
      definition.append(name);
      definition.append(" ");
      definition.append(TYPE_MAP.get(type).toString());
    } else if (ReflectionUtils.isModel(type)) {
      definition.append(name);
      definition.append(" ");
      definition.append(SQLiteType.INTEGER.toString());
    } else if (ReflectionUtils.isSubclassOf(type, Enum.class)) {
      definition.append(name);
      definition.append(" ");
      definition.append(SQLiteType.TEXT.toString());
    }

    if (!TextUtils.isEmpty(definition)) {
      if (column.length() > -1) {
        definition.append("(");
        definition.append(column.length());
        definition.append(")");
      }

      if (name.equals("Id")) {
        definition.append(" PRIMARY KEY AUTOINCREMENT");
      }

      if (column.notNull()) {
        definition.append(" NOT NULL ON CONFLICT ");
        definition.append(column.onNullConflict().toString());
      }

      if (column.unique()) {
        definition.append(" UNIQUE ON CONFLICT ");
        definition.append(column.onUniqueConflict().toString());
      }

      if (FOREIGN_KEYS_SUPPORTED && ReflectionUtils.isModel(type)) {
        definition.append(" REFERENCES ");
        definition.append(Cache.getTableInfo((Class<? extends Model>) type).getTableName());
        definition.append("(Id)");
        definition.append(" ON DELETE ");
        definition.append(column.onDelete().toString().replace("_", " "));
        definition.append(" ON UPDATE ");
        definition.append(column.onUpdate().toString().replace("_", " "));
      }
    } else {
      Log.e("No type mapping for: " + type.toString());
    }

    return definition.toString();
  }