diff options
author | Simon Rettberg | 2015-09-07 18:20:58 +0200 |
---|---|---|
committer | Simon Rettberg | 2015-09-07 18:20:58 +0200 |
commit | 2f140304dd193763b2aa9d509f972c6f23202e93 (patch) | |
tree | 8639a625543d78b35caccfe3dcdfa4740ba6d917 /src/main/java/org/openslx/imagemaster/db/MysqlConnection.java | |
parent | Stuff (diff) | |
download | masterserver-2f140304dd193763b2aa9d509f972c6f23202e93.tar.gz masterserver-2f140304dd193763b2aa9d509f972c6f23202e93.tar.xz masterserver-2f140304dd193763b2aa9d509f972c6f23202e93.zip |
Start adapting to new DB/Thrift model
Diffstat (limited to 'src/main/java/org/openslx/imagemaster/db/MysqlConnection.java')
-rw-r--r-- | src/main/java/org/openslx/imagemaster/db/MysqlConnection.java | 78 |
1 files changed, 78 insertions, 0 deletions
diff --git a/src/main/java/org/openslx/imagemaster/db/MysqlConnection.java b/src/main/java/org/openslx/imagemaster/db/MysqlConnection.java new file mode 100644 index 0000000..dcfa713 --- /dev/null +++ b/src/main/java/org/openslx/imagemaster/db/MysqlConnection.java @@ -0,0 +1,78 @@ +package org.openslx.imagemaster.db; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; + +public class MysqlConnection implements AutoCloseable { + + private static final Logger LOGGER = Logger.getLogger(MysqlConnection.class); + + private static final int CONNECTION_TIMEOUT_MS = 5 * 60 * 1000; + + private final long deadline = System.currentTimeMillis() + CONNECTION_TIMEOUT_MS; + + private final Connection rawConnection; + + private boolean hasPendingQueries = false; + + private List<MysqlStatement> openStatements = new ArrayList<>(); + + MysqlConnection(Connection rawConnection) { + this.rawConnection = rawConnection; + } + + public MysqlStatement prepareStatement(String sql) throws SQLException { + if (!sql.startsWith("SELECT")) + hasPendingQueries = true; + MysqlStatement statement = new MysqlStatement(rawConnection, sql); + openStatements.add(statement); + return statement; + } + + public void commit() throws SQLException { + rawConnection.commit(); + hasPendingQueries = false; + } + + public void rollback() throws SQLException { + rawConnection.rollback(); + hasPendingQueries = false; + } + + boolean isValid() { + return System.currentTimeMillis() < deadline; + } + + @Override + public void close() { + if (hasPendingQueries) { + LOGGER.warn("Mysql connection had uncommited queries on .close()"); + hasPendingQueries = false; + } + try { + rawConnection.rollback(); + } catch (SQLException e) { + LOGGER.warn("Rolling back uncommited queries failed!", e); + } + if (!openStatements.isEmpty()) { + for (MysqlStatement statement : openStatements) { + statement.close(); + } + openStatements.clear(); + } + Database.returnConnection(this); + } + + void release() { + try { + rawConnection.close(); + } catch (SQLException e) { + // Nothing meaningful to do + } + } + +} |