de.greenrobot.dao.query.CountQuery Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of greendao-encryption Show documentation
Show all versions of greendao-encryption Show documentation
greenDAO is a light and fast ORM for Android
package de.greenrobot.dao.query;
import android.database.Cursor;
import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.DaoException;
public class CountQuery extends AbstractQuery {
private final static class QueryData extends AbstractQueryData> {
private QueryData(AbstractDao dao, String sql, String[] initialValues) {
super(dao, sql, initialValues);
}
@Override
protected CountQuery createQuery() {
return new CountQuery(this, dao, sql, initialValues.clone());
}
}
static CountQuery create(AbstractDao dao, String sql, Object[] initialValues) {
QueryData queryData = new QueryData(dao, sql, toStringArray(initialValues));
return queryData.forCurrentThread();
}
private final QueryData queryData;
private CountQuery(QueryData queryData, AbstractDao dao, String sql, String[] initialValues) {
super(dao, sql, initialValues);
this.queryData = queryData;
}
public CountQuery forCurrentThread() {
return queryData.forCurrentThread(this);
}
/** Returns the count (number of results matching the query). Uses SELECT COUNT (*) sematics. */
public long count() {
checkThread();
Cursor cursor = dao.getDatabase().rawQuery(sql, parameters);
try {
if (!cursor.moveToNext()) {
throw new DaoException("No result for count");
} else if (!cursor.isLast()) {
throw new DaoException("Unexpected row count: " + cursor.getCount());
} else if (cursor.getColumnCount() != 1) {
throw new DaoException("Unexpected column count: " + cursor.getColumnCount());
}
return cursor.getLong(0);
} finally {
cursor.close();
}
}
}