tabular formatter: new option 'separateBy' to print horizontal separator on each change of given column
3 * Copyright © 2013 František Kučera (frantovo.cz)
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, version 3 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package info.globalcode.sql.dk;
19 import info.globalcode.sql.dk.configuration.CommandArgument;
20 import info.globalcode.sql.dk.configuration.Configuration;
21 import info.globalcode.sql.dk.configuration.ConfigurationException;
22 import info.globalcode.sql.dk.configuration.ConfigurationProvider;
23 import info.globalcode.sql.dk.configuration.DatabaseDefinition;
24 import info.globalcode.sql.dk.configuration.FormatterDefinition;
25 import info.globalcode.sql.dk.configuration.Properties;
26 import info.globalcode.sql.dk.configuration.Property;
27 import info.globalcode.sql.dk.configuration.PropertyDeclaration;
28 import info.globalcode.sql.dk.configuration.TunnelDefinition;
29 import info.globalcode.sql.dk.formatting.ColumnsHeader;
30 import info.globalcode.sql.dk.formatting.CommonProperties;
31 import info.globalcode.sql.dk.formatting.FakeSqlArray;
32 import info.globalcode.sql.dk.formatting.Formatter;
33 import info.globalcode.sql.dk.formatting.FormatterContext;
34 import info.globalcode.sql.dk.formatting.FormatterException;
35 import java.io.BufferedReader;
36 import java.io.ByteArrayOutputStream;
37 import java.io.InputStreamReader;
38 import java.io.PrintStream;
39 import java.sql.Array;
40 import java.sql.Driver;
41 import java.sql.DriverManager;
42 import java.sql.DriverPropertyInfo;
43 import java.sql.SQLException;
44 import java.util.ArrayList;
45 import java.util.Collections;
46 import java.util.Comparator;
47 import java.util.EnumSet;
48 import java.util.HashMap;
49 import java.util.HashSet;
50 import java.util.List;
52 import java.util.Map.Entry;
53 import java.util.ServiceLoader;
55 import java.util.concurrent.ExecutorService;
56 import java.util.concurrent.Executors;
57 import java.util.concurrent.TimeUnit;
58 import java.util.logging.Level;
59 import java.util.logging.LogRecord;
60 import java.util.logging.Logger;
61 import javax.sql.rowset.RowSetMetaDataImpl;
64 * Displays info like help, version etc.
66 * @author Ing. František Kučera (frantovo.cz)
68 public class InfoLister {
70 private static final Logger log = Logger.getLogger(InfoLister.class.getName());
72 * Fake database name for output formatting
74 public static final String CONFIG_DB_NAME = "sqldk_configuration";
75 private final PrintStream out;
76 private final ConfigurationProvider configurationProvider;
77 private final CLIOptions options;
78 private Formatter formatter;
80 public InfoLister(PrintStream out, ConfigurationProvider configurationProvider, CLIOptions options) {
82 this.configurationProvider = configurationProvider;
83 this.options = options;
86 public void showInfo() throws ConfigurationException, FormatterException {
87 EnumSet<InfoType> commands = options.getShowInfo();
89 boolean formattinNeeded = false;
91 for (InfoType infoType : commands) {
98 case FORMATTER_PROPERTIES:
100 case JAVA_PROPERTIES:
101 case ENVIRONMENT_VARIABLES:
102 formattinNeeded = true;
107 if (formattinNeeded) {
108 try (Formatter f = getFormatter()) {
110 formatter.writeStartBatch();
111 DatabaseDefinition dd = new DatabaseDefinition();
112 dd.setName(CONFIG_DB_NAME);
113 formatter.writeStartDatabase(dd);
115 formatter.writeEndDatabase();
116 formatter.writeEndBatch();
124 private void showInfos(EnumSet<InfoType> commands) throws ConfigurationException, FormatterException {
125 for (InfoType infoType : commands) {
126 infoType.showInfo(this);
130 private void listJavaProperties() throws FormatterException, ConfigurationException {
131 ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("value", SQLType.VARCHAR));
132 List<Object[]> data = new ArrayList<>();
133 for (Entry<Object, Object> e : System.getProperties().entrySet()) {
134 data.add(new Object[]{e.getKey(), e.getValue()});
136 printTable(formatter, header, "-- Java system properties", null, data, 0);
139 private void listEnvironmentVariables() throws FormatterException, ConfigurationException {
140 ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("value", SQLType.VARCHAR));
141 List<Object[]> data = new ArrayList<>();
142 for (Entry<String, String> e : System.getenv().entrySet()) {
143 data.add(new Object[]{e.getKey(), e.getValue()});
145 printTable(formatter, header, "-- environment variables", null, data, 0);
148 private void listFormatters() throws ConfigurationException, FormatterException {
149 ColumnsHeader header = constructHeader(
150 new HeaderField("name", SQLType.VARCHAR),
151 new HeaderField("built_in", SQLType.BOOLEAN),
152 new HeaderField("default", SQLType.BOOLEAN),
153 new HeaderField("class_name", SQLType.VARCHAR),
154 new HeaderField("valid", SQLType.BOOLEAN));
155 List<Object[]> data = new ArrayList<>();
157 String defaultFormatter = configurationProvider.getConfiguration().getDefaultFormatter();
158 defaultFormatter = defaultFormatter == null ? Configuration.DEFAULT_FORMATTER : defaultFormatter;
160 for (FormatterDefinition fd : configurationProvider.getConfiguration().getBuildInFormatters()) {
161 data.add(new Object[]{fd.getName(), true, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
164 for (FormatterDefinition fd : configurationProvider.getConfiguration().getFormatters()) {
165 data.add(new Object[]{fd.getName(), false, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
168 printTable(formatter, header, "-- configured and built-in output formatters", null, data);
171 private boolean isInstantiable(FormatterDefinition fd) {
173 try (ByteArrayOutputStream testStream = new ByteArrayOutputStream()) {
174 fd.getInstance(new FormatterContext(testStream, new Properties(0), null));
177 } catch (Exception e) {
178 log.log(Level.SEVERE, "Unable to create an instance of formatter: " + fd.getName(), e);
183 private void listFormatterProperties() throws FormatterException, ConfigurationException {
184 for (String formatterName : options.getFormatterNamesToListProperties()) {
185 listFormatterProperties(formatterName);
189 private void listFormatterProperties(String formatterName) throws FormatterException, ConfigurationException {
190 FormatterDefinition fd = configurationProvider.getConfiguration().getFormatter(formatterName);
193 // currently only for debugging purposes
194 // TODO: introduce --info-lister-property or generic filtering capability in printTable() ?
195 boolean printDeclaredIn = options.getFormatterProperties().getBoolean("InfoLister:print:declared_in", false);
197 List<HeaderField> headerFields = new ArrayList<>();
198 headerFields.add(new HeaderField("name", SQLType.VARCHAR));
199 headerFields.add(new HeaderField("type", SQLType.VARCHAR));
200 headerFields.add(new HeaderField("default", SQLType.VARCHAR));
201 headerFields.add(new HeaderField("description", SQLType.VARCHAR));
202 if (printDeclaredIn) {
203 headerFields.add(new HeaderField("declared_in", SQLType.VARCHAR));
206 ColumnsHeader header = constructHeader(headerFields.toArray(new HeaderField[0]));
208 Map<String, Object[]> data = new HashMap<>();
209 Class<Formatter> formatterClass = (Class<Formatter>) Class.forName(fd.getClassName());
210 List<Class<? extends Formatter>> hierarchy = Functions.getClassHierarchy(formatterClass, Formatter.class);
211 Collections.reverse(hierarchy);
212 hierarchy.stream().forEach((c) -> {
213 for (PropertyDeclaration p : Functions.getPropertyDeclarations(c)) {
214 data.put(p.name(), propertyDeclarationToRow(p, c, printDeclaredIn));
218 List<Parameter> parameters = new ArrayList<>();
219 parameters.add(new NamedParameter("formatter", formatterName, SQLType.VARCHAR));
221 printTable(formatter, header, "-- formatter properties", parameters, new ArrayList<>(data.values()));
222 } catch (ClassNotFoundException e) {
223 throw new ConfigurationException("Unable to find class " + fd.getClassName() + " of formatter" + fd.getName(), e);
227 private static Object[] propertyDeclarationToRow(PropertyDeclaration p, Class formatterClass, boolean printDeclaredIn) {
228 List list = new ArrayList();
231 list.add(CommonProperties.getSimpleTypeName(p.type()));
232 list.add(p.defaultValue());
233 list.add(p.description());
234 if (printDeclaredIn) {
235 list.add(formatterClass.getName());
238 return list.toArray();
241 private void listTypes() throws FormatterException, ConfigurationException {
242 ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("code", SQLType.INTEGER));
243 List<Object[]> data = new ArrayList<>();
244 for (SQLType sqlType : SQLType.values()) {
245 data.add(new Object[]{sqlType.name(), sqlType.getCode()});
247 printTable(formatter, header, "-- data types", null, data);
248 log.log(Level.INFO, "Type names in --types option are case insensitive");
251 private void listDatabases() throws ConfigurationException, FormatterException {
252 ColumnsHeader header = constructHeader(
253 new HeaderField("database_name", SQLType.VARCHAR),
254 new HeaderField("user_name", SQLType.VARCHAR),
255 new HeaderField("database_url", SQLType.VARCHAR));
256 List<Object[]> data = new ArrayList<>();
258 final List<DatabaseDefinition> configuredDatabases = configurationProvider.getConfiguration().getDatabases();
259 if (configuredDatabases.isEmpty()) {
260 log.log(Level.WARNING, "No databases are configured.");
262 for (DatabaseDefinition dd : configuredDatabases) {
263 data.add(new Object[]{dd.getName(), dd.getUserName(), dd.getUrl()});
265 final TunnelDefinition tunnel = dd.getTunnel();
266 if (tunnel != null) {
267 log.log(Level.INFO, "Tunnel command: {0}", tunnel.getCommand());
268 for (CommandArgument ca : Functions.notNull(tunnel.getArguments())) {
269 log.log(Level.INFO, "\targument: {0}/{1}", new Object[]{ca.getType(), ca.getValue()});
276 printTable(formatter, header, "-- configured databases", null, data);
279 private void listJdbcDrivers() throws FormatterException, ConfigurationException {
280 ColumnsHeader header = constructHeader(
281 new HeaderField("class", SQLType.VARCHAR),
282 new HeaderField("version", SQLType.VARCHAR),
283 new HeaderField("major", SQLType.INTEGER),
284 new HeaderField("minor", SQLType.INTEGER),
285 new HeaderField("jdbc_compliant", SQLType.BOOLEAN));
286 List<Object[]> data = new ArrayList<>();
288 final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
289 for (Driver d : drivers) {
290 data.add(new Object[]{
291 d.getClass().getName(),
292 d.getMajorVersion() + "." + d.getMinorVersion(),
299 printTable(formatter, header, "-- discovered JDBC drivers (available on the CLASSPATH)", null, data);
302 private void listJdbcProperties() throws FormatterException, ConfigurationException {
303 for (String dbName : options.getDatabaseNamesToListProperties()) {
304 ColumnsHeader header = constructHeader(
305 new HeaderField("property_name", SQLType.VARCHAR),
306 new HeaderField("required", SQLType.BOOLEAN),
307 new HeaderField("choices", SQLType.ARRAY),
308 new HeaderField("configured_value", SQLType.VARCHAR),
309 new HeaderField("description", SQLType.VARCHAR));
310 List<Object[]> data = new ArrayList<>();
312 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
314 Driver driver = findDriver(dd);
316 if (driver == null) {
317 log.log(Level.WARNING, "No JDBC driver was found for DB: {0} with URL: {1}", new Object[]{dd.getName(), dd.getUrl()});
319 log.log(Level.INFO, "For DB: {0} was found JDBC driver: {1}", new Object[]{dd.getName(), driver.getClass().getName()});
322 DriverPropertyInfo[] propertyInfos = driver.getPropertyInfo(dd.getUrl(), dd.getProperties().getJavaProperties());
324 Set<String> standardProperties = new HashSet<>();
326 for (DriverPropertyInfo pi : propertyInfos) {
327 Array choices = new FakeSqlArray(pi.choices, SQLType.VARCHAR);
328 data.add(new Object[]{
331 choices.getArray() == null ? "" : choices,
332 pi.value == null ? "" : pi.value,
335 standardProperties.add(pi.name);
338 for (Property p : dd.getProperties()) {
339 if (!standardProperties.contains(p.getName())) {
340 data.add(new Object[]{
347 log.log(Level.WARNING, "Your configuration contains property „{0}“ not declared by the JDBC driver.", p.getName());
351 } catch (SQLException e) {
352 log.log(Level.WARNING, "Error during getting property infos.", e);
355 List<Parameter> parameters = new ArrayList<>();
356 parameters.add(new NamedParameter("database", dbName, SQLType.VARCHAR));
357 parameters.add(new NamedParameter("driver_class", driver.getClass().getName(), SQLType.VARCHAR));
358 parameters.add(new NamedParameter("driver_major_version", driver.getMajorVersion(), SQLType.INTEGER));
359 parameters.add(new NamedParameter("driver_minor_version", driver.getMinorVersion(), SQLType.INTEGER));
361 printTable(formatter, header, "-- configured and configurable JDBC driver properties", parameters, data);
367 private Driver findDriver(DatabaseDefinition dd) {
368 final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
369 for (Driver d : drivers) {
371 if (d.acceptsURL(dd.getUrl())) {
374 } catch (SQLException e) {
375 log.log(Level.WARNING, "Error during finding JDBC driver for: " + dd.getName(), e);
382 * Parallelism for connection testing – maximum concurrent database connections.
384 private static final int TESTING_THREAD_COUNT = 64;
386 * Time limit for all connection testing threads – particular timeouts per connection will be
389 private static final long TESTING_AWAIT_LIMIT = 1;
390 private static final TimeUnit TESTING_AWAIT_UNIT = TimeUnit.DAYS;
392 private void testConnections() throws FormatterException, ConfigurationException {
393 ColumnsHeader header = constructHeader(
394 new HeaderField("database_name", SQLType.VARCHAR),
395 new HeaderField("configured", SQLType.BOOLEAN),
396 new HeaderField("connected", SQLType.BOOLEAN),
397 new HeaderField("product_name", SQLType.VARCHAR),
398 new HeaderField("product_version", SQLType.VARCHAR));
400 log.log(Level.FINE, "Testing DB connections in {0} threads", TESTING_THREAD_COUNT);
402 ExecutorService es = Executors.newFixedThreadPool(TESTING_THREAD_COUNT);
404 final Formatter currentFormatter = formatter;
406 printHeader(currentFormatter, header, "-- database configuration and connectivity test", null);
408 for (final String dbName : options.getDatabaseNamesToTest()) {
409 preloadDriver(dbName);
412 for (final String dbName : options.getDatabaseNamesToTest()) {
414 final Object[] row = testConnection(dbName);
415 synchronized (currentFormatter) {
416 printRow(currentFormatter, row);
425 log.log(Level.FINEST, "Waiting for test results: {0} {1}", new Object[]{TESTING_AWAIT_LIMIT, TESTING_AWAIT_UNIT.name()});
426 boolean finished = es.awaitTermination(TESTING_AWAIT_LIMIT, TESTING_AWAIT_UNIT);
428 log.log(Level.FINEST, "All testing threads finished in time limit.");
430 throw new FormatterException("Exceeded total time limit for test threads – this should never happen");
432 } catch (InterruptedException e) {
433 throw new FormatterException("Interrupted while waiting for test results", e);
436 printFooter(currentFormatter);
440 * JDBC driver classes should be preloaded in single thread to avoid deadlocks while doing
441 * {@linkplain DriverManager#registerDriver(java.sql.Driver)} during parallel connections.
445 private void preloadDriver(String dbName) {
447 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
448 Driver driver = findDriver(dd);
449 if (driver == null) {
450 log.log(Level.WARNING, "No Driver found for DB: {0}", dbName);
452 log.log(Level.FINEST, "Driver preloading for DB: {0} was successfull", dbName);
454 } catch (Exception e) {
455 LogRecord r = new LogRecord(Level.WARNING, "Failed to preload the Driver for DB: {0}");
456 r.setParameters(new Object[]{dbName});
462 private Object[] testConnection(String dbName) {
463 log.log(Level.FINE, "Testing connection to database: {0}", dbName);
465 boolean succesfullyConnected = false;
466 boolean succesfullyConfigured = false;
467 String productName = null;
468 String productVersion = null;
471 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
472 log.log(Level.FINE, "Database definition was loaded from configuration");
473 succesfullyConfigured = true;
474 try (DatabaseConnection dc = dd.connect(options.getDatabaseProperties())) {
475 succesfullyConnected = dc.test();
476 productName = dc.getProductName();
477 productVersion = dc.getProductVersion();
479 log.log(Level.FINE, "Database connection test was successful");
480 } catch (ConfigurationException | SQLException | RuntimeException e) {
481 log.log(Level.SEVERE, "Error during testing connection " + dbName, e);
484 return new Object[]{dbName, succesfullyConfigured, succesfullyConnected, productName, productVersion};
487 private void printResource(String fileName) {
488 try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(fileName)))) {
490 String line = reader.readLine();
497 } catch (Exception e) {
498 log.log(Level.SEVERE, "Unable to print this info. Please see our website for it: " + Constants.WEBSITE, e);
502 private void println(String line) {
506 private void printTable(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters, List<Object[]> data) throws ConfigurationException, FormatterException {
507 printTable(formatter, header, sql, parameters, data, null);
510 private void printTable(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters, List<Object[]> data, final Integer sortByColumn) throws ConfigurationException, FormatterException {
511 printHeader(formatter, header, sql, parameters);
513 if (sortByColumn != null) {
514 Collections.sort(data, new Comparator<Object[]>() {
517 public int compare(Object[] o1, Object[] o2) {
518 String s1 = String.valueOf(o1[sortByColumn]);
519 String s2 = String.valueOf(o2[sortByColumn]);
520 return s1.compareTo(s2);
525 for (Object[] row : data) {
526 printRow(formatter, row);
529 printFooter(formatter);
532 private void printHeader(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters) {
533 formatter.writeStartStatement();
535 formatter.writeQuery(sql);
536 if (parameters != null) {
537 formatter.writeParameters(parameters);
540 formatter.writeStartResultSet(header);
543 private void printRow(Formatter formatter, Object[] row) {
544 formatter.writeStartRow();
545 for (Object cell : row) {
546 formatter.writeColumnValue(cell);
548 formatter.writeEndRow();
551 private void printFooter(Formatter formatter) {
552 formatter.writeEndResultSet();
553 formatter.writeEndStatement();
556 private Formatter getFormatter() throws ConfigurationException, FormatterException {
557 String formatterName = options.getFormatterName();
558 formatterName = formatterName == null ? Configuration.DEFAULT_FORMATTER_PREFETCHING : formatterName;
559 FormatterDefinition fd = configurationProvider.getConfiguration().getFormatter(formatterName);
560 FormatterContext context = new FormatterContext(out, options.getFormatterProperties(), options.getRelationNames());
561 return fd.getInstance(context);
564 private ColumnsHeader constructHeader(HeaderField... fields) throws FormatterException {
566 RowSetMetaDataImpl metaData = new RowSetMetaDataImpl();
567 metaData.setColumnCount(fields.length);
569 for (int i = 0; i < fields.length; i++) {
570 HeaderField hf = fields[i];
571 int sqlIndex = i + 1;
572 metaData.setColumnName(sqlIndex, hf.name);
573 metaData.setColumnLabel(sqlIndex, hf.name);
574 metaData.setColumnType(sqlIndex, hf.type.getCode());
575 metaData.setColumnTypeName(sqlIndex, hf.type.name());
578 return new ColumnsHeader(metaData);
579 } catch (SQLException e) {
580 throw new FormatterException("Error while constructing table headers", e);
584 private static class HeaderField {
589 public HeaderField(String name, SQLType type) {
595 public enum InfoType {
599 public void showInfo(InfoLister infoLister) {
600 infoLister.printResource(Constants.HELP_FILE);
605 public void showInfo(InfoLister infoLister) {
606 infoLister.printResource(Constants.VERSION_FILE);
611 public void showInfo(InfoLister infoLister) {
612 infoLister.printResource(Constants.LICENSE_FILE);
617 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
618 infoLister.listJavaProperties();
621 ENVIRONMENT_VARIABLES {
623 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
624 infoLister.listEnvironmentVariables();
629 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
630 infoLister.listFormatters();
633 FORMATTER_PROPERTIES {
635 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
636 infoLister.listFormatterProperties();
641 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
642 infoLister.listTypes();
647 public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
648 infoLister.listJdbcDrivers();
653 public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
654 infoLister.listJdbcProperties();
659 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
660 infoLister.listDatabases();
665 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
666 infoLister.testConnections();
670 public abstract void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException;