java/sql-dk/src/info/globalcode/sql/dk/formatting/TabularPrefetchingFormatter.java
3 * Copyright © 2013 František Kučera (frantovo.cz)
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package info.globalcode.sql.dk.formatting;
20 import java.util.ArrayList;
21 import java.util.List;
25 * Prefetches whole result set and computes column widths. Whole table is flushed at once in
26 * {@linkplain #writeEndResultSet()}.
30 * Long values will not overflow the cells, but whole result set must be loaded into the memory.
33 * @author Ing. František Kučera (frantovo.cz)
35 public class TabularPrefetchingFormatter extends TabularFormatter {
37 public static final String NAME = "tabular-prefetching"; // bash-completion:formatter
38 private ColumnsHeader currentHeader;
39 private List<Object[]> currentResultSet;
40 private Object[] currentRow;
41 private int currentColumnsCount;
42 private boolean prefetchDone = false;
44 public TabularPrefetchingFormatter(FormatterContext formatterContext) {
45 super(formatterContext);
49 protected int getCurrentColumnsCount() {
51 return super.getCurrentColumnsCount();
53 return currentColumnsCount;
58 public void writeStartResultSet(ColumnsHeader header) {
59 currentResultSet = new ArrayList<>();
60 currentHeader = header;
61 initColumnWidths(header.getColumnCount());
65 public void writeStartRow() {
66 currentRow = new Object[currentHeader.getColumnCount()];
67 currentResultSet.add(currentRow);
68 currentColumnsCount = 0;
72 public void writeColumnValue(Object value) {
73 currentRow[currentColumnsCount] = value;
74 currentColumnsCount++;
75 String textRepresentation = toString(value);
76 /** TODO: count only printable characters (currently not an issue) */
77 updateColumnWidth(currentColumnsCount, textRepresentation.length());
81 public void writeEndRow() {
86 public void writeEndResultSet() {
89 super.writeStartResultSet(currentHeader);
91 for (Object[] row : currentResultSet) {
92 super.writeStartRow();
93 for (Object cell : row) {
94 super.writeColumnValue(cell);
99 currentColumnsCount = 0;
100 currentHeader = null;
102 currentResultSet = null;
103 super.writeEndResultSet();
104 prefetchDone = false;