Skip to content

Commit

Permalink
[misc] implement internal Closable
Browse files Browse the repository at this point in the history
  • Loading branch information
rusher committed Mar 20, 2017
1 parent 83a27db commit 21f76f8
Show file tree
Hide file tree
Showing 50 changed files with 730 additions and 1,508 deletions.
45 changes: 17 additions & 28 deletions src/main/java/org/mariadb/jdbc/CallableParameterMetaData.java
Original file line number Diff line number Diff line change
Expand Up @@ -147,40 +147,29 @@ int mapMariaDbTypeToJdbc(String str) {


private String[] queryMetaInfos(boolean isFunction) throws SQLException {
PreparedStatement preparedStatement;
if (database != null) {
preparedStatement = con.prepareStatement("select param_list, returns, db, type from mysql.proc where db=? and name=?");
} else {
preparedStatement = con.prepareStatement("select param_list, returns, db, type from mysql.proc where db=DATABASE() and name=?");
}

ResultSet rs = null;
String paramList;
String functionReturn;
try {
if (database == null) {
preparedStatement.setString(1, name);
} else {
preparedStatement.setString(1, database);
preparedStatement.setString(2, name);
}
rs = preparedStatement.executeQuery();
if (!rs.next()) {
throw new SQLException((isFunction ? "function" : "procedure") + " `" + name + "` does not exist");
try (PreparedStatement preparedStatement = con.prepareStatement(
"select param_list, returns, db, type from mysql.proc where name=? and db="
+ (database != null ? "?" : "DATABASE()"))) {

preparedStatement.setString(1, name);
if (database != null) preparedStatement.setString(2, database);

try (ResultSet rs = preparedStatement.executeQuery()) {
if (!rs.next()) {
throw new SQLException((isFunction ? "function" : "procedure") + " `" + name + "` does not exist");
}
paramList = rs.getString(1);
functionReturn = rs.getString(2);
database = rs.getString(3);
this.isFunction = "FUNCTION".equals(rs.getString(4));
return new String[]{paramList, functionReturn};
}
paramList = rs.getString(1);
functionReturn = rs.getString(2);
database = rs.getString(3);
this.isFunction = "FUNCTION".equals(rs.getString(4));
return new String[]{paramList, functionReturn};

} catch (SQLSyntaxErrorException sqlSyntaxErrorException) {
throw new SQLException("Access to metaData informations not granted for current user. Consider grant select access to mysql.proc "
+ " or avoid using parameter by name", sqlSyntaxErrorException);
} finally {
if (rs != null) {
rs.close();
}
preparedStatement.close();
}

}
Expand Down
159 changes: 68 additions & 91 deletions src/main/java/org/mariadb/jdbc/MariaDbConnection.java
Original file line number Diff line number Diff line change
Expand Up @@ -583,14 +583,10 @@ public boolean getAutoCommit() throws SQLException {
* @throws SQLException if something goes wrong talking to the server.
*/
public void setAutoCommit(boolean autoCommit) throws SQLException {
if (autoCommit == getAutoCommit()) {
return;
}
Statement stmt = createStatement();
try {
if (autoCommit == getAutoCommit()) return;

try (Statement stmt = createStatement()) {
stmt.executeUpdate("set autocommit=" + ((autoCommit) ? "1" : "0"));
} finally {
stmt.close();
}
}

Expand All @@ -600,18 +596,17 @@ public void setAutoCommit(boolean autoCommit) throws SQLException {
* @throws SQLException if there is an error commiting.
*/
public void commit() throws SQLException {
lock.lock();
try {
if (!getAutoCommit()) {
Statement st = createStatement();
try {
st.execute("COMMIT");
} finally {
st.close();
if (!getAutoCommit()) {
lock.lock();
try {
if (!getAutoCommit()) {
try (Statement st = createStatement()) {
st.execute("COMMIT");
}
}
} finally {
lock.unlock();
}
} finally {
lock.unlock();
}
}

Expand All @@ -621,11 +616,8 @@ public void commit() throws SQLException {
* @throws SQLException if there is an error rolling back.
*/
public void rollback() throws SQLException {
Statement st = createStatement();
try {
try (Statement st = createStatement()) {
st.execute("ROLLBACK");
} finally {
st.close();
}
}

Expand All @@ -643,9 +635,9 @@ public void rollback() throws SQLException {
* @since 1.4
*/
public void rollback(final Savepoint savepoint) throws SQLException {
Statement st = createStatement();
st.execute("ROLLBACK TO SAVEPOINT " + savepoint.toString());
st.close();
try (Statement st = createStatement()) {
st.execute("ROLLBACK TO SAVEPOINT " + savepoint.toString());
}
}

/**
Expand Down Expand Up @@ -722,19 +714,12 @@ public void setReadOnly(final boolean readOnly) throws SQLException {
* @see #setCatalog
*/
public String getCatalog() throws SQLException {
String catalog = null;
Statement st = null;
try {
st = createStatement();
ResultSet rs = st.executeQuery("select database()");
rs.next();
catalog = rs.getString(1);
} finally {
if (st != null) {
st.close();
try (Statement st = createStatement()) {
try (ResultSet rs = st.executeQuery("select database()")) {
rs.next();
return rs.getString(1);
}
}
return catalog;
}

/**
Expand Down Expand Up @@ -768,25 +753,23 @@ public void setCatalog(final String catalog) throws SQLException {
* @see #setTransactionIsolation
*/
public int getTransactionIsolation() throws SQLException {
final Statement stmt = createStatement();
try {
final ResultSet rs = stmt.executeQuery("SELECT @@tx_isolation");
rs.next();
final String response = rs.getString(1);
if (response.equals("REPEATABLE-READ")) {
return Connection.TRANSACTION_REPEATABLE_READ;
}
if (response.equals("READ-UNCOMMITTED")) {
return Connection.TRANSACTION_READ_UNCOMMITTED;
}
if (response.equals("READ-COMMITTED")) {
return Connection.TRANSACTION_READ_COMMITTED;
}
if (response.equals("SERIALIZABLE")) {
return Connection.TRANSACTION_SERIALIZABLE;
try (Statement stmt = createStatement()) {
try (ResultSet rs = stmt.executeQuery("SELECT @@tx_isolation")) {
rs.next();
final String response = rs.getString(1);
if (response.equals("REPEATABLE-READ")) {
return Connection.TRANSACTION_REPEATABLE_READ;
}
if (response.equals("READ-UNCOMMITTED")) {
return Connection.TRANSACTION_READ_UNCOMMITTED;
}
if (response.equals("READ-COMMITTED")) {
return Connection.TRANSACTION_READ_COMMITTED;
}
if (response.equals("SERIALIZABLE")) {
return Connection.TRANSACTION_SERIALIZABLE;
}
}
} finally {
stmt.close();
}
throw ExceptionMapper.getSqlException("Could not get transaction isolation level");
}
Expand Down Expand Up @@ -825,36 +808,27 @@ public void setTransactionIsolation(final int level) throws SQLException {
* @see SQLWarning
*/
public SQLWarning getWarnings() throws SQLException {
if (warningsCleared || isClosed() || !protocol.hasWarnings()) {
return null;
}
Statement st = null;
ResultSet rs = null;
if (warningsCleared || isClosed() || !protocol.hasWarnings()) return null;

SQLWarning last = null;
SQLWarning first = null;
try {
st = this.createStatement();
rs = st.executeQuery("show warnings");
// returned result set has 'level', 'code' and 'message' columns, in this order.
while (rs.next()) {
int code = rs.getInt(2);
String message = rs.getString(3);
SQLWarning warning = new SQLWarning(message, ExceptionMapper.mapCodeToSqlState(code), code);
if (first == null) {
first = warning;
last = warning;
} else {
last.setNextWarning(warning);
last = warning;

try (Statement st = this.createStatement()) {
try (ResultSet rs = st.executeQuery("show warnings")) {
// returned result set has 'level', 'code' and 'message' columns, in this order.
while (rs.next()) {
int code = rs.getInt(2);
String message = rs.getString(3);
SQLWarning warning = new SQLWarning(message, ExceptionMapper.mapCodeToSqlState(code), code);
if (first == null) {
first = warning;
last = warning;
} else {
last.setNextWarning(warning);
last = warning;
}
}
}
} finally {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
}
return first;
}
Expand Down Expand Up @@ -968,8 +942,9 @@ public Savepoint setSavepoint() throws SQLException {
*/
public Savepoint setSavepoint(final String name) throws SQLException {
Savepoint savepoint = new MariaDbSavepoint(name, savepointCount++);
Statement st = createStatement();
st.execute("SAVEPOINT " + savepoint.toString());
try (Statement st = createStatement()) {
st.execute("SAVEPOINT " + savepoint.toString());
}
return savepoint;

}
Expand All @@ -986,9 +961,9 @@ public Savepoint setSavepoint(final String name) throws SQLException {
* @since 1.4
*/
public void releaseSavepoint(final Savepoint savepoint) throws SQLException {
Statement st = createStatement();
st.execute("RELEASE SAVEPOINT " + savepoint.toString());
st.close();
try (Statement st = createStatement()) {
st.execute("RELEASE SAVEPOINT " + savepoint.toString());
}
}

/**
Expand Down Expand Up @@ -1405,10 +1380,12 @@ public void setHostFailed() {
*/
public int getLowercaseTableNames() throws SQLException {
if (lowercaseTableNames == -1) {
Statement st = createStatement();
ResultSet rs = st.executeQuery("select @@lower_case_table_names");
rs.next();
lowercaseTableNames = rs.getInt(1);
try (Statement st = createStatement()) {
try (ResultSet rs = st.executeQuery("select @@lower_case_table_names")) {
rs.next();
lowercaseTableNames = rs.getInt(1);
}
}
}
return lowercaseTableNames;
}
Expand All @@ -1420,9 +1397,8 @@ public int getLowercaseTableNames() throws SQLException {
* @throws SQLException if security manager doesn't permit it.
*/
public void abort(Executor executor) throws SQLException {
if (this.isClosed()) {
return;
}
if (this.isClosed()) return;

SQLPermission sqlPermission = new SQLPermission("callAbort");
SecurityManager securityManager = System.getSecurityManager();
if (securityManager != null && sqlPermission != null) {
Expand All @@ -1431,6 +1407,7 @@ public void abort(Executor executor) throws SQLException {
if (executor == null) {
throw ExceptionMapper.getSqlException("Cannot abort the connection: null executor passed");
}

executor.execute(new Runnable() {
@Override
public void run() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,16 +80,16 @@ public void authenticate(final PacketOutputStream writer, final String serverPri
final File jaasConfFile;
try {
jaasConfFile = File.createTempFile("jaas.conf", null);
final PrintStream bos = new PrintStream(new FileOutputStream(jaasConfFile));
bos.print(String.format(
"Krb5ConnectorContext {\n"
+ "com.sun.security.auth.module.Krb5LoginModule required "
+ "useTicketCache=true "
+ "debug=true "
+ "renewTGT=true "
+ "doNotPrompt=true; };"
));
bos.close();
try (PrintStream bos = new PrintStream(new FileOutputStream(jaasConfFile))) {
bos.print(String.format(
"Krb5ConnectorContext {\n"
+ "com.sun.security.auth.module.Krb5LoginModule required "
+ "useTicketCache=true "
+ "debug=true "
+ "renewTGT=true "
+ "doNotPrompt=true; };"
));
}
jaasConfFile.deleteOnExit();
} catch (final IOException ex) {
throw new IOError(ex);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -730,12 +730,12 @@ public void setCatalog(final String database) throws QueryException {
*/
@Override
public void cancelCurrentQuery() throws QueryException, IOException {
MasterProtocol copiedProtocol = new MasterProtocol(urlParser, new ReentrantLock());
copiedProtocol.setHostAddress(getHostAddress());
copiedProtocol.connect();
//no lock, because there is already a query running that possessed the lock.
copiedProtocol.executeQuery("KILL QUERY " + serverThreadId);
copiedProtocol.close();
try (MasterProtocol copiedProtocol = new MasterProtocol(urlParser, new ReentrantLock())) {
copiedProtocol.setHostAddress(getHostAddress());
copiedProtocol.connect();
//no lock, because there is already a query running that possessed the lock.
copiedProtocol.executeQuery("KILL QUERY " + serverThreadId);
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,13 @@ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWIS
import org.mariadb.jdbc.internal.failover.Listener;
import org.mariadb.jdbc.internal.failover.tools.SearchFilter;

import java.io.Closeable;
import java.util.ArrayDeque;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;


public class MasterProtocol extends AbstractQueryProtocol {
public class MasterProtocol extends AbstractQueryProtocol implements Closeable {

/**
* Get a protocol instance.
Expand Down
1 change: 0 additions & 1 deletion src/test/java/org/mariadb/jdbc/AllowMultiQueriesTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,6 @@ public void allowMultiQueriesFetchInsertSelectTest() throws SQLException {
try (Statement statement = connection.createStatement()) {
statement.setFetchSize(1);
statement.execute("INSERT INTO AllowMultiQueriesTest2(test) VALUES ('a'), ('b');SELECT * from AllowMultiQueriesTest;SELECT 3;");
statement.close();
}
}
}
Expand Down
Loading

0 comments on commit 21f76f8

Please sign in to comment.