4 import org.ibex.mail.protocol.*;
5 import org.ibex.util.*;
11 import java.sql.Timestamp;
12 import java.sql.Connection;
14 public class SqliteTable {
16 protected Connection conn;
17 private String filename;
18 private String reapTable;
19 private String reapColumn;
21 // check upstream: PRAGMA encoding = "UTF-8";
23 // PRAGMA auto_vacuum=1 (can only be set before any tables are created)
24 // periodic "PRAGMA integrity_check; "?
26 public void setCacheSize(int kilobytes) throws SQLException {
27 conn.prepareStatement("PRAGMA cache_size="+Math.ceil(kilobytes/1.5)+";").executeUpdate();
30 public SqliteTable(String filename, String[] tables, String reapTable, String reapColumn) {
31 this(filename, tables, false, reapTable, reapColumn);
33 public SqliteTable(String filename, String[] tables, boolean fastButDangerous,
34 String reapTable, String reapColumn) {
35 this.filename = filename;
37 Class.forName("org.sqlite.JDBC");
38 conn = DriverManager.getConnection("jdbc:sqlite:"+filename);
39 for(String s : tables)
40 conn.prepareStatement(s).executeUpdate();
41 conn.prepareStatement("PRAGMA temp_store = MEMORY").executeUpdate();
42 conn.prepareStatement("PRAGMA page_size=4096").executeUpdate();
43 conn.prepareStatement("PRAGMA cache_size=2000").executeUpdate();
45 conn.prepareStatement("PRAGMA synchronous = OFF").executeUpdate();
47 catch (SQLException e) { throw new RuntimeException(e); }
48 catch (ClassNotFoundException e) { throw new RuntimeException(e); }
49 this.reapTable = reapTable;
50 this.reapColumn = reapColumn;
51 if (reapTable != null && reapColumn != null)
55 public static final int REAPER_INTERVAL_SECONDS = 60 * 60;
57 private class Reaper extends Thread {
62 try { Thread.sleep(1000 * REAPER_INTERVAL_SECONDS); } catch (Exception e) { };
63 Log.warn(Reaper.class, filename + " reaping...");
64 long when = System.currentTimeMillis();
65 when -= 5 * 24 * 60 * 60 * 1000;
66 synchronized(SqliteTable.this) {
67 PreparedStatement ps = conn.prepareStatement("select count(*) from "+reapTable+" where "+reapColumn+"<?");
68 ps.setTimestamp(1, new Timestamp(when));
69 ResultSet rs = ps.executeQuery();
71 Log.warn(Reaper.class, filename + " reaping " + rs.getInt(1) + " entries");
72 Log.warn(Reaper.class, filename + ": " + "delete from "+reapTable+" where "+reapColumn+"<"+when);
73 ps = conn.prepareStatement("delete from "+reapTable+" where "+reapColumn+"<?");
74 ps.setTimestamp(1, new Timestamp(when));
75 int rows = ps.executeUpdate();
76 Log.warn(Reaper.class, filename + " done reaping; removed " + rows + " rows");
78 } catch (Exception e) { Log.error(Reaper.class, e); }