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 info.globalcode.sql.dk.configuration.PropertyDeclaration;
26 import static info.globalcode.sql.dk.formatting.CommonProperties.COLORFUL;
27 import static info.globalcode.sql.dk.formatting.CommonProperties.COLORFUL_DESCRIPTION;
28 import java.util.List;
29 import java.util.regex.Matcher;
30 import java.util.regex.Pattern;
34 * Prints human-readable output – tables of result sets and text messages with update counts.
38 * Longer values might break the table – overflow the cells – see alternative tabular formatters
39 * and the {@linkplain #PROPERTY_TRIM} property.
42 * @author Ing. František Kučera (frantovo.cz)
43 * @see TabularPrefetchingFormatter
44 * @see TabularWrappingFormatter
46 @PropertyDeclaration(name = COLORFUL, type = Boolean.class, description = COLORFUL_DESCRIPTION)
47 @PropertyDeclaration(name = TabularFormatter.PROPERTY_ASCII, type = Boolean.class, description = "whether to use ASCII table borders instead of unicode ones")
48 @PropertyDeclaration(name = TabularFormatter.PROPERTY_TRIM, type = Boolean.class, description = "whether to trim the values to fit the column width")
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 private static final String NBSP = " ";
57 private static final Pattern whitespaceToReplace = Pattern.compile("\\n|\\r|\\t|" + NBSP);
58 protected ColorfulPrintWriter out;
59 private boolean firstResult = true;
60 private int[] columnWidth;
62 * use ASCII borders instead of unicode ones
64 private final boolean asciiNostalgia;
66 * Trim values if they are longer than cell size
68 private final boolean trimValues;
70 public TabularFormatter(FormatterContext formatterContext) {
71 super(formatterContext);
72 out = new ColorfulPrintWriter(formatterContext.getOutputStream());
73 asciiNostalgia = formatterContext.getProperties().getBoolean(PROPERTY_ASCII, false);
74 trimValues = formatterContext.getProperties().getBoolean(PROPERTY_TRIM, false);
75 out.setColorful(formatterContext.getProperties().getBoolean(COLORFUL, true));
79 public void writeStartResultSet(ColumnsHeader header) {
80 super.writeStartResultSet(header);
81 printResultSeparator();
83 initColumnWidths(header.getColumnCount());
86 printTableBorder("╭");
88 List<ColumnDescriptor> columnDescriptors = header.getColumnDescriptors();
90 for (ColumnDescriptor cd : columnDescriptors) {
91 // padding: make header cell at least same width as data cells in this column
92 int typeWidth = cd.getTypeName().length() + HEADER_TYPE_PREFIX.length() + HEADER_TYPE_SUFFIX.length();
93 cd.setLabel(rpad(cd.getLabel(), getColumnWidth(cd.getColumnNumber()) - typeWidth));
94 updateColumnWidth(cd.getColumnNumber(), cd.getLabel().length() + typeWidth);
96 if (!cd.isFirstColumn()) {
97 printTableBorder("┬");
99 printTableBorder(repeat('─', getColumnWidth(cd.getColumnNumber()) + 2));
101 printTableBorder("╮");
104 for (ColumnDescriptor cd : columnDescriptors) {
105 if (cd.isFirstColumn()) {
107 printTableBorder("│ ");
109 printTableBorder(" │ ");
111 out.print(TerminalStyle.Bright, cd.getLabel());
112 out.print(HEADER_TYPE_PREFIX);
113 out.print(cd.getTypeName());
114 out.print(HEADER_TYPE_SUFFIX);
115 if (cd.isLastColumn()) {
116 printTableBorder(" │");
122 printTableBorder("├");
123 for (int i = 1; i <= header.getColumnCount(); i++) {
125 printTableBorder("┼");
127 printTableBorder(repeat('─', getColumnWidth(i) + 2));
129 printTableBorder("┤");
136 * Must be called before
137 * {@linkplain #updateColumnWidth(int, int)}
138 * and {@linkplain #getColumnWidth(int)}
139 * for each result set.
141 * @param columnCount number of columns in current result set
143 protected void initColumnWidths(int columnCount) {
144 if (columnWidth == null) {
145 columnWidth = new int[columnCount];
149 protected void cleanColumnWidths() {
154 public void writeColumnValue(Object value) {
155 super.writeColumnValue(value);
156 writeColumnValueInternal(value);
159 protected void writeColumnValueInternal(Object value) {
161 if (isCurrentColumnFirst()) {
163 printTableBorder("│ ");
165 printTableBorder(" │ ");
168 String valueString = toString(value);
169 printValueWithWhitespaceReplaced(valueString);
171 if (isCurrentColumnLast()) {
172 printTableBorder(" │");
177 protected int getColumnWidth(int columnNumber) {
178 return columnWidth[columnNumber - 1];
181 private void setColumnWidth(int columnNumber, int width) {
182 columnWidth[columnNumber - 1] = width;
185 protected void updateColumnWidth(int columnNumber, int width) {
186 int oldWidth = getColumnWidth(columnNumber);
187 setColumnWidth(columnNumber, Math.max(width, oldWidth));
191 protected String toString(Object value) {
192 final int width = getColumnWidth(getCurrentColumnsCount());
194 if (value instanceof Number || value instanceof Boolean) {
195 result = lpad(String.valueOf(value), width);
197 result = rpad(String.valueOf(value), width);
199 // ? value = (boolean) value ? "✔" : "✗";
201 if (trimValues && result.length() > width) {
202 result = result.substring(0, width - 1) + "…";
209 public void writeEndRow() {
211 writeEndRowInternal();
214 public void writeEndRowInternal() {
220 public void writeEndResultSet() {
221 int columnCount = getCurrentColumnsHeader().getColumnCount();
222 super.writeEndResultSet();
225 printTableBorder("╰");
226 for (int i = 1; i <= columnCount; i++) {
228 printTableBorder("┴");
230 printTableBorder(repeat('─', getColumnWidth(i) + 2));
232 printTableBorder("╯");
237 out.print(TerminalColor.Yellow, "Record count: ");
238 out.println(getCurrentRowCount());
244 public void writeUpdatesResult(int updatedRowsCount) {
245 super.writeUpdatesResult(updatedRowsCount);
246 printResultSeparator();
247 out.print(TerminalColor.Red, "Updated records: ");
248 out.println(updatedRowsCount);
254 public void writeEndDatabase() {
255 super.writeEndDatabase();
259 private void printResultSeparator() {
267 protected void printTableBorder(String border) {
268 if (asciiNostalgia) {
269 border = border.replaceAll("─", "-");
270 border = border.replaceAll("│", "|");
271 border = border.replaceAll("[╭┬╮├┼┤╰┴╯]", "+");
274 out.print(TerminalColor.Green, border);
277 protected void printTableIndent() {
281 protected void printValueWithWhitespaceReplaced(String valueString) {
283 Matcher m = whitespaceToReplace.matcher(valueString);
286 while (m.find(start)) {
288 out.print(TerminalColor.Cyan, valueString.substring(start, m.start()));
292 out.print(TerminalColor.Red, "↲");
295 out.print(TerminalColor.Red, "⏎");
298 out.print(TerminalColor.Red, "↹");
301 out.print(TerminalColor.Red, "⎵");
304 throw new IllegalStateException("Unexpected whitespace token: „" + m.group() + "“");
310 out.print(TerminalColor.Cyan, valueString.substring(start, valueString.length()));