java/sql-dk/src/info/globalcode/sql/dk/formatting/TabularFormatter.java
author František Kučera <franta-hg@frantovo.cz>
Tue, 07 Jan 2014 21:54:59 +0100
branchv_0
changeset 142 da1e38386d84
parent 124 9277b02a3b02
child 155 eb3676c6929b
permissions -rw-r--r--
Formatters: structural change – new level „statement“ → query and parameters are no more duplicated into each result set or updates result
     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 
    27 /**
    28  *
    29  * @author Ing. František Kučera (frantovo.cz)
    30  */
    31 public class TabularFormatter extends AbstractFormatter {
    32 
    33 	public static final String NAME = "tabular"; // bash-completion:formatter
    34 	private static final String HEADER_TYPE_PREFIX = " (";
    35 	private static final String HEADER_TYPE_SUFFIX = ")";
    36 	public static final String PROPERTY_ASCII = "ascii";
    37 	public static final String PROPERTY_COLORFUL = "color";
    38 	public static final String PROPERTY_TRIM = "trim";
    39 	protected ColorfulPrintWriter out;
    40 	private boolean firstResult = true;
    41 	private int[] columnWidth;
    42 	/**
    43 	 * use ASCII borders instead of unicode ones
    44 	 */
    45 	private final boolean asciiNostalgia;
    46 	/**
    47 	 * Trim values if they are longer than cell size
    48 	 */
    49 	private final boolean trimValues;
    50 
    51 	public TabularFormatter(FormatterContext formatterContext) {
    52 		super(formatterContext);
    53 		out = new ColorfulPrintWriter(formatterContext.getOutputStream());
    54 		asciiNostalgia = formatterContext.getProperties().getBoolean(PROPERTY_ASCII, false);
    55 		trimValues = formatterContext.getProperties().getBoolean(PROPERTY_TRIM, false);
    56 		out.setColorful(formatterContext.getProperties().getBoolean(PROPERTY_COLORFUL, true));
    57 	}
    58 
    59 	@Override
    60 	public void writeStartResultSet(ColumnsHeader header) {
    61 		super.writeStartResultSet(header);
    62 		printResultSeparator();
    63 
    64 		initColumnWidths(header.getColumnCount());
    65 
    66 		printTableIndent();
    67 		printTableBorder("╭");
    68 
    69 		List<ColumnDescriptor> columnDescriptors = header.getColumnDescriptors();
    70 
    71 		for (ColumnDescriptor cd : columnDescriptors) {
    72 			// padding: make header cell at least same width as data cells in this column
    73 			int typeWidth = cd.getTypeName().length() + HEADER_TYPE_PREFIX.length() + HEADER_TYPE_SUFFIX.length();
    74 			cd.setLabel(rpad(cd.getLabel(), getColumnWidth(cd.getColumnNumber()) - typeWidth));
    75 			updateColumnWidth(cd.getColumnNumber(), cd.getLabel().length() + typeWidth);
    76 
    77 			if (!cd.isFirstColumn()) {
    78 				printTableBorder("┬");
    79 			}
    80 			printTableBorder(repeat('─', getColumnWidth(cd.getColumnNumber()) + 2));
    81 		}
    82 		printTableBorder("╮");
    83 		out.println();
    84 
    85 		for (ColumnDescriptor cd : columnDescriptors) {
    86 			if (cd.isFirstColumn()) {
    87 				printTableIndent();
    88 				printTableBorder("│ ");
    89 			} else {
    90 				printTableBorder(" │ ");
    91 			}
    92 			out.print(TerminalStyle.Bright, cd.getLabel());
    93 			out.print(HEADER_TYPE_PREFIX);
    94 			out.print(cd.getTypeName());
    95 			out.print(HEADER_TYPE_SUFFIX);
    96 			if (cd.isLastColumn()) {
    97 				printTableBorder(" │");
    98 			}
    99 		}
   100 		out.println();
   101 
   102 		printTableIndent();
   103 		printTableBorder("├");
   104 		for (int i = 1; i <= header.getColumnCount(); i++) {
   105 			if (i > 1) {
   106 				printTableBorder("┼");
   107 			}
   108 			printTableBorder(repeat('─', getColumnWidth(i) + 2));
   109 		}
   110 		printTableBorder("┤");
   111 		out.println();
   112 
   113 		out.flush();
   114 	}
   115 
   116 	/**
   117 	 * Must be called before
   118 	 * {@linkplain #updateColumnWidth(int, int)}
   119 	 * and {@linkplain #getColumnWidth(int)}
   120 	 * for each result set.
   121 	 *
   122 	 * @param columnCount number of columns in current result set
   123 	 */
   124 	protected void initColumnWidths(int columnCount) {
   125 		if (columnWidth == null) {
   126 			columnWidth = new int[columnCount];
   127 		}
   128 	}
   129 
   130 	protected void cleanColumnWidths() {
   131 		columnWidth = null;
   132 	}
   133 
   134 	@Override
   135 	public void writeColumnValue(Object value) {
   136 		super.writeColumnValue(value);
   137 		writeColumnValueInternal(value);
   138 	}
   139 
   140 	protected void writeColumnValueInternal(Object value) {
   141 
   142 		if (isCurrentColumnFirst()) {
   143 			printTableIndent();
   144 			printTableBorder("│ ");
   145 		} else {
   146 			printTableBorder(" │ ");
   147 		}
   148 
   149 		String valueString = toString(value);
   150 		printValueWithNewLinesReplaced(valueString);
   151 
   152 		if (isCurrentColumnLast()) {
   153 			printTableBorder(" │");
   154 		}
   155 
   156 	}
   157 
   158 	protected int getColumnWidth(int columnNumber) {
   159 		return columnWidth[columnNumber - 1];
   160 	}
   161 
   162 	private void setColumnWidth(int columnNumber, int width) {
   163 		columnWidth[columnNumber - 1] = width;
   164 	}
   165 
   166 	protected void updateColumnWidth(int columnNumber, int width) {
   167 		int oldWidth = getColumnWidth(columnNumber);
   168 		setColumnWidth(columnNumber, Math.max(width, oldWidth));
   169 
   170 	}
   171 
   172 	protected String toString(Object value) {
   173 		final int width = getColumnWidth(getCurrentColumnsCount());
   174 		String result;
   175 		if (value instanceof Number || value instanceof Boolean) {
   176 			result = lpad(String.valueOf(value), width);
   177 		} else {
   178 			result = rpad(String.valueOf(value), width);
   179 		}
   180 		// ?	value = (boolean) value ? "✔" : "✗";
   181 
   182 		if (trimValues && result.length() > width) {
   183 			result = result.substring(0, width - 1) + "…";
   184 		}
   185 
   186 		return result;
   187 	}
   188 
   189 	@Override
   190 	public void writeEndRow() {
   191 		super.writeEndRow();
   192 		writeEndRowInternal();
   193 	}
   194 
   195 	public void writeEndRowInternal() {
   196 		out.println();
   197 		out.flush();
   198 	}
   199 
   200 	@Override
   201 	public void writeEndResultSet() {
   202 		int columnCount = getCurrentColumnsHeader().getColumnCount();
   203 		super.writeEndResultSet();
   204 
   205 		printTableIndent();
   206 		printTableBorder("╰");
   207 		for (int i = 1; i <= columnCount; i++) {
   208 			if (i > 1) {
   209 				printTableBorder("┴");
   210 			}
   211 			printTableBorder(repeat('─', getColumnWidth(i) + 2));
   212 		}
   213 		printTableBorder("╯");
   214 		out.println();
   215 
   216 		cleanColumnWidths();
   217 
   218 		out.print(TerminalColor.Yellow, "Record count: ");
   219 		out.println(getCurrentRowCount());
   220 		out.bell();
   221 		out.flush();
   222 	}
   223 
   224 	@Override
   225 	public void writeUpdatesResult(int updatedRowsCount) {
   226 		super.writeUpdatesResult(updatedRowsCount);
   227 		printResultSeparator();
   228 		out.print(TerminalColor.Red, "Updated records: ");
   229 		out.println(updatedRowsCount);
   230 		out.bell();
   231 		out.flush();
   232 	}
   233 
   234 	@Override
   235 	public void writeEndDatabase() {
   236 		super.writeEndDatabase();
   237 		out.flush();
   238 	}
   239 
   240 	private void printResultSeparator() {
   241 		if (firstResult) {
   242 			firstResult = false;
   243 		} else {
   244 			out.println();
   245 		}
   246 	}
   247 
   248 	protected void printTableBorder(String border) {
   249 		if (asciiNostalgia) {
   250 			border = border.replaceAll("─", "-");
   251 			border = border.replaceAll("│", "|");
   252 			border = border.replaceAll("[╭┬╮├┼┤╰┴╯]", "+");
   253 		}
   254 
   255 		out.print(TerminalColor.Green, border);
   256 	}
   257 
   258 	protected void printTableIndent() {
   259 		out.print(" ");
   260 	}
   261 
   262 	protected void printValueWithNewLinesReplaced(String valueString) {
   263 		String[] valueParts = valueString.split("\n");
   264 		for (int i = 0; i < valueParts.length; i++) {
   265 			String valuePart = valueParts[i];
   266 			// TODO: replace also TABs
   267 			out.print(TerminalColor.Cyan, valuePart);
   268 			if (i < valueParts.length - 1) {
   269 				out.print(TerminalColor.Red, "↲");
   270 			}
   271 		}
   272 	}
   273 }