Repository navigation
Handle SQL connection initialization failures safely #111
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
169 changes: 169 additions & 0 deletions
169
...PI/src/test/java/com/bencodez/simpleapi/sql/mysql/AbstractSqlTableInitializationTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,169 @@ | ||
| package com.bencodez.simpleapi.sql.mysql; | ||
|
|
||
| import static org.junit.jupiter.api.Assertions.*; | ||
| import static org.mockito.Mockito.*; | ||
|
|
||
| import java.sql.Connection; | ||
| import java.sql.Driver; | ||
| import java.sql.DriverPropertyInfo; | ||
| import java.sql.SQLException; | ||
| import java.util.Properties; | ||
| import java.util.logging.Logger; | ||
|
|
||
| import org.junit.jupiter.api.Test; | ||
|
|
||
| import com.bencodez.simpleapi.sql.mysql.config.MysqlConfig; | ||
|
|
||
| class AbstractSqlTableInitializationTest { | ||
| @Test | ||
| void deferredExistingPoolConstructorDoesNotNeedSubclassState() { | ||
| MySQL mysql = mock(MySQL.class); | ||
| ConnectionManager manager = mock(ConnectionManager.class); | ||
| when(mysql.getConnectionManager()).thenReturn(manager); | ||
| when(manager.getDbType()).thenReturn(DbType.MYSQL); | ||
| DeferredTable table = new DeferredTable("votes", mysql); | ||
| assertFalse(table.initialized); | ||
| table.initialized = true; | ||
| assertEquals("votes", table.getTableName()); | ||
| } | ||
| @Test | ||
| void authenticationFailureStopsConstructorBeforeSubclassHooksOrQueries() { | ||
| RejectingTable.hookCalls = 0; | ||
| RejectingDriver.connectionAttempts = 0; | ||
| MysqlConfig config = config(); | ||
| config.setDriver(RejectingDriver.class.getName()); | ||
|
|
||
| IllegalStateException failure = assertThrows(IllegalStateException.class, | ||
| () -> new RejectingTable("votes", config, true)); | ||
| assertTrue(hasCause(failure, AUTH_FAILURE)); | ||
| assertEquals(0, RejectingTable.hookCalls); | ||
| assertTrue(RejectingDriver.connectionAttempts > 0); | ||
| } | ||
|
|
||
| @Test void databaseSelectionFailureClosesPoolWithoutCallingSubclassHooks() throws Exception { | ||
| SQLException denied = new SQLException("controlled database selection rejected", "42000"); | ||
| RejectingTable.hookCalls = 0; | ||
| try (var managers = mockConstruction(ConnectionManager.class, (manager, context) -> { | ||
| when(manager.open()).thenReturn(true); | ||
| Connection connection = mock(Connection.class); | ||
| when(manager.getConnectionChecked()).thenReturn(connection); | ||
| when(connection.prepareStatement(anyString())).thenThrow(denied); | ||
| })) { | ||
| IllegalStateException failure = assertThrows(IllegalStateException.class, | ||
| () -> new RejectingTable("votes", config(), true)); | ||
| assertSame(denied, failure.getCause()); | ||
| assertEquals(0, RejectingTable.hookCalls); | ||
| verify(managers.constructed().get(0)).close(); | ||
| } | ||
| } | ||
|
|
||
| @Test void uncheckedDatabaseSelectionFailuresKeepIdentityAndCleanupFailures() throws Exception { | ||
| for (Throwable failure : new Throwable[] {new IllegalArgumentException("driver rejected selection"), | ||
| new LinkageError("driver linkage failure")}) { | ||
| RuntimeException cleanupFailure = new IllegalStateException("controlled cleanup failure"); | ||
| RejectingTable.hookCalls = 0; | ||
| try (var managers = mockConstruction(ConnectionManager.class, (manager, context) -> { | ||
| when(manager.open()).thenReturn(true); | ||
| Connection connection = mock(Connection.class); | ||
| when(manager.getConnectionChecked()).thenReturn(connection); | ||
| when(connection.prepareStatement(anyString())).thenThrow(failure); | ||
| doThrow(cleanupFailure).when(manager).close(); | ||
| })) { | ||
| Throwable thrown = assertThrows(failure.getClass(), | ||
| () -> new RejectingTable("votes", config(), true)); | ||
| assertSame(failure, thrown); | ||
| assertArrayEquals(new Throwable[] {cleanupFailure}, thrown.getSuppressed()); | ||
| assertEquals(0, RejectingTable.hookCalls); | ||
| verify(managers.constructed().get(0)).close(); | ||
| verify(managers.constructed().get(0).getConnectionChecked()).close(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| @Test void databaseSelectionEscapesQuotedDatabaseNames() throws Exception { | ||
| MysqlConfig config = config(); | ||
| config.setDatabase("vote`data"); | ||
| try (var managers = mockConstruction(ConnectionManager.class, (manager, context) -> { | ||
| when(manager.open()).thenReturn(true); | ||
| Connection connection = mock(Connection.class); | ||
| when(manager.getConnectionChecked()).thenReturn(connection); | ||
| when(connection.prepareStatement("USE `vote``data`;")) | ||
| .thenReturn(mock(java.sql.PreparedStatement.class)); | ||
| })) { | ||
| AbstractSqlTable table = new AbstractSqlTable("votes", config, true, true) { | ||
| public String getPrimaryKeyColumn() { return "id"; } | ||
| public String buildCreateTableSql(DbType type) { return "CREATE TABLE votes (id TEXT)"; } | ||
| public void logSevere(String message) { fail("early hook"); } | ||
| public void logInfo(String message) { fail("early hook"); } | ||
| public void debug(Throwable failure) { fail("early hook"); } | ||
| public void debug(String message) { fail("early hook"); } | ||
| }; | ||
| verify(managers.constructed().get(0).getConnectionChecked()) | ||
| .prepareStatement("USE `vote``data`;"); | ||
| table.close(); | ||
| } | ||
| } | ||
|
|
||
| private static MysqlConfig config() { | ||
| MysqlConfig config = new MysqlConfig(); | ||
| config.setHostName("127.0.0.1"); | ||
| config.setPort(3306); | ||
| config.setUser("user"); | ||
| config.setPass("password"); | ||
| config.setDatabase("database"); | ||
| config.setMinimumIdle(0); | ||
| config.setMaxThreads(1); | ||
| config.setConnectionTimeout(1000); | ||
| return config; | ||
| } | ||
|
|
||
| private static boolean hasCause(Throwable failure, String message) { | ||
| for (Throwable current = failure; current != null; current = current.getCause()) { | ||
| if (message.equals(current.getMessage())) return true; | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| private static final String AUTH_FAILURE = "controlled authentication rejected"; | ||
|
|
||
| private static final class DeferredTable extends AbstractSqlTable { | ||
| boolean initialized; | ||
| DeferredTable(String name, MySQL mysql) { super(name, mysql, true); } | ||
| public String getPrimaryKeyColumn() { return "id"; } | ||
| public String buildCreateTableSql(DbType type) { return "CREATE TABLE votes (id TEXT)"; } | ||
| public void logSevere(String message) { if (!initialized) fail("early hook"); } | ||
| public void logInfo(String message) { if (!initialized) fail("early hook"); } | ||
| public void debug(Throwable failure) { if (!initialized) fail("early hook"); } | ||
| public void debug(String message) { if (!initialized) fail("early hook"); } | ||
| } | ||
|
|
||
| private static final class RejectingTable extends AbstractSqlTable { | ||
| static int hookCalls; | ||
|
|
||
| RejectingTable(String name, MysqlConfig config, boolean debug) { | ||
| super(name, config, debug); | ||
| } | ||
|
|
||
| public String getPrimaryKeyColumn() { return "id"; } | ||
| public String buildCreateTableSql(DbType type) { hookCalls++; return "CREATE TABLE votes (id TEXT)"; } | ||
| public void logSevere(String message) { hookCalls++; } | ||
| public void logInfo(String message) { hookCalls++; } | ||
| public void debug(Throwable failure) { hookCalls++; } | ||
| public void debug(String message) { hookCalls++; } | ||
| } | ||
|
|
||
| public static final class RejectingDriver implements Driver { | ||
| static int connectionAttempts; | ||
|
|
||
| public Connection connect(String url, Properties properties) throws SQLException { | ||
| connectionAttempts++; | ||
| throw new SQLException(AUTH_FAILURE); | ||
| } | ||
| public boolean acceptsURL(String url) { return url != null && url.startsWith("jdbc:"); } | ||
| public DriverPropertyInfo[] getPropertyInfo(String url, Properties properties) { return new DriverPropertyInfo[0]; } | ||
| public int getMajorVersion() { return 1; } | ||
| public int getMinorVersion() { return 0; } | ||
| public boolean jdbcCompliant() { return false; } | ||
| public Logger getParentLogger() { return Logger.getGlobal(); } | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If a JDBC driver throws a
RuntimeExceptionor the JVM raises anErrorwhile preparing or executingUSE, this catch converts it toIllegalStateException; previously those unchecked failures propagated unchanged, and wrapping anErrorcan also defeat fatal-error handling. Perform cleanup but rethrow the original unchecked failure, reserving the initialization wrapper for the checkedSQLExceptionpath.AGENTS.md reference: AGENTS.md:L44-L46
Useful? React with 👍 / 👎.