java/sql-dk/src/info/globalcode/sql/dk/formatting/TabularFormatter.java
author František Kučera <franta-hg@frantovo.cz>
Mon, 20 Jan 2014 23:58:57 +0100
branchv_0
changeset 169 4e131a0b521a
parent 167 84aaa91642bf
child 170 8f142472270c
permissions -rw-r--r--
Tabular: replace also TABs with colored symbol (like newlines)
franta-hg@32
     1
/**
franta-hg@32
     2
 * SQL-DK
franta-hg@32
     3
 * Copyright © 2013 František Kučera (frantovo.cz)
franta-hg@32
     4
 *
franta-hg@32
     5
 * This program is free software: you can redistribute it and/or modify
franta-hg@32
     6
 * it under the terms of the GNU General Public License as published by
franta-hg@32
     7
 * the Free Software Foundation, either version 3 of the License, or
franta-hg@32
     8
 * (at your option) any later version.
franta-hg@32
     9
 *
franta-hg@32
    10
 * This program is distributed in the hope that it will be useful,
franta-hg@32
    11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
franta-hg@32
    12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
franta-hg@32
    13
 * GNU General Public License for more details.
franta-hg@32
    14
 *
franta-hg@32
    15
 * You should have received a copy of the GNU General Public License
franta-hg@32
    16
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
franta-hg@32
    17
 */
franta-hg@32
    18
package info.globalcode.sql.dk.formatting;
franta-hg@32
    19
franta-hg@34
    20
import info.globalcode.sql.dk.ColorfulPrintWriter;
franta-hg@37
    21
import static info.globalcode.sql.dk.ColorfulPrintWriter.*;
franta-hg@39
    22
import static info.globalcode.sql.dk.Functions.lpad;
franta-hg@39
    23
import static info.globalcode.sql.dk.Functions.rpad;
franta-hg@40
    24
import static info.globalcode.sql.dk.Functions.repeat;
franta-hg@88
    25
import java.util.List;
franta-hg@169
    26
import java.util.regex.Matcher;
franta-hg@169
    27
import java.util.regex.Pattern;
franta-hg@34
    28
franta-hg@32
    29
/**
franta-hg@155
    30
 * <p>Prints human-readable output – tables of result sets and text messages with update counts.</p>
franta-hg@155
    31
 *
franta-hg@155
    32
 * <p>Longer values might break the table – overflow the cells – see alternative tabular formatters
franta-hg@155
    33
 * and the {@linkplain #PROPERTY_TRIM} property.</p>
franta-hg@32
    34
 *
franta-hg@32
    35
 * @author Ing. František Kučera (frantovo.cz)
franta-hg@155
    36
 * @see TabularPrefetchingFormatter
franta-hg@155
    37
 * @see TabularWrappingFormatter
franta-hg@32
    38
 */
franta-hg@32
    39
public class TabularFormatter extends AbstractFormatter {
franta-hg@32
    40
franta-hg@79
    41
	public static final String NAME = "tabular"; // bash-completion:formatter
franta-hg@39
    42
	private static final String HEADER_TYPE_PREFIX = " (";
franta-hg@39
    43
	private static final String HEADER_TYPE_SUFFIX = ")";
franta-hg@104
    44
	public static final String PROPERTY_ASCII = "ascii";
franta-hg@104
    45
	public static final String PROPERTY_COLORFUL = "color";
franta-hg@104
    46
	public static final String PROPERTY_TRIM = "trim";
franta-hg@169
    47
	private static final Pattern whitespaceToReplace = Pattern.compile("\\n|\\t");
franta-hg@123
    48
	protected ColorfulPrintWriter out;
franta-hg@37
    49
	private boolean firstResult = true;
franta-hg@39
    50
	private int[] columnWidth;
franta-hg@87
    51
	/**
franta-hg@87
    52
	 * use ASCII borders instead of unicode ones
franta-hg@87
    53
	 */
franta-hg@104
    54
	private final boolean asciiNostalgia;
franta-hg@87
    55
	/**
franta-hg@87
    56
	 * Trim values if they are longer than cell size
franta-hg@87
    57
	 */
franta-hg@104
    58
	private final boolean trimValues;
franta-hg@32
    59
franta-hg@32
    60
	public TabularFormatter(FormatterContext formatterContext) {
franta-hg@32
    61
		super(formatterContext);
franta-hg@34
    62
		out = new ColorfulPrintWriter(formatterContext.getOutputStream());
franta-hg@104
    63
		asciiNostalgia = formatterContext.getProperties().getBoolean(PROPERTY_ASCII, false);
franta-hg@104
    64
		trimValues = formatterContext.getProperties().getBoolean(PROPERTY_TRIM, false);
franta-hg@104
    65
		out.setColorful(formatterContext.getProperties().getBoolean(PROPERTY_COLORFUL, true));
franta-hg@34
    66
	}
franta-hg@34
    67
franta-hg@34
    68
	@Override
franta-hg@142
    69
	public void writeStartResultSet(ColumnsHeader header) {
franta-hg@142
    70
		super.writeStartResultSet(header);
franta-hg@37
    71
		printResultSeparator();
franta-hg@37
    72
franta-hg@88
    73
		initColumnWidths(header.getColumnCount());
franta-hg@39
    74
franta-hg@40
    75
		printTableIndent();
franta-hg@40
    76
		printTableBorder("╭");
franta-hg@88
    77
franta-hg@88
    78
		List<ColumnDescriptor> columnDescriptors = header.getColumnDescriptors();
franta-hg@88
    79
franta-hg@88
    80
		for (ColumnDescriptor cd : columnDescriptors) {
franta-hg@88
    81
			// padding: make header cell at least same width as data cells in this column
franta-hg@88
    82
			int typeWidth = cd.getTypeName().length() + HEADER_TYPE_PREFIX.length() + HEADER_TYPE_SUFFIX.length();
franta-hg@88
    83
			cd.setLabel(rpad(cd.getLabel(), getColumnWidth(cd.getColumnNumber()) - typeWidth));
franta-hg@88
    84
			updateColumnWidth(cd.getColumnNumber(), cd.getLabel().length() + typeWidth);
franta-hg@88
    85
franta-hg@40
    86
			if (!cd.isFirstColumn()) {
franta-hg@40
    87
				printTableBorder("┬");
franta-hg@40
    88
			}
franta-hg@40
    89
			printTableBorder(repeat('─', getColumnWidth(cd.getColumnNumber()) + 2));
franta-hg@40
    90
		}
franta-hg@40
    91
		printTableBorder("╮");
franta-hg@40
    92
		out.println();
franta-hg@40
    93
franta-hg@88
    94
		for (ColumnDescriptor cd : columnDescriptors) {
franta-hg@40
    95
			if (cd.isFirstColumn()) {
franta-hg@40
    96
				printTableIndent();
franta-hg@40
    97
				printTableBorder("│ ");
franta-hg@40
    98
			} else {
franta-hg@40
    99
				printTableBorder(" │ ");
franta-hg@40
   100
			}
franta-hg@37
   101
			out.print(TerminalStyle.Bright, cd.getLabel());
franta-hg@39
   102
			out.print(HEADER_TYPE_PREFIX);
franta-hg@37
   103
			out.print(cd.getTypeName());
franta-hg@39
   104
			out.print(HEADER_TYPE_SUFFIX);
franta-hg@40
   105
			if (cd.isLastColumn()) {
franta-hg@40
   106
				printTableBorder(" │");
franta-hg@37
   107
			}
franta-hg@37
   108
		}
franta-hg@37
   109
		out.println();
franta-hg@40
   110
franta-hg@40
   111
		printTableIndent();
franta-hg@40
   112
		printTableBorder("├");
franta-hg@40
   113
		for (int i = 1; i <= header.getColumnCount(); i++) {
franta-hg@40
   114
			if (i > 1) {
franta-hg@40
   115
				printTableBorder("┼");
franta-hg@40
   116
			}
franta-hg@40
   117
			printTableBorder(repeat('─', getColumnWidth(i) + 2));
franta-hg@40
   118
		}
franta-hg@40
   119
		printTableBorder("┤");
franta-hg@40
   120
		out.println();
franta-hg@40
   121
franta-hg@37
   122
		out.flush();
franta-hg@37
   123
	}
franta-hg@37
   124
franta-hg@88
   125
	/**
franta-hg@88
   126
	 * Must be called before
franta-hg@88
   127
	 * {@linkplain #updateColumnWidth(int, int)}
franta-hg@88
   128
	 * and {@linkplain #getColumnWidth(int)}
franta-hg@88
   129
	 * for each result set.
franta-hg@88
   130
	 *
franta-hg@88
   131
	 * @param columnCount number of columns in current result set
franta-hg@88
   132
	 */
franta-hg@88
   133
	protected void initColumnWidths(int columnCount) {
franta-hg@88
   134
		if (columnWidth == null) {
franta-hg@88
   135
			columnWidth = new int[columnCount];
franta-hg@88
   136
		}
franta-hg@88
   137
	}
franta-hg@88
   138
franta-hg@88
   139
	protected void cleanColumnWidths() {
franta-hg@88
   140
		columnWidth = null;
franta-hg@88
   141
	}
franta-hg@88
   142
franta-hg@37
   143
	@Override
franta-hg@34
   144
	public void writeColumnValue(Object value) {
franta-hg@34
   145
		super.writeColumnValue(value);
franta-hg@123
   146
		writeColumnValueInternal(value);
franta-hg@123
   147
	}
franta-hg@123
   148
franta-hg@123
   149
	protected void writeColumnValueInternal(Object value) {
franta-hg@34
   150
franta-hg@40
   151
		if (isCurrentColumnFirst()) {
franta-hg@40
   152
			printTableIndent();
franta-hg@40
   153
			printTableBorder("│ ");
franta-hg@40
   154
		} else {
franta-hg@90
   155
			printTableBorder(" │ ");
franta-hg@34
   156
		}
franta-hg@37
   157
franta-hg@123
   158
		String valueString = toString(value);
franta-hg@169
   159
		printValueWithWhitespaceReplaced(valueString);
franta-hg@40
   160
franta-hg@40
   161
		if (isCurrentColumnLast()) {
franta-hg@90
   162
			printTableBorder(" │");
franta-hg@40
   163
		}
franta-hg@40
   164
franta-hg@39
   165
	}
franta-hg@39
   166
franta-hg@123
   167
	protected int getColumnWidth(int columnNumber) {
franta-hg@39
   168
		return columnWidth[columnNumber - 1];
franta-hg@39
   169
	}
franta-hg@39
   170
franta-hg@39
   171
	private void setColumnWidth(int columnNumber, int width) {
franta-hg@39
   172
		columnWidth[columnNumber - 1] = width;
franta-hg@39
   173
	}
franta-hg@39
   174
franta-hg@88
   175
	protected void updateColumnWidth(int columnNumber, int width) {
franta-hg@39
   176
		int oldWidth = getColumnWidth(columnNumber);
franta-hg@39
   177
		setColumnWidth(columnNumber, Math.max(width, oldWidth));
franta-hg@39
   178
franta-hg@39
   179
	}
franta-hg@39
   180
franta-hg@39
   181
	protected String toString(Object value) {
franta-hg@39
   182
		final int width = getColumnWidth(getCurrentColumnsCount());
franta-hg@87
   183
		String result;
franta-hg@43
   184
		if (value instanceof Number || value instanceof Boolean) {
franta-hg@98
   185
			result = lpad(String.valueOf(value), width);
franta-hg@39
   186
		} else {
franta-hg@98
   187
			result = rpad(String.valueOf(value), width);
franta-hg@39
   188
		}
franta-hg@40
   189
		// ?	value = (boolean) value ? "✔" : "✗";
franta-hg@87
   190
franta-hg@87
   191
		if (trimValues && result.length() > width) {
franta-hg@87
   192
			result = result.substring(0, width - 1) + "…";
franta-hg@87
   193
		}
franta-hg@87
   194
franta-hg@87
   195
		return result;
franta-hg@34
   196
	}
franta-hg@34
   197
franta-hg@34
   198
	@Override
franta-hg@34
   199
	public void writeEndRow() {
franta-hg@34
   200
		super.writeEndRow();
franta-hg@123
   201
		writeEndRowInternal();
franta-hg@123
   202
	}
franta-hg@123
   203
franta-hg@123
   204
	public void writeEndRowInternal() {
franta-hg@34
   205
		out.println();
franta-hg@34
   206
		out.flush();
franta-hg@32
   207
	}
franta-hg@37
   208
franta-hg@37
   209
	@Override
franta-hg@37
   210
	public void writeEndResultSet() {
franta-hg@40
   211
		int columnCount = getCurrentColumnsHeader().getColumnCount();
franta-hg@37
   212
		super.writeEndResultSet();
franta-hg@40
   213
franta-hg@40
   214
		printTableIndent();
franta-hg@40
   215
		printTableBorder("╰");
franta-hg@40
   216
		for (int i = 1; i <= columnCount; i++) {
franta-hg@40
   217
			if (i > 1) {
franta-hg@40
   218
				printTableBorder("┴");
franta-hg@40
   219
			}
franta-hg@40
   220
			printTableBorder(repeat('─', getColumnWidth(i) + 2));
franta-hg@40
   221
		}
franta-hg@40
   222
		printTableBorder("╯");
franta-hg@40
   223
		out.println();
franta-hg@40
   224
franta-hg@88
   225
		cleanColumnWidths();
franta-hg@40
   226
franta-hg@37
   227
		out.print(TerminalColor.Yellow, "Record count: ");
franta-hg@37
   228
		out.println(getCurrentRowCount());
franta-hg@40
   229
		out.bell();
franta-hg@37
   230
		out.flush();
franta-hg@37
   231
	}
franta-hg@37
   232
franta-hg@37
   233
	@Override
franta-hg@142
   234
	public void writeUpdatesResult(int updatedRowsCount) {
franta-hg@142
   235
		super.writeUpdatesResult(updatedRowsCount);
franta-hg@37
   236
		printResultSeparator();
franta-hg@37
   237
		out.print(TerminalColor.Red, "Updated records: ");
franta-hg@37
   238
		out.println(updatedRowsCount);
franta-hg@40
   239
		out.bell();
franta-hg@37
   240
		out.flush();
franta-hg@37
   241
	}
franta-hg@37
   242
franta-hg@37
   243
	@Override
franta-hg@37
   244
	public void writeEndDatabase() {
franta-hg@37
   245
		super.writeEndDatabase();
franta-hg@37
   246
		out.flush();
franta-hg@37
   247
	}
franta-hg@37
   248
franta-hg@37
   249
	private void printResultSeparator() {
franta-hg@37
   250
		if (firstResult) {
franta-hg@37
   251
			firstResult = false;
franta-hg@37
   252
		} else {
franta-hg@37
   253
			out.println();
franta-hg@37
   254
		}
franta-hg@37
   255
	}
franta-hg@40
   256
franta-hg@123
   257
	protected void printTableBorder(String border) {
franta-hg@76
   258
		if (asciiNostalgia) {
franta-hg@76
   259
			border = border.replaceAll("─", "-");
franta-hg@76
   260
			border = border.replaceAll("│", "|");
franta-hg@76
   261
			border = border.replaceAll("[╭┬╮├┼┤╰┴╯]", "+");
franta-hg@76
   262
		}
franta-hg@87
   263
franta-hg@40
   264
		out.print(TerminalColor.Green, border);
franta-hg@40
   265
	}
franta-hg@40
   266
franta-hg@123
   267
	protected void printTableIndent() {
franta-hg@40
   268
		out.print(" ");
franta-hg@40
   269
	}
franta-hg@123
   270
franta-hg@169
   271
	protected void printValueWithWhitespaceReplaced(String valueString) {
franta-hg@169
   272
franta-hg@169
   273
		Matcher m = whitespaceToReplace.matcher(valueString);
franta-hg@169
   274
franta-hg@169
   275
		int start = 0;
franta-hg@169
   276
		while (m.find(start)) {
franta-hg@169
   277
franta-hg@169
   278
			out.print(TerminalColor.Cyan, valueString.substring(start, m.start()));
franta-hg@169
   279
franta-hg@169
   280
			switch (m.group()) {
franta-hg@169
   281
				case "\n":
franta-hg@169
   282
					out.print(TerminalColor.Red, "↲");
franta-hg@169
   283
					break;
franta-hg@169
   284
				case "\t":
franta-hg@169
   285
					out.print(TerminalColor.Red, "↹");
franta-hg@169
   286
					break;
franta-hg@169
   287
				default:
franta-hg@169
   288
					throw new IllegalStateException("Unexpected whitespace token: „" + m.group() + "“");
franta-hg@123
   289
			}
franta-hg@169
   290
franta-hg@169
   291
			start = m.end();
franta-hg@123
   292
		}
franta-hg@167
   293
franta-hg@169
   294
		out.print(TerminalColor.Cyan, valueString.substring(start, valueString.length()));
franta-hg@123
   295
	}
franta-hg@32
   296
}