java/sql-dk/src/info/globalcode/sql/dk/formatting/TabularPrefetchingFormatter.java
SingleRecordFormatter: escape whitespace characters in the same way as in TabularFormatter (fixed)
/**
* SQL-DK
* Copyright © 2013 František Kučera (frantovo.cz)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package info.globalcode.sql.dk.formatting;
import java.util.ArrayList;
import java.util.List;
/**
* <p>
* Prefetches whole result set and computes column widths. Whole table is flushed at once in
* {@linkplain #writeEndResultSet()}.
* </p>
*
* <p>
* Long values will not overflow the cells, but whole result set must be loaded into the memory.
* </p>
*
* @author Ing. František Kučera (frantovo.cz)
*/
public class TabularPrefetchingFormatter extends TabularFormatter {
public static final String NAME = "tabular-prefetching"; // bash-completion:formatter
private ColumnsHeader currentHeader;
private List<Object[]> currentResultSet;
private Object[] currentRow;
private int currentColumnsCount;
private boolean prefetchDone = false;
public TabularPrefetchingFormatter(FormatterContext formatterContext) {
super(formatterContext);
}
@Override
protected int getCurrentColumnsCount() {
if (prefetchDone) {
return super.getCurrentColumnsCount();
} else {
return currentColumnsCount;
}
}
@Override
public void writeStartResultSet(ColumnsHeader header) {
currentResultSet = new ArrayList<>();
currentHeader = header;
initColumnWidths(header.getColumnCount());
}
@Override
public void writeStartRow() {
currentRow = new Object[currentHeader.getColumnCount()];
currentResultSet.add(currentRow);
currentColumnsCount = 0;
}
@Override
public void writeColumnValue(Object value) {
currentRow[currentColumnsCount] = value;
currentColumnsCount++;
String textRepresentation = toString(value);
/** TODO: count only printable characters (currently not an issue) */
updateColumnWidth(currentColumnsCount, textRepresentation.length());
}
@Override
public void writeEndRow() {
// do nothing
}
@Override
public void writeEndResultSet() {
prefetchDone = true;
super.writeStartResultSet(currentHeader);
for (Object[] row : currentResultSet) {
super.writeStartRow();
for (Object cell : row) {
super.writeColumnValue(cell);
}
super.writeEndRow();
}
currentColumnsCount = 0;
currentHeader = null;
currentRow = null;
currentResultSet = null;
super.writeEndResultSet();
prefetchDone = false;
}
}