java/sql-dk/src/info/globalcode/sql/dk/formatting/TabularFormatter.java
author František Kučera <franta-hg@frantovo.cz>
Tue, 31 Dec 2013 17:35:33 +0100
branchv_0
changeset 104 245f1b88a3e6
parent 103 5410b6afc839
child 123 248a98c13ca4
permissions -rw-r--r--
formatter/database properties
     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 	private 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() {
    61 		super.writeStartResultSet();
    62 		printResultSeparator();
    63 	}
    64 
    65 	@Override
    66 	public void writeColumnsHeader(ColumnsHeader header) {
    67 		super.writeColumnsHeader(header);
    68 
    69 		initColumnWidths(header.getColumnCount());
    70 
    71 		printTableIndent();
    72 		printTableBorder("╭");
    73 
    74 		List<ColumnDescriptor> columnDescriptors = header.getColumnDescriptors();
    75 
    76 		for (ColumnDescriptor cd : columnDescriptors) {
    77 			// padding: make header cell at least same width as data cells in this column
    78 			int typeWidth = cd.getTypeName().length() + HEADER_TYPE_PREFIX.length() + HEADER_TYPE_SUFFIX.length();
    79 			cd.setLabel(rpad(cd.getLabel(), getColumnWidth(cd.getColumnNumber()) - typeWidth));
    80 			updateColumnWidth(cd.getColumnNumber(), cd.getLabel().length() + typeWidth);
    81 
    82 			if (!cd.isFirstColumn()) {
    83 				printTableBorder("┬");
    84 			}
    85 			printTableBorder(repeat('─', getColumnWidth(cd.getColumnNumber()) + 2));
    86 		}
    87 		printTableBorder("╮");
    88 		out.println();
    89 
    90 		for (ColumnDescriptor cd : columnDescriptors) {
    91 			if (cd.isFirstColumn()) {
    92 				printTableIndent();
    93 				printTableBorder("│ ");
    94 			} else {
    95 				printTableBorder(" │ ");
    96 			}
    97 			out.print(TerminalStyle.Bright, cd.getLabel());
    98 			out.print(HEADER_TYPE_PREFIX);
    99 			out.print(cd.getTypeName());
   100 			out.print(HEADER_TYPE_SUFFIX);
   101 			if (cd.isLastColumn()) {
   102 				printTableBorder(" │");
   103 			}
   104 		}
   105 		out.println();
   106 
   107 		printTableIndent();
   108 		printTableBorder("├");
   109 		for (int i = 1; i <= header.getColumnCount(); i++) {
   110 			if (i > 1) {
   111 				printTableBorder("┼");
   112 			}
   113 			printTableBorder(repeat('─', getColumnWidth(i) + 2));
   114 		}
   115 		printTableBorder("┤");
   116 		out.println();
   117 
   118 		out.flush();
   119 	}
   120 
   121 	/**
   122 	 * Must be called before
   123 	 * {@linkplain #updateColumnWidth(int, int)}
   124 	 * and {@linkplain #getColumnWidth(int)}
   125 	 * for each result set.
   126 	 *
   127 	 * @param columnCount number of columns in current result set
   128 	 */
   129 	protected void initColumnWidths(int columnCount) {
   130 		if (columnWidth == null) {
   131 			columnWidth = new int[columnCount];
   132 		}
   133 	}
   134 
   135 	protected void cleanColumnWidths() {
   136 		columnWidth = null;
   137 	}
   138 
   139 	@Override
   140 	public void writeColumnValue(Object value) {
   141 		super.writeColumnValue(value);
   142 
   143 		if (isCurrentColumnFirst()) {
   144 			printTableIndent();
   145 			printTableBorder("│ ");
   146 		} else {
   147 			printTableBorder(" │ ");
   148 		}
   149 
   150 		String[] valueParts = toString(value).split("\n");
   151 		for (int i = 0; i < valueParts.length; i++) {
   152 			String valuePart = valueParts[i];
   153 			out.print(TerminalColor.Cyan, valuePart);
   154 			if (i < valueParts.length - 1) {
   155 				out.print(TerminalColor.Red, "↲");
   156 			}
   157 		}
   158 
   159 		if (isCurrentColumnLast()) {
   160 			printTableBorder(" │");
   161 		}
   162 
   163 	}
   164 
   165 	private 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 		out.println();
   200 		out.flush();
   201 	}
   202 
   203 	@Override
   204 	public void writeEndResultSet() {
   205 		int columnCount = getCurrentColumnsHeader().getColumnCount();
   206 		super.writeEndResultSet();
   207 
   208 		printTableIndent();
   209 		printTableBorder("╰");
   210 		for (int i = 1; i <= columnCount; i++) {
   211 			if (i > 1) {
   212 				printTableBorder("┴");
   213 			}
   214 			printTableBorder(repeat('─', getColumnWidth(i) + 2));
   215 		}
   216 		printTableBorder("╯");
   217 		out.println();
   218 
   219 		cleanColumnWidths();
   220 
   221 		out.print(TerminalColor.Yellow, "Record count: ");
   222 		out.println(getCurrentRowCount());
   223 		out.bell();
   224 		out.flush();
   225 	}
   226 
   227 	@Override
   228 	public void writeStartUpdatesResult() {
   229 		super.writeStartUpdatesResult();
   230 		printResultSeparator();
   231 	}
   232 
   233 	@Override
   234 	public void writeUpdatedRowsCount(int updatedRowsCount) {
   235 		super.writeUpdatedRowsCount(updatedRowsCount);
   236 		out.print(TerminalColor.Red, "Updated records: ");
   237 		out.println(updatedRowsCount);
   238 		out.bell();
   239 		out.flush();
   240 	}
   241 
   242 	@Override
   243 	public void writeEndDatabase() {
   244 		super.writeEndDatabase();
   245 		out.flush();
   246 	}
   247 
   248 	private void printResultSeparator() {
   249 		if (firstResult) {
   250 			firstResult = false;
   251 		} else {
   252 			out.println();
   253 		}
   254 	}
   255 
   256 	private void printTableBorder(String border) {
   257 		if (asciiNostalgia) {
   258 			border = border.replaceAll("─", "-");
   259 			border = border.replaceAll("│", "|");
   260 			border = border.replaceAll("[╭┬╮├┼┤╰┴╯]", "+");
   261 		}
   262 
   263 		out.print(TerminalColor.Green, border);
   264 	}
   265 
   266 	private void printTableIndent() {
   267 		out.print(" ");
   268 	}
   269 }