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