0d8053294af772a9514996a44ac09c21ed7a92fb
[org.ibex.mail.git] / src / org / ibex / mail / SqliteMailbox.java
1 package org.ibex.mail;
2
3 import org.ibex.util.*;
4 import org.ibex.io.Fountain;
5 import org.ibex.io.Stream;
6 import java.sql.Timestamp;
7 import java.sql.*;
8 import java.net.*;
9 import java.io.*;
10 import java.util.*;
11
12
13 public class SqliteMailbox extends Mailbox.Default implements MailTree {
14
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; }
20
21
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[] {
26         "uid_",
27         "messageid_",
28         "flags_",
29         /*
30         "from_",
31         "to_",
32         "subject_",
33         "date_"
34         */
35     };
36     
37     /**
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
47      *   SQLITE_FULL error.
48      */
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_";
52
53     private final int uidValidity;
54     private final File file;
55     public  int uidValidity()  { return uidValidity; }
56
57     public SqliteMailbox(String filename) throws SQLException {
58         try {
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();
64             if (!rs.next()) {
65                 this.uidValidity = new Random().nextInt();
66                 PreparedStatement ps = conn.prepareStatement("insert into uidvalidity (uidvalidity) values (?)");
67                 ps.setInt(1, uidValidity);
68                 ps.executeUpdate();
69             } else {
70                 this.uidValidity = rs.getInt(1);
71             }
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();
75         }
76         catch (SQLException e) { throw new RuntimeException(e); }
77         catch (ClassNotFoundException e) { throw new RuntimeException(e); }
78     }
79
80     public int uidNext() {
81         try {
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); }
87     }
88
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 ";
95             whereClause += "(";
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];
100             whereClause += ")";
101             needsOr = true;
102         }
103         return whereClause;
104     }
105     private static String joinWith(String op, Query[] q) throws UnsupportedQueryException {
106         boolean add = false;
107         StringBuffer sb = new StringBuffer();
108         for(int i=0; i<q.length; i++) {
109             if (add) sb.append(" " + op);
110             sb.append(" (");
111             sb.append(getWhereClause(q[i]));
112             sb.append(")");
113             add = true;
114         }
115         return sb.toString();
116     }
117     private static String getWhereClause(Query q) throws UnsupportedQueryException {
118         switch(q.type) {
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)";
130                 /*
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;
138                 */
139             default: {
140                 Log.info(SqliteMailbox.class, "resorting to superclass: " + q.type);
141                 throw new UnsupportedQueryException();
142             }
143         }
144     }
145     private static class UnsupportedQueryException extends Exception { }
146     public Mailbox.Iterator iterator(Query q) {
147         try {
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);
153         }
154     }
155     public int count(Query q) {
156         try {
157             String whereClause = getWhereClause(q);
158             Log.info(this, "whereClause = " + whereClause);
159             try {
160                 ResultSet rs = conn.prepareStatement("select count(*) from mail where " + whereClause).executeQuery();
161                 rs.next();
162                 return rs.getInt(1);
163             } catch (Exception e) { throw new RuntimeException(e); }
164         } catch (UnsupportedQueryException _) {
165             return super.count(q);
166         }
167     }
168     public void             insert(Message m, int flags) {
169         try {
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);
180             add.executeUpdate();
181         } catch (Exception e) { throw new RuntimeException(e); }
182     }
183
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;
188         private int flags;
189         private Message m  = null;
190         private int uid = -1;
191         private String whereClause;
192         public SqliteJdbcIterator() { this(""); }
193         public SqliteJdbcIterator(String whereClause) {
194             try {
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); }
199         }
200         public Message cur()    {
201             try {
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));
205
206                 ResultSet rs2 = query.executeQuery();
207                 if (!rs2.next()) {
208                     Log.error("XXX", "should not happen");
209                     return null;
210                 }
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);
215
216                 return m;
217             } catch (Exception e) { throw new RuntimeException(e); }
218         }
219         public int     getFlags()   {
220             try { return rs.getInt("flags_"); } catch (Exception e) { throw new RuntimeException(e); }
221         }
222         public void    setFlags(int flags) {
223             try {
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); }
232         }
233         public Headers head()       { return cur().headers; }
234         public boolean next()       {
235             try { m = null; uid = -1; count++;
236             boolean ret = rs.next();
237             return ret;
238             } catch (Exception e) { throw new RuntimeException(e); } }
239         public int     uid()        {
240             if (uid == -1)
241                 try { uid = rs.getInt("uid_"); } catch (Exception e) { throw new RuntimeException(e); }
242             return uid;
243         }
244         public int     imapNumber() {
245             if ("".equals(whereClause)) return count;
246             try {
247                 ResultSet rs = conn.prepareStatement("select count(*) from mail where uid_ <= " + uid()).executeQuery();
248                 rs.next();
249                 return rs.getInt(1);
250             } catch (Exception e) { throw new RuntimeException(e); }
251         }
252         public int     nntpNumber() { return uid(); }
253         public void    delete()     {
254             try {
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); }
259         }
260     }
261
262
263 }