1 package org.cacert.gigi.database;
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.sql.Connection;
6 import java.sql.DriverManager;
7 import java.sql.ResultSet;
8 import java.sql.SQLException;
9 import java.sql.Statement;
10 import java.util.HashMap;
11 import java.util.Properties;
12 import java.util.StringJoiner;
13 import java.util.regex.Matcher;
14 import java.util.regex.Pattern;
16 import org.cacert.gigi.database.SQLFileManager.ImportType;
18 public class DatabaseConnection {
20 public static final int CURRENT_SCHEMA_VERSION = 4;
22 public static final int CONNECTION_TIMEOUT = 24 * 60 * 60;
26 private HashMap<String, GigiPreparedStatement> statements = new HashMap<String, GigiPreparedStatement>();
28 private static Properties credentials;
30 private Statement adHoc;
32 public DatabaseConnection() {
34 Class.forName(credentials.getProperty("sql.driver"));
35 } catch (ClassNotFoundException e) {
42 private void tryConnect() {
44 c = DriverManager.getConnection(credentials.getProperty("sql.url") + "?socketTimeout=" + CONNECTION_TIMEOUT, credentials.getProperty("sql.user"), credentials.getProperty("sql.password"));
45 adHoc = c.createStatement();
46 } catch (SQLException e) {
51 public GigiPreparedStatement prepare(String query) {
53 query = preprocessQuery(query);
54 GigiPreparedStatement statement = statements.get(query);
55 if (statement == null) {
57 statement = new GigiPreparedStatement(c.prepareStatement(query, query.startsWith("SELECT ") ? Statement.NO_GENERATED_KEYS : Statement.RETURN_GENERATED_KEYS));
58 } catch (SQLException e) {
61 statements.put(query, statement);
66 public GigiPreparedStatement prepareScrollable(String query) {
68 query = preprocessQuery(query);
69 GigiPreparedStatement statement = statements.get(query);
70 if (statement == null) {
72 statement = new GigiPreparedStatement(c.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY));
73 } catch (SQLException e) {
76 statements.put(query, statement);
81 private long lastAction = System.currentTimeMillis();
83 private void ensureOpen() {
84 if (System.currentTimeMillis() - lastAction > CONNECTION_TIMEOUT * 1000L) {
86 ResultSet rs = adHoc.executeQuery("SELECT 1");
88 lastAction = System.currentTimeMillis();
90 } catch (SQLException e) {
95 lastAction = System.currentTimeMillis();
98 private static ThreadLocal<DatabaseConnection> instances = new ThreadLocal<DatabaseConnection>() {
101 protected DatabaseConnection initialValue() {
102 return new DatabaseConnection();
106 public static DatabaseConnection getInstance() {
107 return instances.get();
110 public static boolean isInited() {
111 return credentials != null;
114 public static void init(Properties conf) {
115 if (credentials != null) {
116 throw new Error("Re-initiaizing is forbidden.");
119 GigiResultSet rs = getInstance().prepare("SELECT version FROM \"schemeVersion\" ORDER BY version DESC LIMIT 1;").executeQuery();
122 version = rs.getInt(1);
124 if (version == CURRENT_SCHEMA_VERSION) {
125 return; // Good to go
127 if (version > CURRENT_SCHEMA_VERSION) {
128 throw new Error("Invalid database version. Please fix this.");
133 public void beginTransaction() throws SQLException {
134 c.setAutoCommit(false);
137 private static void upgrade(int version) {
139 Statement s = getInstance().c.createStatement();
141 while (version < CURRENT_SCHEMA_VERSION) {
142 try (InputStream resourceAsStream = DatabaseConnection.class.getResourceAsStream("upgrade/from_" + version + ".sql")) {
143 if (resourceAsStream == null) {
144 throw new Error("Upgrade script from version " + version + " was not found.");
146 SQLFileManager.addFile(s, resourceAsStream, ImportType.PRODUCTION);
150 s.addBatch("UPDATE schemeVersion SET version='" + version + "'");
151 System.out.println("UPGRADING Database to version " + version);
153 System.out.println("done.");
157 } catch (SQLException e) {
159 } catch (IOException e) {
164 public void commitTransaction() throws SQLException {
166 c.setAutoCommit(true);
169 public void quitTransaction() {
171 if ( !c.getAutoCommit()) {
173 c.setAutoCommit(true);
175 } catch (SQLException e) {
180 public static final String preprocessQuery(String originalQuery) {
181 originalQuery = originalQuery.replace('`', '"');
182 if (originalQuery.matches("^INSERT INTO [^ ]+ SET .*")) {
183 Pattern p = Pattern.compile("INSERT INTO ([^ ]+) SET (.*)");
184 Matcher m = p.matcher(originalQuery);
186 String replacement = "INSERT INTO " + toIdentifier(m.group(1));
187 String[] parts = m.group(2).split(",");
188 StringJoiner columns = new StringJoiner(", ");
189 StringJoiner values = new StringJoiner(", ");
190 for (int i = 0; i < parts.length; i++) {
191 String[] split = parts[i].split("=", 2);
192 columns.add(toIdentifier(split[0]));
193 values.add(split[1]);
195 replacement += "(" + columns.toString() + ") VALUES(" + values.toString() + ")";
201 return originalQuery;
204 private static CharSequence toIdentifier(String ident) {
205 ident = ident.trim();
206 if ( !ident.startsWith("\"")) {
207 ident = "\"" + ident;
209 if ( !ident.endsWith("\"")) {
210 ident = ident + "\"";