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 info.globalcode.sql.dk.Functions;
23 import static info.globalcode.sql.dk.Functions.lpad;
24 import static info.globalcode.sql.dk.Functions.rpad;
25 import static info.globalcode.sql.dk.Functions.repeat;
26 import info.globalcode.sql.dk.configuration.PropertyDeclaration;
27 import static info.globalcode.sql.dk.formatting.CommonProperties.COLORFUL;
28 import static info.globalcode.sql.dk.formatting.CommonProperties.COLORFUL_DESCRIPTION;
29 import java.util.List;
33 * Prints human-readable output – tables of result sets and text messages with update counts.
37 * Longer values might break the table – overflow the cells – see alternative tabular formatters
38 * and the {@linkplain #PROPERTY_TRIM} property.
41 * @author Ing. František Kučera (frantovo.cz)
42 * @see TabularPrefetchingFormatter
43 * @see TabularWrappingFormatter
45 @PropertyDeclaration(name = COLORFUL, defaultValue = "true", type = Boolean.class, description = COLORFUL_DESCRIPTION)
46 @PropertyDeclaration(name = TabularFormatter.PROPERTY_ASCII, defaultValue = "false", type = Boolean.class, description = "whether to use ASCII table borders instead of unicode ones")
47 @PropertyDeclaration(name = TabularFormatter.PROPERTY_TRIM, defaultValue = "false", type = Boolean.class, description = "whether to trim the values to fit the column width")
48 @PropertyDeclaration(name = TabularFormatter.PROPERTY_HEADER_TYPE, defaultValue = "true", type = Boolean.class, description = "whether to print data types in column headers")
49 public class TabularFormatter extends AbstractFormatter {
51 public static final String NAME = "tabular"; // bash-completion:formatter
52 private static final String HEADER_TYPE_PREFIX = " (";
53 private static final String HEADER_TYPE_SUFFIX = ")";
54 public static final String PROPERTY_ASCII = "ascii";
55 public static final String PROPERTY_TRIM = "trim";
56 public static final String PROPERTY_HEADER_TYPE = "headerTypes";
57 protected ColorfulPrintWriter out;
58 private boolean firstResult = true;
59 private int[] columnWidth;
61 * use ASCII borders instead of unicode ones
63 private final boolean asciiNostalgia;
65 * Trim values if they are longer than cell size
67 private final boolean trimValues;
69 * Print data type of each column in the header
71 private final boolean printHeaderTypes;
73 public TabularFormatter(FormatterContext formatterContext) {
74 super(formatterContext);
75 out = new ColorfulPrintWriter(formatterContext.getOutputStream());
76 asciiNostalgia = formatterContext.getProperties().getBoolean(PROPERTY_ASCII, false);
77 trimValues = formatterContext.getProperties().getBoolean(PROPERTY_TRIM, false);
78 printHeaderTypes = formatterContext.getProperties().getBoolean(PROPERTY_HEADER_TYPE, true);
79 out.setColorful(formatterContext.getProperties().getBoolean(COLORFUL, true));
83 public void writeStartResultSet(ColumnsHeader header) {
84 super.writeStartResultSet(header);
85 printResultSeparator();
87 initColumnWidths(header.getColumnCount());
90 printTableBorder("╭");
92 List<ColumnDescriptor> columnDescriptors = header.getColumnDescriptors();
94 for (ColumnDescriptor cd : columnDescriptors) {
95 // padding: make header cell at least same width as data cells in this column
96 int typeWidth = printHeaderTypes ? cd.getTypeName().length() + HEADER_TYPE_PREFIX.length() + HEADER_TYPE_SUFFIX.length() : 0;
97 cd.setLabel(rpad(cd.getLabel(), getColumnWidth(cd.getColumnNumber()) - typeWidth));
98 updateColumnWidth(cd.getColumnNumber(), cd.getLabel().length() + typeWidth);
100 if (!cd.isFirstColumn()) {
101 printTableBorder("┬");
103 printTableBorder(repeat('─', getColumnWidth(cd.getColumnNumber()) + 2));
105 printTableBorder("╮");
108 for (ColumnDescriptor cd : columnDescriptors) {
109 if (cd.isFirstColumn()) {
111 printTableBorder("│ ");
113 printTableBorder(" │ ");
115 out.print(TerminalStyle.Bright, cd.getLabel());
116 if (printHeaderTypes) {
117 out.print(HEADER_TYPE_PREFIX);
118 out.print(cd.getTypeName());
119 out.print(HEADER_TYPE_SUFFIX);
121 if (cd.isLastColumn()) {
122 printTableBorder(" │");
128 printTableBorder("├");
129 for (int i = 1; i <= header.getColumnCount(); i++) {
131 printTableBorder("┼");
133 printTableBorder(repeat('─', getColumnWidth(i) + 2));
135 printTableBorder("┤");
142 * Must be called before
143 * {@linkplain #updateColumnWidth(int, int)}
144 * and {@linkplain #getColumnWidth(int)}
145 * for each result set.
147 * @param columnCount number of columns in current result set
149 protected void initColumnWidths(int columnCount) {
150 if (columnWidth == null) {
151 columnWidth = new int[columnCount];
155 protected void cleanColumnWidths() {
160 public void writeColumnValue(Object value) {
161 super.writeColumnValue(value);
162 writeColumnValueInternal(value);
165 protected void writeColumnValueInternal(Object value) {
167 if (isCurrentColumnFirst()) {
169 printTableBorder("│ ");
171 printTableBorder(" │ ");
174 printValueWithWhitespaceReplaced(toString(value));
176 if (isCurrentColumnLast()) {
177 printTableBorder(" │");
182 protected void printValueWithWhitespaceReplaced(String text) {
183 Functions.printValueWithWhitespaceReplaced(out, text, TerminalColor.Cyan, TerminalColor.Red);
186 protected int getColumnWidth(int columnNumber) {
187 return columnWidth[columnNumber - 1];
190 private void setColumnWidth(int columnNumber, int width) {
191 columnWidth[columnNumber - 1] = width;
194 protected void updateColumnWidth(int columnNumber, int width) {
195 int oldWidth = getColumnWidth(columnNumber);
196 setColumnWidth(columnNumber, Math.max(width, oldWidth));
200 protected String toString(Object value) {
201 final int width = getColumnWidth(getCurrentColumnsCount());
203 if (value instanceof Number || value instanceof Boolean) {
204 result = lpad(String.valueOf(value), width);
206 result = rpad(String.valueOf(value), width);
208 // ? value = (boolean) value ? "✔" : "✗";
210 if (trimValues && result.length() > width) {
211 result = result.substring(0, width - 1) + "…";
218 public void writeEndRow() {
220 writeEndRowInternal();
223 public void writeEndRowInternal() {
229 public void writeEndResultSet() {
230 int columnCount = getCurrentColumnsHeader().getColumnCount();
231 super.writeEndResultSet();
234 printTableBorder("╰");
235 for (int i = 1; i <= columnCount; i++) {
237 printTableBorder("┴");
239 printTableBorder(repeat('─', getColumnWidth(i) + 2));
241 printTableBorder("╯");
246 out.print(TerminalColor.Yellow, "Record count: ");
247 out.println(getCurrentRowCount());
253 public void writeUpdatesResult(int updatedRowsCount) {
254 super.writeUpdatesResult(updatedRowsCount);
255 printResultSeparator();
256 out.print(TerminalColor.Red, "Updated records: ");
257 out.println(updatedRowsCount);
263 public void writeEndDatabase() {
264 super.writeEndDatabase();
268 private void printResultSeparator() {
276 protected void printTableBorder(String border) {
277 if (asciiNostalgia) {
278 border = border.replaceAll("─", "-");
279 border = border.replaceAll("│", "|");
280 border = border.replaceAll("[╭┬╮├┼┤╰┴╯]", "+");
283 out.print(TerminalColor.Green, border);
286 protected void printTableIndent() {
291 * @return whether should print only ASCII characters instead of unlimited Unicode.
293 protected boolean isAsciiNostalgia() {
294 return asciiNostalgia;