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