java/sql-dk/src/info/globalcode/sql/dk/formatting/TabularFormatter.java
author František Kučera <franta-hg@frantovo.cz>
Sun, 13 Sep 2015 19:25:36 +0200
branchv_0
changeset 227 0094319a274a
parent 224 36db9fd27436
child 234 305871254838
permissions -rw-r--r--
headerTypes: new option to hide column types in tabular headers
     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 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;
    30 
    31 /**
    32  * <p>
    33  * Prints human-readable output – tables of result sets and text messages with update counts.
    34  * </p>
    35  *
    36  * <p>
    37  * Longer values might break the table – overflow the cells – see alternative tabular formatters
    38  * and the {@linkplain #PROPERTY_TRIM} property.
    39  * </p>
    40  *
    41  * @author Ing. František Kučera (frantovo.cz)
    42  * @see TabularPrefetchingFormatter
    43  * @see TabularWrappingFormatter
    44  */
    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 {
    50 
    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;
    60 	/**
    61 	 * use ASCII borders instead of unicode ones
    62 	 */
    63 	private final boolean asciiNostalgia;
    64 	/**
    65 	 * Trim values if they are longer than cell size
    66 	 */
    67 	private final boolean trimValues;
    68 	/**
    69 	 * Print data type of each column in the header
    70 	 */
    71 	private final boolean printHeaderTypes;
    72 
    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));
    80 	}
    81 
    82 	@Override
    83 	public void writeStartResultSet(ColumnsHeader header) {
    84 		super.writeStartResultSet(header);
    85 		printResultSeparator();
    86 
    87 		initColumnWidths(header.getColumnCount());
    88 
    89 		printTableIndent();
    90 		printTableBorder("╭");
    91 
    92 		List<ColumnDescriptor> columnDescriptors = header.getColumnDescriptors();
    93 
    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);
    99 
   100 			if (!cd.isFirstColumn()) {
   101 				printTableBorder("┬");
   102 			}
   103 			printTableBorder(repeat('─', getColumnWidth(cd.getColumnNumber()) + 2));
   104 		}
   105 		printTableBorder("╮");
   106 		out.println();
   107 
   108 		for (ColumnDescriptor cd : columnDescriptors) {
   109 			if (cd.isFirstColumn()) {
   110 				printTableIndent();
   111 				printTableBorder("│ ");
   112 			} else {
   113 				printTableBorder(" │ ");
   114 			}
   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);
   120 			}
   121 			if (cd.isLastColumn()) {
   122 				printTableBorder(" │");
   123 			}
   124 		}
   125 		out.println();
   126 
   127 		printTableIndent();
   128 		printTableBorder("├");
   129 		for (int i = 1; i <= header.getColumnCount(); i++) {
   130 			if (i > 1) {
   131 				printTableBorder("┼");
   132 			}
   133 			printTableBorder(repeat('─', getColumnWidth(i) + 2));
   134 		}
   135 		printTableBorder("┤");
   136 		out.println();
   137 
   138 		out.flush();
   139 	}
   140 
   141 	/**
   142 	 * Must be called before
   143 	 * {@linkplain #updateColumnWidth(int, int)}
   144 	 * and {@linkplain #getColumnWidth(int)}
   145 	 * for each result set.
   146 	 *
   147 	 * @param columnCount number of columns in current result set
   148 	 */
   149 	protected void initColumnWidths(int columnCount) {
   150 		if (columnWidth == null) {
   151 			columnWidth = new int[columnCount];
   152 		}
   153 	}
   154 
   155 	protected void cleanColumnWidths() {
   156 		columnWidth = null;
   157 	}
   158 
   159 	@Override
   160 	public void writeColumnValue(Object value) {
   161 		super.writeColumnValue(value);
   162 		writeColumnValueInternal(value);
   163 	}
   164 
   165 	protected void writeColumnValueInternal(Object value) {
   166 
   167 		if (isCurrentColumnFirst()) {
   168 			printTableIndent();
   169 			printTableBorder("│ ");
   170 		} else {
   171 			printTableBorder(" │ ");
   172 		}
   173 
   174 		printValueWithWhitespaceReplaced(toString(value));
   175 
   176 		if (isCurrentColumnLast()) {
   177 			printTableBorder(" │");
   178 		}
   179 
   180 	}
   181 
   182 	protected void printValueWithWhitespaceReplaced(String text) {
   183 		Functions.printValueWithWhitespaceReplaced(out, text, TerminalColor.Cyan, TerminalColor.Red);
   184 	}
   185 
   186 	protected int getColumnWidth(int columnNumber) {
   187 		return columnWidth[columnNumber - 1];
   188 	}
   189 
   190 	private void setColumnWidth(int columnNumber, int width) {
   191 		columnWidth[columnNumber - 1] = width;
   192 	}
   193 
   194 	protected void updateColumnWidth(int columnNumber, int width) {
   195 		int oldWidth = getColumnWidth(columnNumber);
   196 		setColumnWidth(columnNumber, Math.max(width, oldWidth));
   197 
   198 	}
   199 
   200 	protected String toString(Object value) {
   201 		final int width = getColumnWidth(getCurrentColumnsCount());
   202 		String result;
   203 		if (value instanceof Number || value instanceof Boolean) {
   204 			result = lpad(String.valueOf(value), width);
   205 		} else {
   206 			result = rpad(String.valueOf(value), width);
   207 		}
   208 		// ?	value = (boolean) value ? "✔" : "✗";
   209 
   210 		if (trimValues && result.length() > width) {
   211 			result = result.substring(0, width - 1) + "…";
   212 		}
   213 
   214 		return result;
   215 	}
   216 
   217 	@Override
   218 	public void writeEndRow() {
   219 		super.writeEndRow();
   220 		writeEndRowInternal();
   221 	}
   222 
   223 	public void writeEndRowInternal() {
   224 		out.println();
   225 		out.flush();
   226 	}
   227 
   228 	@Override
   229 	public void writeEndResultSet() {
   230 		int columnCount = getCurrentColumnsHeader().getColumnCount();
   231 		super.writeEndResultSet();
   232 
   233 		printTableIndent();
   234 		printTableBorder("╰");
   235 		for (int i = 1; i <= columnCount; i++) {
   236 			if (i > 1) {
   237 				printTableBorder("┴");
   238 			}
   239 			printTableBorder(repeat('─', getColumnWidth(i) + 2));
   240 		}
   241 		printTableBorder("╯");
   242 		out.println();
   243 
   244 		cleanColumnWidths();
   245 
   246 		out.print(TerminalColor.Yellow, "Record count: ");
   247 		out.println(getCurrentRowCount());
   248 		out.bell();
   249 		out.flush();
   250 	}
   251 
   252 	@Override
   253 	public void writeUpdatesResult(int updatedRowsCount) {
   254 		super.writeUpdatesResult(updatedRowsCount);
   255 		printResultSeparator();
   256 		out.print(TerminalColor.Red, "Updated records: ");
   257 		out.println(updatedRowsCount);
   258 		out.bell();
   259 		out.flush();
   260 	}
   261 
   262 	@Override
   263 	public void writeEndDatabase() {
   264 		super.writeEndDatabase();
   265 		out.flush();
   266 	}
   267 
   268 	private void printResultSeparator() {
   269 		if (firstResult) {
   270 			firstResult = false;
   271 		} else {
   272 			out.println();
   273 		}
   274 	}
   275 
   276 	protected void printTableBorder(String border) {
   277 		if (asciiNostalgia) {
   278 			border = border.replaceAll("─", "-");
   279 			border = border.replaceAll("│", "|");
   280 			border = border.replaceAll("[╭┬╮├┼┤╰┴╯]", "+");
   281 		}
   282 
   283 		out.print(TerminalColor.Green, border);
   284 	}
   285 
   286 	protected void printTableIndent() {
   287 		out.print(" ");
   288 	}
   289 
   290 	/**
   291 	 * @return whether should print only ASCII characters instead of unlimited Unicode.
   292 	 */
   293 	protected boolean isAsciiNostalgia() {
   294 		return asciiNostalgia;
   295 	}
   296 }