3 import org.ibex.util.*;
4 import org.ibex.io.Fountain;
5 import org.ibex.io.Stream;
6 import java.sql.Timestamp;
13 public class SqliteMailbox extends Mailbox.Default implements MailTree {
15 public MailTree slash(String name, boolean create) { return null; }
16 public String[] children() { return new String[0]; }
17 public void rmdir(String subdir) { throw new RuntimeException("invalid"); }
18 public void rename(String subdir, MailTree newParent, String newName) { throw new RuntimeException("invalid"); }
19 public Mailbox getMailbox() { return this; }
22 private Connection conn;
23 private static final String columns =
24 " messageid_, from_,to_,date_,subject_,headers_,body_,flags_";
25 private static final String[] indexedColumns = new String[] {
38 * from http://www.sqlite.org/autoinc.html
39 * "If a column has the type INTEGER PRIMARY KEY AUTOINCREMENT
40 * then a slightly different ROWID selection algorithm is
41 * used. The ROWID chosen for the new row is one larger than the
42 * largest ROWID that has ever before existed in that same
43 * table. If the table has never before contained any data, then
44 * a ROWID of 1 is used. If the table has previously held a row
45 * with the largest possible ROWID, then new INSERTs are not
46 * allowed and any attempt to insert a new row will fail with an
49 // FIXME: should messageid_ be decared unique?
50 private static final String columns_ =
51 "uid_ INTEGER PRIMARY KEY AUTOINCREMENT, messageid_ unique,from_,to_,date_,subject_,headers_,body_,flags_";
53 private final int uidValidity;
54 private final File file;
55 public int uidValidity() { return uidValidity; }
57 public SqliteMailbox(String filename) throws SQLException {
59 this.file = new File(filename);
60 Class.forName("org.sqlite.JDBC");
61 conn = DriverManager.getConnection("jdbc:sqlite:"+filename);
62 conn.prepareStatement("create table if not exists uidvalidity (uidvalidity)").executeUpdate();
63 ResultSet rs = conn.prepareStatement("select uidvalidity from uidvalidity").executeQuery();
65 this.uidValidity = new Random().nextInt();
66 PreparedStatement ps = conn.prepareStatement("insert into uidvalidity (uidvalidity) values (?)");
67 ps.setInt(1, uidValidity);
70 this.uidValidity = rs.getInt(1);
72 conn.prepareStatement("create table if not exists 'mail' ("+columns_+")").executeUpdate();
73 for(String name : indexedColumns)
74 conn.prepareStatement("create index if not exists "+name+"index on mail("+name+");").executeUpdate();
76 catch (SQLException e) { throw new RuntimeException(e); }
77 catch (ClassNotFoundException e) { throw new RuntimeException(e); }
80 public int uidNext() {
82 PreparedStatement q = conn.prepareStatement("select max(uid_) from mail");
83 ResultSet rs = q.executeQuery();
84 if (!rs.next()) return -1;
85 return rs.getInt(1)+1;
86 } catch (Exception e) { throw new RuntimeException(e); }
89 public Mailbox.Iterator iterator() { return new SqliteJdbcIterator(); }
90 private static String set(int[] set, String arg) {
91 String whereClause = "";
92 boolean needsOr = false;
93 for(int i=0; i<set.length; i+=2) {
94 if (needsOr) whereClause += " or ";
96 whereClause += arg+">=" + set[i];
97 whereClause += " and ";
98 while(i+2 < set.length && set[i+2] == (set[i+1]+1)) i += 2;
99 whereClause += arg+"<=" + set[i+1];
105 private static String joinWith(String op, Query[] q) throws UnsupportedQueryException {
107 StringBuffer sb = new StringBuffer();
108 for(int i=0; i<q.length; i++) {
109 if (add) sb.append(" " + op);
111 sb.append(getWhereClause(q[i]));
115 return sb.toString();
117 private static String getWhereClause(Query q) throws UnsupportedQueryException {
119 case Query.NOT: return "not ("+getWhereClause(q.q[0])+")";
120 case Query.AND: return joinWith("and", q.q);
121 case Query.OR: return joinWith("or", q.q);
122 case Query.ALL: return "1=1";
123 case Query.UID: return set(q.set, "uid_");
124 case Query.DELETED: return "((flags_ & "+(Mailbox.Flag.DELETED)+")!=0)";
125 case Query.SEEN: return "((flags_ & "+(Mailbox.Flag.SEEN)+")!=0)";
126 case Query.FLAGGED: return "((flags_ & "+(Mailbox.Flag.FLAGGED)+")!=0)";
127 case Query.DRAFT: return "((flags_ & "+(Mailbox.Flag.DRAFT)+")!=0)";
128 case Query.ANSWERED: return "((flags_ & "+(Mailbox.Flag.ANSWERED)+")!=0)";
129 case Query.RECENT: return "((flags_ & "+(Mailbox.Flag.RECENT)+")!=0)";
131 public static final int SENT = 5;
132 public static final int ARRIVAL = 6;
133 public static final int HEADER = 7;
134 public static final int SIZE = 8;
135 public static final int BODY = 9;
136 public static final int FULL = 10;
137 public static final int IMAPNUM = 11;
140 Log.info(SqliteMailbox.class, "resorting to superclass: " + q.type);
141 throw new UnsupportedQueryException();
145 private static class UnsupportedQueryException extends Exception { }
146 public Mailbox.Iterator iterator(Query q) {
148 String whereClause = getWhereClause(q);
149 Log.info(this, "whereClause = " + whereClause);
150 return new SqliteJdbcIterator("where "+whereClause+";");
151 } catch (UnsupportedQueryException _) {
152 return super.iterator(q);
155 public int count(Query q) {
157 String whereClause = getWhereClause(q);
158 Log.info(this, "whereClause = " + whereClause);
160 ResultSet rs = conn.prepareStatement("select count(*) from mail where " + whereClause).executeQuery();
163 } catch (Exception e) { throw new RuntimeException(e); }
164 } catch (UnsupportedQueryException _) {
165 return super.count(q);
168 public void insert(Message m, int flags) {
170 PreparedStatement add =
171 conn.prepareStatement("insert or replace into 'mail' ("+columns+") values (?,?,?,?,?,?,?,?)");
172 add.setString(1, m.messageid+"");
173 add.setString(2, m.from+"");
174 add.setString(3, m.to+"");
175 add.setString(4, m.date+"");
176 add.setString(5, m.subject+"");
177 add.setString(6, streamToString(m.headers.getStream()));
178 add.setString(7, streamToString(m.getBody().getStream()));
179 add.setInt (8, flags);
181 } catch (Exception e) { throw new RuntimeException(e); }
184 private class SqliteJdbcIterator implements Mailbox.Iterator {
185 // could be more efficient in a ton of ways
186 private ResultSet rs;
187 private int count = 0;
189 private Message m = null;
190 private int uid = -1;
191 private String whereClause;
192 public SqliteJdbcIterator() { this(""); }
193 public SqliteJdbcIterator(String whereClause) {
195 this.whereClause = whereClause;
196 PreparedStatement query = conn.prepareStatement("select messageid_,uid_,flags_ from 'mail' "+whereClause);
197 rs = query.executeQuery();
198 } catch (Exception e) { throw new RuntimeException(e); }
200 public Message cur() {
202 if (m!=null) return m;
203 PreparedStatement query = conn.prepareStatement("select headers_,body_,flags_ from 'mail' where messageid_=?");
204 query.setString(1, rs.getString(1));
206 ResultSet rs2 = query.executeQuery();
208 Log.error("XXX", "should not happen");
211 m = Message.newMessage(Fountain.Util.concat(Fountain.Util.create(rs2.getString(1)),
212 Fountain.Util.create("\r\n\r\n"),
213 Fountain.Util.create(rs2.getString(2))));
214 flags = rs2.getInt(3);
217 } catch (Exception e) { throw new RuntimeException(e); }
219 public int getFlags() {
220 try { return rs.getInt("flags_"); } catch (Exception e) { throw new RuntimeException(e); }
222 public void setFlags(int flags) {
224 int oldflags = rs.getInt("flags_");
225 if (oldflags==flags) return;
226 Log.info(this, "setflags (old="+oldflags+")" + "update mail set flags_="+(flags)+" where uid_="+uid()+"");
227 PreparedStatement update = conn.prepareStatement("update mail set flags_=? where uid_=?");
228 update.setInt(1, flags);
229 update.setInt(2, uid());
230 update.executeUpdate();
231 } catch (Exception e) { throw new RuntimeException(e); }
233 public Headers head() { return cur().headers; }
234 public boolean next() {
235 try { m = null; uid = -1; count++;
236 boolean ret = rs.next();
238 } catch (Exception e) { throw new RuntimeException(e); } }
241 try { uid = rs.getInt("uid_"); } catch (Exception e) { throw new RuntimeException(e); }
244 public int imapNumber() {
245 if ("".equals(whereClause)) return count;
247 ResultSet rs = conn.prepareStatement("select count(*) from mail where uid_ <= " + uid()).executeQuery();
250 } catch (Exception e) { throw new RuntimeException(e); }
252 public int nntpNumber() { return uid(); }
253 public void delete() {
255 PreparedStatement update = conn.prepareStatement("delete from mail where uid_=?");
256 update.setInt(1, uid());
257 update.executeUpdate();
258 } catch (Exception e) { throw new RuntimeException(e); }