Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
[CONJ-958] When multiple host without failover prefix, ensure connect…
…ing to all host until successfully establish a connection
  • Loading branch information
rusher committed Apr 11, 2022
1 parent 0231bb7 commit bb30bc3
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 6 deletions.
35 changes: 29 additions & 6 deletions src/main/java/org/mariadb/jdbc/Driver.java
Expand Up @@ -7,6 +7,7 @@
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.SocketAddress;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
Expand Down Expand Up @@ -56,17 +57,39 @@ public static Connection connect(Configuration configuration) throws SQLExceptio
break;

default:
HostAddress hostAddress =
configuration.addresses().isEmpty() ? null : configuration.addresses().get(0);
client =
configuration.transactionReplay()
? new ReplayClient(configuration, hostAddress, lock, false)
: new StandardClient(configuration, hostAddress, lock, false);
ClientInstance<Configuration , HostAddress , ReentrantLock , Boolean ,Client>
clientInstance =
(configuration.transactionReplay()) ? ReplayClient::new : StandardClient::new;

if (configuration.addresses().isEmpty()) {
// unix socket / windows pipe
client = clientInstance.apply(configuration, null, lock, false);
} else {
// loop until finding
SQLException lastException = null;
for (HostAddress host : configuration.addresses()) {
try {
client = clientInstance.apply(configuration, host, lock, false);
return new Connection(configuration, lock, client);
} catch (SQLException e) {
lastException = e;
}
}
throw lastException;
}
break;
}
return new Connection(configuration, lock, client);


}

@FunctionalInterface
public interface ClientInstance<T, U, V, W, R> {
R apply(T t, U u, V v, W w) throws SQLException;
}


/**
* Connect to the given connection string.
*
Expand Down
16 changes: 16 additions & 0 deletions src/test/java/org/mariadb/jdbc/integration/ConnectionTest.java
Expand Up @@ -1115,4 +1115,20 @@ public void createDatabaseIfNotExist() throws SQLException {

sharedConn.createStatement().execute("DROP DATABASE IF EXISTS `bla``f``l`");
}


@Test
public void loopHost() throws SQLException {
Assumptions.assumeTrue(
!"skysql".equals(System.getenv("srv")) && !"skysql-ha".equals(System.getenv("srv")));

// ensure connecting without DB
String connStr =
String.format(
"jdbc:mariadb://wronghost,%s:%s/%s?user=%s&password=%s&%s",
hostname, port, database, user, password, defaultOther);
try (Connection con = DriverManager.getConnection(connStr)) {
con.createStatement().executeQuery("SELECT 1");
}
}
}

0 comments on commit bb30bc3

Please sign in to comment.