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;
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
30 * <p>Prints human-readable output – tables of result sets and text messages with update counts.</p>
32 * <p>Longer values might break the table – overflow the cells – see alternative tabular formatters
33 * and the {@linkplain #PROPERTY_TRIM} property.</p>
35 * @author Ing. František Kučera (frantovo.cz)
36 * @see TabularPrefetchingFormatter
37 * @see TabularWrappingFormatter
39 public class TabularFormatter extends AbstractFormatter {
41 public static final String NAME = "tabular"; // bash-completion:formatter
42 private static final String HEADER_TYPE_PREFIX = " (";
43 private static final String HEADER_TYPE_SUFFIX = ")";
44 public static final String PROPERTY_ASCII = "ascii";
45 public static final String PROPERTY_COLORFUL = "color";
46 public static final String PROPERTY_TRIM = "trim";
47 private static final Pattern whitespaceToReplace = Pattern.compile("\\n|\\t");
48 protected ColorfulPrintWriter out;
49 private boolean firstResult = true;
50 private int[] columnWidth;
52 * use ASCII borders instead of unicode ones
54 private final boolean asciiNostalgia;
56 * Trim values if they are longer than cell size
58 private final boolean trimValues;
60 public TabularFormatter(FormatterContext formatterContext) {
61 super(formatterContext);
62 out = new ColorfulPrintWriter(formatterContext.getOutputStream());
63 asciiNostalgia = formatterContext.getProperties().getBoolean(PROPERTY_ASCII, false);
64 trimValues = formatterContext.getProperties().getBoolean(PROPERTY_TRIM, false);
65 out.setColorful(formatterContext.getProperties().getBoolean(PROPERTY_COLORFUL, true));
69 public void writeStartResultSet(ColumnsHeader header) {
70 super.writeStartResultSet(header);
71 printResultSeparator();
73 initColumnWidths(header.getColumnCount());
76 printTableBorder("╭");
78 List<ColumnDescriptor> columnDescriptors = header.getColumnDescriptors();
80 for (ColumnDescriptor cd : columnDescriptors) {
81 // padding: make header cell at least same width as data cells in this column
82 int typeWidth = cd.getTypeName().length() + HEADER_TYPE_PREFIX.length() + HEADER_TYPE_SUFFIX.length();
83 cd.setLabel(rpad(cd.getLabel(), getColumnWidth(cd.getColumnNumber()) - typeWidth));
84 updateColumnWidth(cd.getColumnNumber(), cd.getLabel().length() + typeWidth);
86 if (!cd.isFirstColumn()) {
87 printTableBorder("┬");
89 printTableBorder(repeat('─', getColumnWidth(cd.getColumnNumber()) + 2));
91 printTableBorder("╮");
94 for (ColumnDescriptor cd : columnDescriptors) {
95 if (cd.isFirstColumn()) {
97 printTableBorder("│ ");
99 printTableBorder(" │ ");
101 out.print(TerminalStyle.Bright, cd.getLabel());
102 out.print(HEADER_TYPE_PREFIX);
103 out.print(cd.getTypeName());
104 out.print(HEADER_TYPE_SUFFIX);
105 if (cd.isLastColumn()) {
106 printTableBorder(" │");
112 printTableBorder("├");
113 for (int i = 1; i <= header.getColumnCount(); i++) {
115 printTableBorder("┼");
117 printTableBorder(repeat('─', getColumnWidth(i) + 2));
119 printTableBorder("┤");
126 * Must be called before
127 * {@linkplain #updateColumnWidth(int, int)}
128 * and {@linkplain #getColumnWidth(int)}
129 * for each result set.
131 * @param columnCount number of columns in current result set
133 protected void initColumnWidths(int columnCount) {
134 if (columnWidth == null) {
135 columnWidth = new int[columnCount];
139 protected void cleanColumnWidths() {
144 public void writeColumnValue(Object value) {
145 super.writeColumnValue(value);
146 writeColumnValueInternal(value);
149 protected void writeColumnValueInternal(Object value) {
151 if (isCurrentColumnFirst()) {
153 printTableBorder("│ ");
155 printTableBorder(" │ ");
158 String valueString = toString(value);
159 printValueWithWhitespaceReplaced(valueString);
161 if (isCurrentColumnLast()) {
162 printTableBorder(" │");
167 protected int getColumnWidth(int columnNumber) {
168 return columnWidth[columnNumber - 1];
171 private void setColumnWidth(int columnNumber, int width) {
172 columnWidth[columnNumber - 1] = width;
175 protected void updateColumnWidth(int columnNumber, int width) {
176 int oldWidth = getColumnWidth(columnNumber);
177 setColumnWidth(columnNumber, Math.max(width, oldWidth));
181 protected String toString(Object value) {
182 final int width = getColumnWidth(getCurrentColumnsCount());
184 if (value instanceof Number || value instanceof Boolean) {
185 result = lpad(String.valueOf(value), width);
187 result = rpad(String.valueOf(value), width);
189 // ? value = (boolean) value ? "✔" : "✗";
191 if (trimValues && result.length() > width) {
192 result = result.substring(0, width - 1) + "…";
199 public void writeEndRow() {
201 writeEndRowInternal();
204 public void writeEndRowInternal() {
210 public void writeEndResultSet() {
211 int columnCount = getCurrentColumnsHeader().getColumnCount();
212 super.writeEndResultSet();
215 printTableBorder("╰");
216 for (int i = 1; i <= columnCount; i++) {
218 printTableBorder("┴");
220 printTableBorder(repeat('─', getColumnWidth(i) + 2));
222 printTableBorder("╯");
227 out.print(TerminalColor.Yellow, "Record count: ");
228 out.println(getCurrentRowCount());
234 public void writeUpdatesResult(int updatedRowsCount) {
235 super.writeUpdatesResult(updatedRowsCount);
236 printResultSeparator();
237 out.print(TerminalColor.Red, "Updated records: ");
238 out.println(updatedRowsCount);
244 public void writeEndDatabase() {
245 super.writeEndDatabase();
249 private void printResultSeparator() {
257 protected void printTableBorder(String border) {
258 if (asciiNostalgia) {
259 border = border.replaceAll("─", "-");
260 border = border.replaceAll("│", "|");
261 border = border.replaceAll("[╭┬╮├┼┤╰┴╯]", "+");
264 out.print(TerminalColor.Green, border);
267 protected void printTableIndent() {
271 protected void printValueWithWhitespaceReplaced(String valueString) {
273 Matcher m = whitespaceToReplace.matcher(valueString);
276 while (m.find(start)) {
278 out.print(TerminalColor.Cyan, valueString.substring(start, m.start()));
282 out.print(TerminalColor.Red, "↲");
285 out.print(TerminalColor.Red, "↹");
288 throw new IllegalStateException("Unexpected whitespace token: „" + m.group() + "“");
294 out.print(TerminalColor.Cyan, valueString.substring(start, valueString.length()));