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 info.globalcode.sql.dk.ColorfulPrintWriter;
21 import static info.globalcode.sql.dk.ColorfulPrintWriter.*;
22 import static info.globalcode.sql.dk.Functions.lpad;
23 import static info.globalcode.sql.dk.Functions.rpad;
24 import static info.globalcode.sql.dk.Functions.repeat;
25 import java.util.List;
28 * <p>Prints human-readable output – tables of result sets and text messages with update counts.</p>
30 * <p>Longer values might break the table – overflow the cells – see alternative tabular formatters
31 * and the {@linkplain #PROPERTY_TRIM} property.</p>
33 * @author Ing. František Kučera (frantovo.cz)
34 * @see TabularPrefetchingFormatter
35 * @see TabularWrappingFormatter
37 public class TabularFormatter extends AbstractFormatter {
39 public static final String NAME = "tabular"; // bash-completion:formatter
40 private static final String HEADER_TYPE_PREFIX = " (";
41 private static final String HEADER_TYPE_SUFFIX = ")";
42 public static final String PROPERTY_ASCII = "ascii";
43 public static final String PROPERTY_COLORFUL = "color";
44 public static final String PROPERTY_TRIM = "trim";
45 protected ColorfulPrintWriter out;
46 private boolean firstResult = true;
47 private int[] columnWidth;
49 * use ASCII borders instead of unicode ones
51 private final boolean asciiNostalgia;
53 * Trim values if they are longer than cell size
55 private final boolean trimValues;
57 public TabularFormatter(FormatterContext formatterContext) {
58 super(formatterContext);
59 out = new ColorfulPrintWriter(formatterContext.getOutputStream());
60 asciiNostalgia = formatterContext.getProperties().getBoolean(PROPERTY_ASCII, false);
61 trimValues = formatterContext.getProperties().getBoolean(PROPERTY_TRIM, false);
62 out.setColorful(formatterContext.getProperties().getBoolean(PROPERTY_COLORFUL, true));
66 public void writeStartResultSet(ColumnsHeader header) {
67 super.writeStartResultSet(header);
68 printResultSeparator();
70 initColumnWidths(header.getColumnCount());
73 printTableBorder("╭");
75 List<ColumnDescriptor> columnDescriptors = header.getColumnDescriptors();
77 for (ColumnDescriptor cd : columnDescriptors) {
78 // padding: make header cell at least same width as data cells in this column
79 int typeWidth = cd.getTypeName().length() + HEADER_TYPE_PREFIX.length() + HEADER_TYPE_SUFFIX.length();
80 cd.setLabel(rpad(cd.getLabel(), getColumnWidth(cd.getColumnNumber()) - typeWidth));
81 updateColumnWidth(cd.getColumnNumber(), cd.getLabel().length() + typeWidth);
83 if (!cd.isFirstColumn()) {
84 printTableBorder("┬");
86 printTableBorder(repeat('─', getColumnWidth(cd.getColumnNumber()) + 2));
88 printTableBorder("╮");
91 for (ColumnDescriptor cd : columnDescriptors) {
92 if (cd.isFirstColumn()) {
94 printTableBorder("│ ");
96 printTableBorder(" │ ");
98 out.print(TerminalStyle.Bright, cd.getLabel());
99 out.print(HEADER_TYPE_PREFIX);
100 out.print(cd.getTypeName());
101 out.print(HEADER_TYPE_SUFFIX);
102 if (cd.isLastColumn()) {
103 printTableBorder(" │");
109 printTableBorder("├");
110 for (int i = 1; i <= header.getColumnCount(); i++) {
112 printTableBorder("┼");
114 printTableBorder(repeat('─', getColumnWidth(i) + 2));
116 printTableBorder("┤");
123 * Must be called before
124 * {@linkplain #updateColumnWidth(int, int)}
125 * and {@linkplain #getColumnWidth(int)}
126 * for each result set.
128 * @param columnCount number of columns in current result set
130 protected void initColumnWidths(int columnCount) {
131 if (columnWidth == null) {
132 columnWidth = new int[columnCount];
136 protected void cleanColumnWidths() {
141 public void writeColumnValue(Object value) {
142 super.writeColumnValue(value);
143 writeColumnValueInternal(value);
146 protected void writeColumnValueInternal(Object value) {
148 if (isCurrentColumnFirst()) {
150 printTableBorder("│ ");
152 printTableBorder(" │ ");
155 String valueString = toString(value);
156 printValueWithNewLinesReplaced(valueString);
158 if (isCurrentColumnLast()) {
159 printTableBorder(" │");
164 protected int getColumnWidth(int columnNumber) {
165 return columnWidth[columnNumber - 1];
168 private void setColumnWidth(int columnNumber, int width) {
169 columnWidth[columnNumber - 1] = width;
172 protected void updateColumnWidth(int columnNumber, int width) {
173 int oldWidth = getColumnWidth(columnNumber);
174 setColumnWidth(columnNumber, Math.max(width, oldWidth));
178 protected String toString(Object value) {
179 final int width = getColumnWidth(getCurrentColumnsCount());
181 if (value instanceof Number || value instanceof Boolean) {
182 result = lpad(String.valueOf(value), width);
184 result = rpad(String.valueOf(value), width);
186 // ? value = (boolean) value ? "✔" : "✗";
188 if (trimValues && result.length() > width) {
189 result = result.substring(0, width - 1) + "…";
196 public void writeEndRow() {
198 writeEndRowInternal();
201 public void writeEndRowInternal() {
207 public void writeEndResultSet() {
208 int columnCount = getCurrentColumnsHeader().getColumnCount();
209 super.writeEndResultSet();
212 printTableBorder("╰");
213 for (int i = 1; i <= columnCount; i++) {
215 printTableBorder("┴");
217 printTableBorder(repeat('─', getColumnWidth(i) + 2));
219 printTableBorder("╯");
224 out.print(TerminalColor.Yellow, "Record count: ");
225 out.println(getCurrentRowCount());
231 public void writeUpdatesResult(int updatedRowsCount) {
232 super.writeUpdatesResult(updatedRowsCount);
233 printResultSeparator();
234 out.print(TerminalColor.Red, "Updated records: ");
235 out.println(updatedRowsCount);
241 public void writeEndDatabase() {
242 super.writeEndDatabase();
246 private void printResultSeparator() {
254 protected void printTableBorder(String border) {
255 if (asciiNostalgia) {
256 border = border.replaceAll("─", "-");
257 border = border.replaceAll("│", "|");
258 border = border.replaceAll("[╭┬╮├┼┤╰┴╯]", "+");
261 out.print(TerminalColor.Green, border);
264 protected void printTableIndent() {
268 protected void printValueWithNewLinesReplaced(String valueString) {
269 String[] valueParts = valueString.split("\n");
270 for (int i = 0; i < valueParts.length; i++) {
271 String valuePart = valueParts[i];
272 // TODO: replace also TABs
273 out.print(TerminalColor.Cyan, valuePart);
274 if (i < valueParts.length - 1) {
275 out.print(TerminalColor.Red, "↲");