java/sql-dk/src/main/java/info/globalcode/sql/dk/formatting/TabularFormatter.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 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.sql.SQLException;
30 import java.sql.SQLXML;
31 import java.util.List;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
37 * Prints human-readable output – tables of result sets and text messages with update counts.
41 * Longer values might break the table – overflow the cells – see alternative tabular formatters and
42 * the {@linkplain #PROPERTY_TRIM} property.
45 * @author Ing. František Kučera (frantovo.cz)
46 * @see TabularPrefetchingFormatter
47 * @see TabularWrappingFormatter
49 @PropertyDeclaration(name = COLORFUL, defaultValue = "true", type = Boolean.class, description = COLORFUL_DESCRIPTION)
50 @PropertyDeclaration(name = TabularFormatter.PROPERTY_ASCII, defaultValue = "false", type = Boolean.class, description = "whether to use ASCII table borders instead of unicode ones")
51 @PropertyDeclaration(name = TabularFormatter.PROPERTY_TRIM, defaultValue = "false", type = Boolean.class, description = "whether to trim the values to fit the column width")
52 @PropertyDeclaration(name = TabularFormatter.PROPERTY_HEADER_TYPE, defaultValue = "true", type = Boolean.class, description = "whether to print data types in column headers")
53 public class TabularFormatter extends AbstractFormatter {
55 private static final Logger log = Logger.getLogger(TabularFormatter.class.getName());
56 public static final String NAME = "tabular"; // bash-completion:formatter
57 private static final String HEADER_TYPE_PREFIX = " (";
58 private static final String HEADER_TYPE_SUFFIX = ")";
59 public static final String PROPERTY_ASCII = "ascii";
60 public static final String PROPERTY_TRIM = "trim";
61 public static final String PROPERTY_HEADER_TYPE = "headerTypes";
62 protected ColorfulPrintWriter out;
63 private boolean firstResult = true;
64 private int[] columnWidth;
66 * use ASCII borders instead of unicode ones
68 private final boolean asciiNostalgia;
70 * Trim values if they are longer than cell size
72 private final boolean trimValues;
74 * Print data type of each column in the header
76 private final boolean printHeaderTypes;
78 public TabularFormatter(FormatterContext formatterContext) {
79 super(formatterContext);
80 out = new ColorfulPrintWriter(formatterContext.getOutputStream());
81 asciiNostalgia = formatterContext.getProperties().getBoolean(PROPERTY_ASCII, false);
82 trimValues = formatterContext.getProperties().getBoolean(PROPERTY_TRIM, false);
83 printHeaderTypes = formatterContext.getProperties().getBoolean(PROPERTY_HEADER_TYPE, true);
84 out.setColorful(formatterContext.getProperties().getBoolean(COLORFUL, true));
88 public void writeStartResultSet(ColumnsHeader header) {
89 super.writeStartResultSet(header);
90 printResultSeparator();
92 initColumnWidths(header.getColumnCount());
95 printTableBorder("╭");
97 List<ColumnDescriptor> columnDescriptors = header.getColumnDescriptors();
99 for (ColumnDescriptor cd : columnDescriptors) {
100 // padding: make header cell at least same width as data cells in this column
101 int typeWidth = printHeaderTypes ? cd.getTypeName().length() + HEADER_TYPE_PREFIX.length() + HEADER_TYPE_SUFFIX.length() : 0;
102 cd.setLabel(rpad(cd.getLabel(), getColumnWidth(cd.getColumnNumber()) - typeWidth));
103 updateColumnWidth(cd.getColumnNumber(), cd.getLabel().length() + typeWidth);
105 if (!cd.isFirstColumn()) {
106 printTableBorder("┬");
108 printTableBorder(repeat('─', getColumnWidth(cd.getColumnNumber()) + 2));
110 printTableBorder("╮");
113 for (ColumnDescriptor cd : columnDescriptors) {
114 if (cd.isFirstColumn()) {
116 printTableBorder("│ ");
118 printTableBorder(" │ ");
120 out.print(TerminalStyle.Bright, cd.getLabel());
121 if (printHeaderTypes) {
122 out.print(HEADER_TYPE_PREFIX);
123 out.print(cd.getTypeName());
124 out.print(HEADER_TYPE_SUFFIX);
126 if (cd.isLastColumn()) {
127 printTableBorder(" │");
133 printTableBorder("├");
134 for (int i = 1; i <= header.getColumnCount(); i++) {
136 printTableBorder("┼");
138 printTableBorder(repeat('─', getColumnWidth(i) + 2));
140 printTableBorder("┤");
147 * Must be called before {@linkplain #updateColumnWidth(int, int)} and
148 * {@linkplain #getColumnWidth(int)} for each result set.
150 * @param columnCount number of columns in current result set
152 protected void initColumnWidths(int columnCount) {
153 if (columnWidth == null) {
154 columnWidth = new int[columnCount];
158 protected void cleanColumnWidths() {
163 public void writeColumnValue(Object value) {
164 super.writeColumnValue(value);
165 writeColumnValueInternal(value);
168 protected void writeColumnValueInternal(Object value) {
170 if (isCurrentColumnFirst()) {
172 printTableBorder("│ ");
174 printTableBorder(" │ ");
177 printValueWithWhitespaceReplaced(toString(value));
179 if (isCurrentColumnLast()) {
180 printTableBorder(" │");
185 protected void printValueWithWhitespaceReplaced(String text) {
186 Functions.printValueWithWhitespaceReplaced(out, text, TerminalColor.Cyan, TerminalColor.Red);
189 protected int getColumnWidth(int columnNumber) {
190 return columnWidth[columnNumber - 1];
193 private void setColumnWidth(int columnNumber, int width) {
194 columnWidth[columnNumber - 1] = width;
197 protected void updateColumnWidth(int columnNumber, int width) {
198 int oldWidth = getColumnWidth(columnNumber);
199 setColumnWidth(columnNumber, Math.max(width, oldWidth));
203 protected String toString(Object value) {
204 final int width = getColumnWidth(getCurrentColumnsCount());
206 if (value instanceof Number || value instanceof Boolean) {
207 result = lpad(String.valueOf(value), width);
209 if (value instanceof SQLXML) {
210 // TODO: move to a common method, share with other formatters
212 value = ((SQLXML) value).getString();
213 } catch (SQLException e) {
214 log.log(Level.SEVERE, "Unable to format XML", e);
218 result = rpad(String.valueOf(value), width);
220 // ? value = (boolean) value ? "✔" : "✗";
222 if (trimValues && result.length() > width) {
223 result = result.substring(0, width - 1) + "…";
230 public void writeEndRow() {
232 writeEndRowInternal();
235 public void writeEndRowInternal() {
241 public void writeEndResultSet() {
242 int columnCount = getCurrentColumnsHeader().getColumnCount();
243 super.writeEndResultSet();
246 printTableBorder("╰");
247 for (int i = 1; i <= columnCount; i++) {
249 printTableBorder("┴");
251 printTableBorder(repeat('─', getColumnWidth(i) + 2));
253 printTableBorder("╯");
258 out.print(TerminalColor.Yellow, "Record count: ");
259 out.println(getCurrentRowCount());
265 public void writeUpdatesResult(int updatedRowsCount) {
266 super.writeUpdatesResult(updatedRowsCount);
267 printResultSeparator();
268 out.print(TerminalColor.Red, "Updated records: ");
269 out.println(updatedRowsCount);
275 public void writeEndDatabase() {
276 super.writeEndDatabase();
280 private void printResultSeparator() {
288 protected void printTableBorder(String border) {
289 if (asciiNostalgia) {
290 border = border.replaceAll("─", "-");
291 border = border.replaceAll("│", "|");
292 border = border.replaceAll("[╭┬╮├┼┤╰┴╯]", "+");
295 out.print(TerminalColor.Green, border);
298 protected void printTableIndent() {
303 * @return whether should print only ASCII characters instead of unlimited Unicode.
305 protected boolean isAsciiNostalgia() {
306 return asciiNostalgia;