+ private static String set(int[] set, String arg) {
+ String whereClause = "";
+ boolean needsOr = false;
+ for(int i=0; i<set.length; i+=2) {
+ if (needsOr) whereClause += " or ";
+ whereClause += "(";
+ whereClause += arg+">=" + set[i];
+ whereClause += " and ";
+ while(i+2 < set.length && set[i+2] == (set[i+1]+1)) i += 2;
+ whereClause += arg+"<=" + set[i+1];
+ whereClause += ")";
+ needsOr = true;
+ }
+ return whereClause;
+ }
+ private static String joinWith(String op, Query[] q) throws UnsupportedQueryException {
+ boolean add = false;
+ StringBuffer sb = new StringBuffer();
+ for(int i=0; i<q.length; i++) {
+ if (add) sb.append(" " + op);
+ sb.append(" (");
+ sb.append(getWhereClause(q[i]));
+ sb.append(")");
+ add = true;
+ }
+ return sb.toString();
+ }
+ private static String getWhereClause(Query q) throws UnsupportedQueryException {
+ switch(q.type) {
+ case Query.NOT: return "not ("+getWhereClause(q.q[0])+")";
+ case Query.AND: return joinWith("and", q.q);
+ case Query.OR: return joinWith("or", q.q);
+ case Query.ALL: return "1=1";
+ case Query.UID: return set(q.set, "uid_");
+ case Query.DELETED: return "((flags_ & "+(Mailbox.Flag.DELETED)+")!=0)";
+ case Query.SEEN: return "((flags_ & "+(Mailbox.Flag.SEEN)+")!=0)";
+ case Query.FLAGGED: return "((flags_ & "+(Mailbox.Flag.FLAGGED)+")!=0)";
+ case Query.DRAFT: return "((flags_ & "+(Mailbox.Flag.DRAFT)+")!=0)";
+ case Query.ANSWERED: return "((flags_ & "+(Mailbox.Flag.ANSWERED)+")!=0)";
+ case Query.RECENT: return "((flags_ & "+(Mailbox.Flag.RECENT)+")!=0)";
+ /*
+ public static final int SENT = 5;
+ public static final int ARRIVAL = 6;
+ public static final int HEADER = 7;
+ public static final int SIZE = 8;
+ public static final int BODY = 9;
+ public static final int FULL = 10;
+ public static final int IMAPNUM = 11;
+ */
+ default: {
+ Log.info(SqliteMailbox.class, "resorting to superclass: " + q.type);
+ throw new UnsupportedQueryException();
+ }
+ }
+ }
+ private static class UnsupportedQueryException extends Exception { }
+ public Mailbox.Iterator iterator(Query q) {
+ try {
+ String whereClause = getWhereClause(q);
+ Log.info(this, "whereClause = " + whereClause);
+ return new SqliteJdbcIterator("where "+whereClause+";");
+ } catch (UnsupportedQueryException _) {
+ return super.iterator(q);
+ }
+ }
+ public int count(Query q) {
+ try {
+ String whereClause = getWhereClause(q);
+ Log.info(this, "whereClause = " + whereClause);
+ try {
+ ResultSet rs = conn.prepareStatement("select count(*) from mail where " + whereClause).executeQuery();
+ rs.next();
+ return rs.getInt(1);
+ } catch (Exception e) { throw new RuntimeException(e); }
+ } catch (UnsupportedQueryException _) {
+ return super.count(q);
+ }
+ }