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.Scanner;
29 * <p>Prints human-readable output – tables of result sets and text messages with update counts.</p>
31 * <p>Longer values might break the table – overflow the cells – see alternative tabular formatters
32 * and the {@linkplain #PROPERTY_TRIM} property.</p>
34 * @author Ing. František Kučera (frantovo.cz)
35 * @see TabularPrefetchingFormatter
36 * @see TabularWrappingFormatter
38 public class TabularFormatter extends AbstractFormatter {
40 public static final String NAME = "tabular"; // bash-completion:formatter
41 private static final String HEADER_TYPE_PREFIX = " (";
42 private static final String HEADER_TYPE_SUFFIX = ")";
43 public static final String PROPERTY_ASCII = "ascii";
44 public static final String PROPERTY_COLORFUL = "color";
45 public static final String PROPERTY_TRIM = "trim";
46 protected ColorfulPrintWriter out;
47 private boolean firstResult = true;
48 private int[] columnWidth;
50 * use ASCII borders instead of unicode ones
52 private final boolean asciiNostalgia;
54 * Trim values if they are longer than cell size
56 private final boolean trimValues;
58 public TabularFormatter(FormatterContext formatterContext) {
59 super(formatterContext);
60 out = new ColorfulPrintWriter(formatterContext.getOutputStream());
61 asciiNostalgia = formatterContext.getProperties().getBoolean(PROPERTY_ASCII, false);
62 trimValues = formatterContext.getProperties().getBoolean(PROPERTY_TRIM, false);
63 out.setColorful(formatterContext.getProperties().getBoolean(PROPERTY_COLORFUL, true));
67 public void writeStartResultSet(ColumnsHeader header) {
68 super.writeStartResultSet(header);
69 printResultSeparator();
71 initColumnWidths(header.getColumnCount());
74 printTableBorder("╭");
76 List<ColumnDescriptor> columnDescriptors = header.getColumnDescriptors();
78 for (ColumnDescriptor cd : columnDescriptors) {
79 // padding: make header cell at least same width as data cells in this column
80 int typeWidth = cd.getTypeName().length() + HEADER_TYPE_PREFIX.length() + HEADER_TYPE_SUFFIX.length();
81 cd.setLabel(rpad(cd.getLabel(), getColumnWidth(cd.getColumnNumber()) - typeWidth));
82 updateColumnWidth(cd.getColumnNumber(), cd.getLabel().length() + typeWidth);
84 if (!cd.isFirstColumn()) {
85 printTableBorder("┬");
87 printTableBorder(repeat('─', getColumnWidth(cd.getColumnNumber()) + 2));
89 printTableBorder("╮");
92 for (ColumnDescriptor cd : columnDescriptors) {
93 if (cd.isFirstColumn()) {
95 printTableBorder("│ ");
97 printTableBorder(" │ ");
99 out.print(TerminalStyle.Bright, cd.getLabel());
100 out.print(HEADER_TYPE_PREFIX);
101 out.print(cd.getTypeName());
102 out.print(HEADER_TYPE_SUFFIX);
103 if (cd.isLastColumn()) {
104 printTableBorder(" │");
110 printTableBorder("├");
111 for (int i = 1; i <= header.getColumnCount(); i++) {
113 printTableBorder("┼");
115 printTableBorder(repeat('─', getColumnWidth(i) + 2));
117 printTableBorder("┤");
124 * Must be called before
125 * {@linkplain #updateColumnWidth(int, int)}
126 * and {@linkplain #getColumnWidth(int)}
127 * for each result set.
129 * @param columnCount number of columns in current result set
131 protected void initColumnWidths(int columnCount) {
132 if (columnWidth == null) {
133 columnWidth = new int[columnCount];
137 protected void cleanColumnWidths() {
142 public void writeColumnValue(Object value) {
143 super.writeColumnValue(value);
144 writeColumnValueInternal(value);
147 protected void writeColumnValueInternal(Object value) {
149 if (isCurrentColumnFirst()) {
151 printTableBorder("│ ");
153 printTableBorder(" │ ");
156 String valueString = toString(value);
157 printValueWithNewLinesReplaced(valueString);
159 if (isCurrentColumnLast()) {
160 printTableBorder(" │");
165 protected int getColumnWidth(int columnNumber) {
166 return columnWidth[columnNumber - 1];
169 private void setColumnWidth(int columnNumber, int width) {
170 columnWidth[columnNumber - 1] = width;
173 protected void updateColumnWidth(int columnNumber, int width) {
174 int oldWidth = getColumnWidth(columnNumber);
175 setColumnWidth(columnNumber, Math.max(width, oldWidth));
179 protected String toString(Object value) {
180 final int width = getColumnWidth(getCurrentColumnsCount());
182 if (value instanceof Number || value instanceof Boolean) {
183 result = lpad(String.valueOf(value), width);
185 result = rpad(String.valueOf(value), width);
187 // ? value = (boolean) value ? "✔" : "✗";
189 if (trimValues && result.length() > width) {
190 result = result.substring(0, width - 1) + "…";
197 public void writeEndRow() {
199 writeEndRowInternal();
202 public void writeEndRowInternal() {
208 public void writeEndResultSet() {
209 int columnCount = getCurrentColumnsHeader().getColumnCount();
210 super.writeEndResultSet();
213 printTableBorder("╰");
214 for (int i = 1; i <= columnCount; i++) {
216 printTableBorder("┴");
218 printTableBorder(repeat('─', getColumnWidth(i) + 2));
220 printTableBorder("╯");
225 out.print(TerminalColor.Yellow, "Record count: ");
226 out.println(getCurrentRowCount());
232 public void writeUpdatesResult(int updatedRowsCount) {
233 super.writeUpdatesResult(updatedRowsCount);
234 printResultSeparator();
235 out.print(TerminalColor.Red, "Updated records: ");
236 out.println(updatedRowsCount);
242 public void writeEndDatabase() {
243 super.writeEndDatabase();
247 private void printResultSeparator() {
255 protected void printTableBorder(String border) {
256 if (asciiNostalgia) {
257 border = border.replaceAll("─", "-");
258 border = border.replaceAll("│", "|");
259 border = border.replaceAll("[╭┬╮├┼┤╰┴╯]", "+");
262 out.print(TerminalColor.Green, border);
265 protected void printTableIndent() {
269 protected void printValueWithNewLinesReplaced(String valueString) {
270 String[] valueParts = valueString.split("\n");
271 for (int i = 0; i < valueParts.length; i++) {
272 String valuePart = valueParts[i];
273 // TODO: replace also TABs
274 out.print(TerminalColor.Cyan, valuePart);
275 if (i < valueParts.length - 1) {
276 out.print(TerminalColor.Red, "↲");
280 if (valueString.endsWith("\n")) {
281 out.print(TerminalColor.Red, "↲");