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