java/sql-dk/src/info/globalcode/sql/dk/formatting/TabularFormatter.java
author František Kučera <franta-hg@frantovo.cz>
Sun, 19 Jan 2014 18:30:21 +0100
branchv_0
changeset 167 84aaa91642bf
parent 155 eb3676c6929b
child 169 4e131a0b521a
permissions -rw-r--r--
fix Tabular: table was broken if value ended with \n
     1 /**
     2  * SQL-DK
     3  * Copyright © 2013 František Kučera (frantovo.cz)
     4  *
     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.
     9  *
    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.
    14  *
    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/>.
    17  */
    18 package info.globalcode.sql.dk.formatting;
    19 
    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;
    27 
    28 /**
    29  * <p>Prints human-readable output – tables of result sets and text messages with update counts.</p>
    30  *
    31  * <p>Longer values might break the table – overflow the cells – see alternative tabular formatters
    32  * and the {@linkplain #PROPERTY_TRIM} property.</p>
    33  *
    34  * @author Ing. František Kučera (frantovo.cz)
    35  * @see TabularPrefetchingFormatter
    36  * @see TabularWrappingFormatter
    37  */
    38 public class TabularFormatter extends AbstractFormatter {
    39 
    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;
    49 	/**
    50 	 * use ASCII borders instead of unicode ones
    51 	 */
    52 	private final boolean asciiNostalgia;
    53 	/**
    54 	 * Trim values if they are longer than cell size
    55 	 */
    56 	private final boolean trimValues;
    57 
    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));
    64 	}
    65 
    66 	@Override
    67 	public void writeStartResultSet(ColumnsHeader header) {
    68 		super.writeStartResultSet(header);
    69 		printResultSeparator();
    70 
    71 		initColumnWidths(header.getColumnCount());
    72 
    73 		printTableIndent();
    74 		printTableBorder("╭");
    75 
    76 		List<ColumnDescriptor> columnDescriptors = header.getColumnDescriptors();
    77 
    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);
    83 
    84 			if (!cd.isFirstColumn()) {
    85 				printTableBorder("┬");
    86 			}
    87 			printTableBorder(repeat('─', getColumnWidth(cd.getColumnNumber()) + 2));
    88 		}
    89 		printTableBorder("╮");
    90 		out.println();
    91 
    92 		for (ColumnDescriptor cd : columnDescriptors) {
    93 			if (cd.isFirstColumn()) {
    94 				printTableIndent();
    95 				printTableBorder("│ ");
    96 			} else {
    97 				printTableBorder(" │ ");
    98 			}
    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(" │");
   105 			}
   106 		}
   107 		out.println();
   108 
   109 		printTableIndent();
   110 		printTableBorder("├");
   111 		for (int i = 1; i <= header.getColumnCount(); i++) {
   112 			if (i > 1) {
   113 				printTableBorder("┼");
   114 			}
   115 			printTableBorder(repeat('─', getColumnWidth(i) + 2));
   116 		}
   117 		printTableBorder("┤");
   118 		out.println();
   119 
   120 		out.flush();
   121 	}
   122 
   123 	/**
   124 	 * Must be called before
   125 	 * {@linkplain #updateColumnWidth(int, int)}
   126 	 * and {@linkplain #getColumnWidth(int)}
   127 	 * for each result set.
   128 	 *
   129 	 * @param columnCount number of columns in current result set
   130 	 */
   131 	protected void initColumnWidths(int columnCount) {
   132 		if (columnWidth == null) {
   133 			columnWidth = new int[columnCount];
   134 		}
   135 	}
   136 
   137 	protected void cleanColumnWidths() {
   138 		columnWidth = null;
   139 	}
   140 
   141 	@Override
   142 	public void writeColumnValue(Object value) {
   143 		super.writeColumnValue(value);
   144 		writeColumnValueInternal(value);
   145 	}
   146 
   147 	protected void writeColumnValueInternal(Object value) {
   148 
   149 		if (isCurrentColumnFirst()) {
   150 			printTableIndent();
   151 			printTableBorder("│ ");
   152 		} else {
   153 			printTableBorder(" │ ");
   154 		}
   155 
   156 		String valueString = toString(value);
   157 		printValueWithNewLinesReplaced(valueString);
   158 
   159 		if (isCurrentColumnLast()) {
   160 			printTableBorder(" │");
   161 		}
   162 
   163 	}
   164 
   165 	protected int getColumnWidth(int columnNumber) {
   166 		return columnWidth[columnNumber - 1];
   167 	}
   168 
   169 	private void setColumnWidth(int columnNumber, int width) {
   170 		columnWidth[columnNumber - 1] = width;
   171 	}
   172 
   173 	protected void updateColumnWidth(int columnNumber, int width) {
   174 		int oldWidth = getColumnWidth(columnNumber);
   175 		setColumnWidth(columnNumber, Math.max(width, oldWidth));
   176 
   177 	}
   178 
   179 	protected String toString(Object value) {
   180 		final int width = getColumnWidth(getCurrentColumnsCount());
   181 		String result;
   182 		if (value instanceof Number || value instanceof Boolean) {
   183 			result = lpad(String.valueOf(value), width);
   184 		} else {
   185 			result = rpad(String.valueOf(value), width);
   186 		}
   187 		// ?	value = (boolean) value ? "✔" : "✗";
   188 
   189 		if (trimValues && result.length() > width) {
   190 			result = result.substring(0, width - 1) + "…";
   191 		}
   192 
   193 		return result;
   194 	}
   195 
   196 	@Override
   197 	public void writeEndRow() {
   198 		super.writeEndRow();
   199 		writeEndRowInternal();
   200 	}
   201 
   202 	public void writeEndRowInternal() {
   203 		out.println();
   204 		out.flush();
   205 	}
   206 
   207 	@Override
   208 	public void writeEndResultSet() {
   209 		int columnCount = getCurrentColumnsHeader().getColumnCount();
   210 		super.writeEndResultSet();
   211 
   212 		printTableIndent();
   213 		printTableBorder("╰");
   214 		for (int i = 1; i <= columnCount; i++) {
   215 			if (i > 1) {
   216 				printTableBorder("┴");
   217 			}
   218 			printTableBorder(repeat('─', getColumnWidth(i) + 2));
   219 		}
   220 		printTableBorder("╯");
   221 		out.println();
   222 
   223 		cleanColumnWidths();
   224 
   225 		out.print(TerminalColor.Yellow, "Record count: ");
   226 		out.println(getCurrentRowCount());
   227 		out.bell();
   228 		out.flush();
   229 	}
   230 
   231 	@Override
   232 	public void writeUpdatesResult(int updatedRowsCount) {
   233 		super.writeUpdatesResult(updatedRowsCount);
   234 		printResultSeparator();
   235 		out.print(TerminalColor.Red, "Updated records: ");
   236 		out.println(updatedRowsCount);
   237 		out.bell();
   238 		out.flush();
   239 	}
   240 
   241 	@Override
   242 	public void writeEndDatabase() {
   243 		super.writeEndDatabase();
   244 		out.flush();
   245 	}
   246 
   247 	private void printResultSeparator() {
   248 		if (firstResult) {
   249 			firstResult = false;
   250 		} else {
   251 			out.println();
   252 		}
   253 	}
   254 
   255 	protected void printTableBorder(String border) {
   256 		if (asciiNostalgia) {
   257 			border = border.replaceAll("─", "-");
   258 			border = border.replaceAll("│", "|");
   259 			border = border.replaceAll("[╭┬╮├┼┤╰┴╯]", "+");
   260 		}
   261 
   262 		out.print(TerminalColor.Green, border);
   263 	}
   264 
   265 	protected void printTableIndent() {
   266 		out.print(" ");
   267 	}
   268 
   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, "↲");
   277 			}
   278 		}
   279 
   280 		if (valueString.endsWith("\n")) {
   281 			out.print(TerminalColor.Red, "↲");
   282 		}
   283 	}
   284 }