Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/main/java/org/apache/commons/csv/CSVPrinter.java
Original file line number Diff line number Diff line change
Expand Up @@ -502,7 +502,11 @@ public void printRecords(final Object... values) throws IOException {
*/
public void printRecords(final ResultSet resultSet) throws SQLException, IOException {
final int columnCount = resultSet.getMetaData().getColumnCount();
while (resultSet.next() && format.useRow(resultSet.getRow())) {
// Count the rows produced here instead of ResultSet.getRow(): getRow() is the absolute cursor
// position, which is optional for TYPE_FORWARD_ONLY result sets and returns 0 there, silently
// disabling maxRows. Mirrors the row-produced counter the parser uses (CSV-327).
long rowCount = 0;
while (format.useRow(rowCount + 1) && resultSet.next()) {
lock.lock();
try {
for (int i = 1; i <= columnCount; i++) {
Expand All @@ -523,6 +527,7 @@ public void printRecords(final ResultSet resultSet) throws SQLException, IOExcep
} finally {
lock.unlock();
}
rowCount++;
}
}

Expand Down
25 changes: 25 additions & 0 deletions src/test/java/org/apache/commons/csv/CSVPrinterTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
Expand Down Expand Up @@ -964,6 +965,30 @@ void testJdbcPrinterWithResultSetMetaData(final long maxRows) throws IOException
}
}

@Test
void testJdbcPrinterWithResultSetWithoutRowNumber() throws IOException, SQLException {
// JDBC makes ResultSet.getRow() optional for TYPE_FORWARD_ONLY result sets, where a driver may return 0.
// maxRows must still cap the output by rows produced rather than by getRow().
final StringWriter sw = new StringWriter();
final CSVFormat format = CSVFormat.DEFAULT.builder().setMaxRows(2).get();
try (SimpleResultSet resultSet = new SimpleResultSet() {
@Override
public int getRow() {
return 0;
}
}) {
resultSet.addColumn("ID", Types.INTEGER, 10, 0);
for (int i = 1; i <= 4; i++) {
resultSet.addRow(i);
}
try (CSVPrinter printer = new CSVPrinter(sw, format)) {
printer.printRecords(resultSet);
assertEquals(2, printer.getRecordCount());
}
}
assertEquals("1" + RECORD_SEPARATOR + "2" + RECORD_SEPARATOR, sw.toString());
}

@Test
void testJira135_part1() throws IOException {
final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH);
Expand Down
Loading