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