Skip to content

Commit

Permalink
Fix Issue #2928 number of ports not equal to number of servers in dat…
Browse files Browse the repository at this point in the history
…asource (#2929)

* In BaseDataSource, check to make sure the number of servers is equal to the number of ports.
Throw an IllegalArgumentException if they are not.
Added test case to ensure

* changed test to remove nesting
Add the ports and server names to the error message
  • Loading branch information
davecramer committed Jul 20, 2023
1 parent 258cff3 commit aff581f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
12 changes: 10 additions & 2 deletions pgjdbc/src/main/java/org/postgresql/ds/common/BaseDataSource.java
Original file line number Diff line number Diff line change
Expand Up @@ -1337,8 +1337,16 @@ public String getUrl() {
url.append(",");
}
url.append(serverNames[i]);
if (portNumbers != null && portNumbers.length >= i && portNumbers[i] != 0) {
url.append(":").append(portNumbers[i]);
if (portNumbers != null) {
if (serverNames.length != portNumbers.length) {
throw new IllegalArgumentException(
String.format("Invalid argument: number of port %s entries must equal number of serverNames %s",
Arrays.toString(portNumbers), Arrays.toString(serverNames)));
}
if (portNumbers.length >= i && portNumbers[i] != 0) {
url.append(":").append(portNumbers[i]);
}

}
}
url.append("/");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
package org.postgresql.test.jdbc2.optional;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;

import org.postgresql.ds.common.BaseDataSource;

Expand Down Expand Up @@ -67,6 +68,16 @@ public void testEmptyPorts() {
assertEquals(0, bds.getPortNumbers()[0]);
}

@Test
public void testWrongNumberOfPorts() {
BaseDataSource bds = newDS();
bds.setDatabaseName("database");
bds.setServerNames(new String[] {"localhost", "localhost1"});
bds.setPortNumbers(new int[] {6432});
assertThrows("Number of ports not equal to the number of servers should throw an exception",
IllegalArgumentException.class, () -> bds.getUrl());
}

private BaseDataSource newDS() {
return new BaseDataSource() {
@Override
Expand Down

0 comments on commit aff581f

Please sign in to comment.