java/sql-dk/src/info/globalcode/sql/dk/formatting/TabularFormatter.java
author František Kučera <franta-hg@frantovo.cz>
Sun, 01 Feb 2015 00:03:40 +0100
branchv_0
changeset 185 087d8ec75109
parent 170 8f142472270c
child 206 e2f24eea8543
permissions -rw-r--r--
Tabular formatter: fix problem with CR (carriage return).
Less command or orher programs shows it as ^M (two characters) and it breaks the table layout – so we need to translate it to a single symbol.
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@185
    30
 * <p>
franta-hg@185
    31
 * Prints human-readable output – tables of result sets and text messages with update counts.
franta-hg@185
    32
 * </p>
franta-hg@155
    33
 *
franta-hg@185
    34
 * <p>
franta-hg@185
    35
 * Longer values might break the table – overflow the cells – see alternative tabular formatters
franta-hg@185
    36
 * and the {@linkplain #PROPERTY_TRIM} property.
franta-hg@185
    37
 * </p>
franta-hg@32
    38
 *
franta-hg@32
    39
 * @author Ing. František Kučera (frantovo.cz)
franta-hg@155
    40
 * @see TabularPrefetchingFormatter
franta-hg@155
    41
 * @see TabularWrappingFormatter
franta-hg@32
    42
 */
franta-hg@32
    43
public class TabularFormatter extends AbstractFormatter {
franta-hg@32
    44
franta-hg@79
    45
	public static final String NAME = "tabular"; // bash-completion:formatter
franta-hg@39
    46
	private static final String HEADER_TYPE_PREFIX = " (";
franta-hg@39
    47
	private static final String HEADER_TYPE_SUFFIX = ")";
franta-hg@104
    48
	public static final String PROPERTY_ASCII = "ascii";
franta-hg@104
    49
	public static final String PROPERTY_COLORFUL = "color";
franta-hg@104
    50
	public static final String PROPERTY_TRIM = "trim";
franta-hg@170
    51
	private static final String NBSP = " ";
franta-hg@185
    52
	private static final Pattern whitespaceToReplace = Pattern.compile("\\n|\\r|\\t|" + NBSP);
franta-hg@123
    53
	protected ColorfulPrintWriter out;
franta-hg@37
    54
	private boolean firstResult = true;
franta-hg@39
    55
	private int[] columnWidth;
franta-hg@87
    56
	/**
franta-hg@87
    57
	 * use ASCII borders instead of unicode ones
franta-hg@87
    58
	 */
franta-hg@104
    59
	private final boolean asciiNostalgia;
franta-hg@87
    60
	/**
franta-hg@87
    61
	 * Trim values if they are longer than cell size
franta-hg@87
    62
	 */
franta-hg@104
    63
	private final boolean trimValues;
franta-hg@32
    64
franta-hg@32
    65
	public TabularFormatter(FormatterContext formatterContext) {
franta-hg@32
    66
		super(formatterContext);
franta-hg@34
    67
		out = new ColorfulPrintWriter(formatterContext.getOutputStream());
franta-hg@104
    68
		asciiNostalgia = formatterContext.getProperties().getBoolean(PROPERTY_ASCII, false);
franta-hg@104
    69
		trimValues = formatterContext.getProperties().getBoolean(PROPERTY_TRIM, false);
franta-hg@104
    70
		out.setColorful(formatterContext.getProperties().getBoolean(PROPERTY_COLORFUL, true));
franta-hg@34
    71
	}
franta-hg@34
    72
franta-hg@34
    73
	@Override
franta-hg@142
    74
	public void writeStartResultSet(ColumnsHeader header) {
franta-hg@142
    75
		super.writeStartResultSet(header);
franta-hg@37
    76
		printResultSeparator();
franta-hg@37
    77
franta-hg@88
    78
		initColumnWidths(header.getColumnCount());
franta-hg@39
    79
franta-hg@40
    80
		printTableIndent();
franta-hg@40
    81
		printTableBorder("╭");
franta-hg@88
    82
franta-hg@88
    83
		List<ColumnDescriptor> columnDescriptors = header.getColumnDescriptors();
franta-hg@88
    84
franta-hg@88
    85
		for (ColumnDescriptor cd : columnDescriptors) {
franta-hg@88
    86
			// padding: make header cell at least same width as data cells in this column
franta-hg@88
    87
			int typeWidth = cd.getTypeName().length() + HEADER_TYPE_PREFIX.length() + HEADER_TYPE_SUFFIX.length();
franta-hg@88
    88
			cd.setLabel(rpad(cd.getLabel(), getColumnWidth(cd.getColumnNumber()) - typeWidth));
franta-hg@88
    89
			updateColumnWidth(cd.getColumnNumber(), cd.getLabel().length() + typeWidth);
franta-hg@88
    90
franta-hg@40
    91
			if (!cd.isFirstColumn()) {
franta-hg@40
    92
				printTableBorder("┬");
franta-hg@40
    93
			}
franta-hg@40
    94
			printTableBorder(repeat('─', getColumnWidth(cd.getColumnNumber()) + 2));
franta-hg@40
    95
		}
franta-hg@40
    96
		printTableBorder("╮");
franta-hg@40
    97
		out.println();
franta-hg@40
    98
franta-hg@88
    99
		for (ColumnDescriptor cd : columnDescriptors) {
franta-hg@40
   100
			if (cd.isFirstColumn()) {
franta-hg@40
   101
				printTableIndent();
franta-hg@40
   102
				printTableBorder("│ ");
franta-hg@40
   103
			} else {
franta-hg@40
   104
				printTableBorder(" │ ");
franta-hg@40
   105
			}
franta-hg@37
   106
			out.print(TerminalStyle.Bright, cd.getLabel());
franta-hg@39
   107
			out.print(HEADER_TYPE_PREFIX);
franta-hg@37
   108
			out.print(cd.getTypeName());
franta-hg@39
   109
			out.print(HEADER_TYPE_SUFFIX);
franta-hg@40
   110
			if (cd.isLastColumn()) {
franta-hg@40
   111
				printTableBorder(" │");
franta-hg@37
   112
			}
franta-hg@37
   113
		}
franta-hg@37
   114
		out.println();
franta-hg@40
   115
franta-hg@40
   116
		printTableIndent();
franta-hg@40
   117
		printTableBorder("├");
franta-hg@40
   118
		for (int i = 1; i <= header.getColumnCount(); i++) {
franta-hg@40
   119
			if (i > 1) {
franta-hg@40
   120
				printTableBorder("┼");
franta-hg@40
   121
			}
franta-hg@40
   122
			printTableBorder(repeat('─', getColumnWidth(i) + 2));
franta-hg@40
   123
		}
franta-hg@40
   124
		printTableBorder("┤");
franta-hg@40
   125
		out.println();
franta-hg@40
   126
franta-hg@37
   127
		out.flush();
franta-hg@37
   128
	}
franta-hg@37
   129
franta-hg@88
   130
	/**
franta-hg@88
   131
	 * Must be called before
franta-hg@88
   132
	 * {@linkplain #updateColumnWidth(int, int)}
franta-hg@88
   133
	 * and {@linkplain #getColumnWidth(int)}
franta-hg@88
   134
	 * for each result set.
franta-hg@88
   135
	 *
franta-hg@88
   136
	 * @param columnCount number of columns in current result set
franta-hg@88
   137
	 */
franta-hg@88
   138
	protected void initColumnWidths(int columnCount) {
franta-hg@88
   139
		if (columnWidth == null) {
franta-hg@88
   140
			columnWidth = new int[columnCount];
franta-hg@88
   141
		}
franta-hg@88
   142
	}
franta-hg@88
   143
franta-hg@88
   144
	protected void cleanColumnWidths() {
franta-hg@88
   145
		columnWidth = null;
franta-hg@88
   146
	}
franta-hg@88
   147
franta-hg@37
   148
	@Override
franta-hg@34
   149
	public void writeColumnValue(Object value) {
franta-hg@34
   150
		super.writeColumnValue(value);
franta-hg@123
   151
		writeColumnValueInternal(value);
franta-hg@123
   152
	}
franta-hg@123
   153
franta-hg@123
   154
	protected void writeColumnValueInternal(Object value) {
franta-hg@34
   155
franta-hg@40
   156
		if (isCurrentColumnFirst()) {
franta-hg@40
   157
			printTableIndent();
franta-hg@40
   158
			printTableBorder("│ ");
franta-hg@40
   159
		} else {
franta-hg@90
   160
			printTableBorder(" │ ");
franta-hg@34
   161
		}
franta-hg@37
   162
franta-hg@123
   163
		String valueString = toString(value);
franta-hg@169
   164
		printValueWithWhitespaceReplaced(valueString);
franta-hg@40
   165
franta-hg@40
   166
		if (isCurrentColumnLast()) {
franta-hg@90
   167
			printTableBorder(" │");
franta-hg@40
   168
		}
franta-hg@40
   169
franta-hg@39
   170
	}
franta-hg@39
   171
franta-hg@123
   172
	protected int getColumnWidth(int columnNumber) {
franta-hg@39
   173
		return columnWidth[columnNumber - 1];
franta-hg@39
   174
	}
franta-hg@39
   175
franta-hg@39
   176
	private void setColumnWidth(int columnNumber, int width) {
franta-hg@39
   177
		columnWidth[columnNumber - 1] = width;
franta-hg@39
   178
	}
franta-hg@39
   179
franta-hg@88
   180
	protected void updateColumnWidth(int columnNumber, int width) {
franta-hg@39
   181
		int oldWidth = getColumnWidth(columnNumber);
franta-hg@39
   182
		setColumnWidth(columnNumber, Math.max(width, oldWidth));
franta-hg@39
   183
franta-hg@39
   184
	}
franta-hg@39
   185
franta-hg@39
   186
	protected String toString(Object value) {
franta-hg@39
   187
		final int width = getColumnWidth(getCurrentColumnsCount());
franta-hg@87
   188
		String result;
franta-hg@43
   189
		if (value instanceof Number || value instanceof Boolean) {
franta-hg@98
   190
			result = lpad(String.valueOf(value), width);
franta-hg@39
   191
		} else {
franta-hg@98
   192
			result = rpad(String.valueOf(value), width);
franta-hg@39
   193
		}
franta-hg@40
   194
		// ?	value = (boolean) value ? "✔" : "✗";
franta-hg@87
   195
franta-hg@87
   196
		if (trimValues && result.length() > width) {
franta-hg@87
   197
			result = result.substring(0, width - 1) + "…";
franta-hg@87
   198
		}
franta-hg@87
   199
franta-hg@87
   200
		return result;
franta-hg@34
   201
	}
franta-hg@34
   202
franta-hg@34
   203
	@Override
franta-hg@34
   204
	public void writeEndRow() {
franta-hg@34
   205
		super.writeEndRow();
franta-hg@123
   206
		writeEndRowInternal();
franta-hg@123
   207
	}
franta-hg@123
   208
franta-hg@123
   209
	public void writeEndRowInternal() {
franta-hg@34
   210
		out.println();
franta-hg@34
   211
		out.flush();
franta-hg@32
   212
	}
franta-hg@37
   213
franta-hg@37
   214
	@Override
franta-hg@37
   215
	public void writeEndResultSet() {
franta-hg@40
   216
		int columnCount = getCurrentColumnsHeader().getColumnCount();
franta-hg@37
   217
		super.writeEndResultSet();
franta-hg@40
   218
franta-hg@40
   219
		printTableIndent();
franta-hg@40
   220
		printTableBorder("╰");
franta-hg@40
   221
		for (int i = 1; i <= columnCount; i++) {
franta-hg@40
   222
			if (i > 1) {
franta-hg@40
   223
				printTableBorder("┴");
franta-hg@40
   224
			}
franta-hg@40
   225
			printTableBorder(repeat('─', getColumnWidth(i) + 2));
franta-hg@40
   226
		}
franta-hg@40
   227
		printTableBorder("╯");
franta-hg@40
   228
		out.println();
franta-hg@40
   229
franta-hg@88
   230
		cleanColumnWidths();
franta-hg@40
   231
franta-hg@37
   232
		out.print(TerminalColor.Yellow, "Record count: ");
franta-hg@37
   233
		out.println(getCurrentRowCount());
franta-hg@40
   234
		out.bell();
franta-hg@37
   235
		out.flush();
franta-hg@37
   236
	}
franta-hg@37
   237
franta-hg@37
   238
	@Override
franta-hg@142
   239
	public void writeUpdatesResult(int updatedRowsCount) {
franta-hg@142
   240
		super.writeUpdatesResult(updatedRowsCount);
franta-hg@37
   241
		printResultSeparator();
franta-hg@37
   242
		out.print(TerminalColor.Red, "Updated records: ");
franta-hg@37
   243
		out.println(updatedRowsCount);
franta-hg@40
   244
		out.bell();
franta-hg@37
   245
		out.flush();
franta-hg@37
   246
	}
franta-hg@37
   247
franta-hg@37
   248
	@Override
franta-hg@37
   249
	public void writeEndDatabase() {
franta-hg@37
   250
		super.writeEndDatabase();
franta-hg@37
   251
		out.flush();
franta-hg@37
   252
	}
franta-hg@37
   253
franta-hg@37
   254
	private void printResultSeparator() {
franta-hg@37
   255
		if (firstResult) {
franta-hg@37
   256
			firstResult = false;
franta-hg@37
   257
		} else {
franta-hg@37
   258
			out.println();
franta-hg@37
   259
		}
franta-hg@37
   260
	}
franta-hg@40
   261
franta-hg@123
   262
	protected void printTableBorder(String border) {
franta-hg@76
   263
		if (asciiNostalgia) {
franta-hg@76
   264
			border = border.replaceAll("─", "-");
franta-hg@76
   265
			border = border.replaceAll("│", "|");
franta-hg@76
   266
			border = border.replaceAll("[╭┬╮├┼┤╰┴╯]", "+");
franta-hg@76
   267
		}
franta-hg@87
   268
franta-hg@40
   269
		out.print(TerminalColor.Green, border);
franta-hg@40
   270
	}
franta-hg@40
   271
franta-hg@123
   272
	protected void printTableIndent() {
franta-hg@40
   273
		out.print(" ");
franta-hg@40
   274
	}
franta-hg@123
   275
franta-hg@169
   276
	protected void printValueWithWhitespaceReplaced(String valueString) {
franta-hg@169
   277
franta-hg@169
   278
		Matcher m = whitespaceToReplace.matcher(valueString);
franta-hg@169
   279
franta-hg@169
   280
		int start = 0;
franta-hg@169
   281
		while (m.find(start)) {
franta-hg@169
   282
franta-hg@169
   283
			out.print(TerminalColor.Cyan, valueString.substring(start, m.start()));
franta-hg@169
   284
franta-hg@169
   285
			switch (m.group()) {
franta-hg@169
   286
				case "\n":
franta-hg@169
   287
					out.print(TerminalColor.Red, "↲");
franta-hg@169
   288
					break;
franta-hg@185
   289
				case "\r":
franta-hg@185
   290
					out.print(TerminalColor.Red, "⏎");
franta-hg@185
   291
					break;
franta-hg@169
   292
				case "\t":
franta-hg@169
   293
					out.print(TerminalColor.Red, "↹");
franta-hg@169
   294
					break;
franta-hg@170
   295
				case NBSP:
franta-hg@170
   296
					out.print(TerminalColor.Red, "⎵");
franta-hg@170
   297
					break;
franta-hg@169
   298
				default:
franta-hg@169
   299
					throw new IllegalStateException("Unexpected whitespace token: „" + m.group() + "“");
franta-hg@123
   300
			}
franta-hg@169
   301
franta-hg@169
   302
			start = m.end();
franta-hg@123
   303
		}
franta-hg@167
   304
franta-hg@169
   305
		out.print(TerminalColor.Cyan, valueString.substring(start, valueString.length()));
franta-hg@123
   306
	}
franta-hg@32
   307
}