java/sql-dk/src/info/globalcode/sql/dk/formatting/TabularFormatter.java
author František Kučera <franta-hg@frantovo.cz>
Sat, 28 Dec 2013 12:19:39 +0100
branchv_0
changeset 88 102ba0fcb07f
parent 87 03bf24449c7a
child 89 98d18e9a357b
permissions -rw-r--r--
TabularPrefetchingFormatter: prefetch whole result set to avoid value overflow the cell
     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.Arrays;
    26 import java.util.List;
    27 
    28 /**
    29  *
    30  * @author Ing. František Kučera (frantovo.cz)
    31  */
    32 public class TabularFormatter extends AbstractFormatter {
    33 
    34 	public static final String NAME = "tabular"; // bash-completion:formatter
    35 	private static final String HEADER_TYPE_PREFIX = " (";
    36 	private static final String HEADER_TYPE_SUFFIX = ")";
    37 	private ColorfulPrintWriter out;
    38 	private boolean firstResult = true;
    39 	private int[] columnWidth;
    40 	/**
    41 	 * use ASCII borders instead of unicode ones
    42 	 */
    43 	private final boolean asciiNostalgia = false;
    44 	/**
    45 	 * Trim values if they are longer than cell size
    46 	 */
    47 	private final boolean trimValues = false;
    48 
    49 	public TabularFormatter(FormatterContext formatterContext) {
    50 		super(formatterContext);
    51 		out = new ColorfulPrintWriter(formatterContext.getOutputStream());
    52 	}
    53 
    54 	@Override
    55 	public void writeStartResultSet() {
    56 		super.writeStartResultSet();
    57 		printResultSeparator();
    58 	}
    59 
    60 	@Override
    61 	public void writeColumnsHeader(ColumnsHeader header) {
    62 		super.writeColumnsHeader(header);
    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 
   138 		if (isCurrentColumnFirst()) {
   139 			printTableIndent();
   140 			printTableBorder("│ ");
   141 		} else {
   142 			printTableBorder(" │ ");
   143 		}
   144 
   145 		out.print(TerminalColor.Cyan, toString(value));
   146 
   147 		if (isCurrentColumnLast()) {
   148 			printTableBorder(" │");
   149 		}
   150 
   151 	}
   152 
   153 	private int getColumnWidth(int columnNumber) {
   154 		return columnWidth[columnNumber - 1];
   155 	}
   156 
   157 	private void setColumnWidth(int columnNumber, int width) {
   158 		columnWidth[columnNumber - 1] = width;
   159 	}
   160 
   161 	protected void updateColumnWidth(int columnNumber, int width) {
   162 		int oldWidth = getColumnWidth(columnNumber);
   163 		setColumnWidth(columnNumber, Math.max(width, oldWidth));
   164 
   165 	}
   166 
   167 	@Override
   168 	protected String toString(Object value) {
   169 		final int width = getColumnWidth(getCurrentColumnsCount());
   170 		String result;
   171 		if (value instanceof Number || value instanceof Boolean) {
   172 			result = lpad(super.toString(value), width);
   173 		} else {
   174 			result = rpad(super.toString(value), width);
   175 		}
   176 		// ?	value = (boolean) value ? "✔" : "✗";
   177 
   178 		if (trimValues && result.length() > width) {
   179 			result = result.substring(0, width - 1) + "…";
   180 		}
   181 
   182 		return result;
   183 	}
   184 
   185 	@Override
   186 	public void writeEndRow() {
   187 		super.writeEndRow();
   188 		out.println();
   189 		out.flush();
   190 	}
   191 
   192 	@Override
   193 	public void writeEndResultSet() {
   194 		int columnCount = getCurrentColumnsHeader().getColumnCount();
   195 		super.writeEndResultSet();
   196 
   197 		printTableIndent();
   198 		printTableBorder("╰");
   199 		for (int i = 1; i <= columnCount; i++) {
   200 			if (i > 1) {
   201 				printTableBorder("┴");
   202 			}
   203 			printTableBorder(repeat('─', getColumnWidth(i) + 2));
   204 		}
   205 		printTableBorder("╯");
   206 		out.println();
   207 
   208 		cleanColumnWidths();
   209 
   210 		out.print(TerminalColor.Yellow, "Record count: ");
   211 		out.println(getCurrentRowCount());
   212 		out.bell();
   213 		out.flush();
   214 	}
   215 
   216 	@Override
   217 	public void writeStartUpdatesResult() {
   218 		super.writeStartUpdatesResult();
   219 		printResultSeparator();
   220 	}
   221 
   222 	@Override
   223 	public void writeUpdatedRowsCount(int updatedRowsCount) {
   224 		super.writeUpdatedRowsCount(updatedRowsCount);
   225 		out.print(TerminalColor.Red, "Updated records: ");
   226 		out.println(updatedRowsCount);
   227 		out.bell();
   228 		out.flush();
   229 	}
   230 
   231 	@Override
   232 	public void writeEndDatabase() {
   233 		super.writeEndDatabase();
   234 		out.flush();
   235 	}
   236 
   237 	private void printResultSeparator() {
   238 		if (firstResult) {
   239 			firstResult = false;
   240 		} else {
   241 			out.println();
   242 		}
   243 	}
   244 
   245 	private void printTableBorder(String border) {
   246 		if (asciiNostalgia) {
   247 			border = border.replaceAll("─", "-");
   248 			border = border.replaceAll("│", "|");
   249 			border = border.replaceAll("[╭┬╮├┼┤╰┴╯]", "+");
   250 		}
   251 
   252 		out.print(TerminalColor.Green, border);
   253 	}
   254 
   255 	private void printTableIndent() {
   256 		out.print(" ");
   257 	}
   258 }