1 package org.cacert.gigi.database;
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.io.PrintWriter;
6 import java.sql.Connection;
7 import java.sql.DriverManager;
8 import java.sql.PreparedStatement;
9 import java.sql.ResultSet;
10 import java.sql.SQLException;
11 import java.sql.Statement;
12 import java.util.HashMap;
13 import java.util.HashSet;
14 import java.util.Map.Entry;
15 import java.util.Properties;
16 import java.util.StringJoiner;
17 import java.util.regex.Matcher;
18 import java.util.regex.Pattern;
20 import org.cacert.gigi.database.SQLFileManager.ImportType;
22 public class DatabaseConnection {
24 public static final int MAX_CACHED_INSTANCES = 3;
26 private static class StatementDescriptor {
34 PreparedStatement target;
36 public StatementDescriptor(String query, boolean scrollable) {
38 this.scrollable = scrollable;
42 public synchronized void instanciate(Connection c) throws SQLException {
44 target = c.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
46 target = c.prepareStatement(query, query.startsWith("SELECT ") ? Statement.NO_GENERATED_KEYS : Statement.RETURN_GENERATED_KEYS);
51 public synchronized PreparedStatement getTarget() {
55 public synchronized void increase() {
57 throw new IllegalStateException();
63 public int hashCode() {
66 result = prime * result + instance;
67 result = prime * result + ((query == null) ? 0 : query.hashCode());
68 result = prime * result + (scrollable ? 1231 : 1237);
73 public boolean equals(Object obj) {
80 if (getClass() != obj.getClass()) {
83 StatementDescriptor other = (StatementDescriptor) obj;
84 if (instance != other.instance) {
88 if (other.query != null) {
91 } else if ( !query.equals(other.query)) {
94 if (scrollable != other.scrollable) {
102 public static final int CURRENT_SCHEMA_VERSION = 8;
104 public static final int CONNECTION_TIMEOUT = 24 * 60 * 60;
106 private Connection c;
108 private HashMap<StatementDescriptor, PreparedStatement> statements = new HashMap<StatementDescriptor, PreparedStatement>();
110 HashSet<PreparedStatement> underUse = new HashSet<>();
112 private static Properties credentials;
114 private Statement adHoc;
116 public DatabaseConnection() {
118 Class.forName(credentials.getProperty("sql.driver"));
119 } catch (ClassNotFoundException e) {
126 private void tryConnect() {
128 c = DriverManager.getConnection(credentials.getProperty("sql.url") + "?socketTimeout=" + CONNECTION_TIMEOUT, credentials.getProperty("sql.user"), credentials.getProperty("sql.password"));
129 adHoc = c.createStatement();
130 } catch (SQLException e) {
135 protected synchronized PreparedStatement prepareInternal(String query) throws SQLException {
136 return prepareInternal(query, false);
139 protected synchronized PreparedStatement prepareInternal(String query, boolean scrollable) throws SQLException {
142 query = preprocessQuery(query);
143 StatementDescriptor searchHead = new StatementDescriptor(query, scrollable);
144 PreparedStatement statement = null;
145 while (statement == null) {
146 statement = statements.get(searchHead);
147 if (statement == null) {
148 searchHead.instanciate(c);
149 statement = searchHead.getTarget();
150 if (searchHead.instance >= MAX_CACHED_INSTANCES) {
153 underUse.add(statement);
154 statements.put(searchHead, statement);
155 } else if (underUse.contains(statement)) {
156 searchHead.increase();
159 underUse.add(statement);
165 protected synchronized PreparedStatement prepareInternalScrollable(String query) throws SQLException {
166 return prepareInternal(query, true);
169 private long lastAction = System.currentTimeMillis();
171 private void ensureOpen() {
172 if (System.currentTimeMillis() - lastAction > CONNECTION_TIMEOUT * 1000L) {
174 ResultSet rs = adHoc.executeQuery("SELECT 1");
176 lastAction = System.currentTimeMillis();
178 } catch (SQLException e) {
183 lastAction = System.currentTimeMillis();
186 private static volatile DatabaseConnection instance;
188 public static synchronized DatabaseConnection getInstance() {
189 if (instance == null) {
190 instance = new DatabaseConnection();
195 public static boolean isInited() {
196 return credentials != null;
199 public static void init(Properties conf) {
200 if (credentials != null) {
201 throw new Error("Re-initiaizing is forbidden.");
205 try (GigiPreparedStatement gigiPreparedStatement = new GigiPreparedStatement("SELECT version FROM \"schemeVersion\" ORDER BY version DESC LIMIT 1;")) {
206 GigiResultSet rs = gigiPreparedStatement.executeQuery();
208 version = rs.getInt(1);
211 if (version == CURRENT_SCHEMA_VERSION) {
212 return; // Good to go
214 if (version > CURRENT_SCHEMA_VERSION) {
215 throw new Error("Invalid database version. Please fix this.");
220 public void beginTransaction() throws SQLException {
221 c.setAutoCommit(false);
224 private static void upgrade(int version) {
226 Statement s = getInstance().c.createStatement();
228 while (version < CURRENT_SCHEMA_VERSION) {
229 try (InputStream resourceAsStream = DatabaseConnection.class.getResourceAsStream("upgrade/from_" + version + ".sql")) {
230 if (resourceAsStream == null) {
231 throw new Error("Upgrade script from version " + version + " was not found.");
233 SQLFileManager.addFile(s, resourceAsStream, ImportType.PRODUCTION);
237 s.addBatch("UPDATE \"schemeVersion\" SET version='" + version + "'");
238 System.out.println("UPGRADING Database to version " + version);
240 System.out.println("done.");
244 } catch (SQLException e) {
246 } catch (IOException e) {
251 public void commitTransaction() throws SQLException {
253 c.setAutoCommit(true);
256 public void quitTransaction() {
258 if ( !c.getAutoCommit()) {
260 c.setAutoCommit(true);
262 } catch (SQLException e) {
267 public static final String preprocessQuery(String originalQuery) {
268 originalQuery = originalQuery.replace('`', '"');
269 if (originalQuery.matches("^INSERT INTO [^ ]+ SET .*")) {
270 Pattern p = Pattern.compile("INSERT INTO ([^ ]+) SET (.*)");
271 Matcher m = p.matcher(originalQuery);
273 String replacement = "INSERT INTO " + toIdentifier(m.group(1));
274 String[] parts = m.group(2).split(",");
275 StringJoiner columns = new StringJoiner(", ");
276 StringJoiner values = new StringJoiner(", ");
277 for (int i = 0; i < parts.length; i++) {
278 String[] split = parts[i].split("=", 2);
279 columns.add(toIdentifier(split[0]));
280 values.add(split[1]);
282 replacement += "(" + columns.toString() + ") VALUES(" + values.toString() + ")";
288 return originalQuery;
291 private static CharSequence toIdentifier(String ident) {
292 ident = ident.trim();
293 if ( !ident.startsWith("\"")) {
294 ident = "\"" + ident;
296 if ( !ident.endsWith("\"")) {
297 ident = ident + "\"";
302 protected synchronized void returnStatement(PreparedStatement target) throws SQLException {
303 if ( !underUse.remove(target)) {
308 public synchronized int getNumberOfLockedStatements() {
309 return underUse.size();
312 public synchronized void lockedStatements(PrintWriter writer) {
313 writer.println(underUse.size());
314 for (PreparedStatement ps : underUse) {
315 for (Entry<StatementDescriptor, PreparedStatement> e : statements.entrySet()) {
316 if (e.getValue() == ps) {
317 writer.println("<br/>");
318 writer.println(e.getKey().instance + ":");
320 writer.println(e.getKey().query);