support custom relation names in the XML formatter (added --relation CLI option)
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, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package info.globalcode.sql.dk;
20 import info.globalcode.sql.dk.configuration.CommandArgument;
21 import info.globalcode.sql.dk.configuration.Configuration;
22 import info.globalcode.sql.dk.configuration.ConfigurationException;
23 import info.globalcode.sql.dk.configuration.ConfigurationProvider;
24 import info.globalcode.sql.dk.configuration.DatabaseDefinition;
25 import info.globalcode.sql.dk.configuration.FormatterDefinition;
26 import info.globalcode.sql.dk.configuration.Properties;
27 import info.globalcode.sql.dk.configuration.Property;
28 import info.globalcode.sql.dk.configuration.PropertyDeclaration;
29 import info.globalcode.sql.dk.configuration.TunnelDefinition;
30 import info.globalcode.sql.dk.formatting.ColumnsHeader;
31 import info.globalcode.sql.dk.formatting.CommonProperties;
32 import info.globalcode.sql.dk.formatting.FakeSqlArray;
33 import info.globalcode.sql.dk.formatting.Formatter;
34 import info.globalcode.sql.dk.formatting.FormatterContext;
35 import info.globalcode.sql.dk.formatting.FormatterException;
36 import java.io.BufferedReader;
37 import java.io.ByteArrayOutputStream;
38 import java.io.InputStreamReader;
39 import java.io.PrintStream;
40 import java.sql.Array;
41 import java.sql.Driver;
42 import java.sql.DriverManager;
43 import java.sql.DriverPropertyInfo;
44 import java.sql.SQLException;
45 import java.util.ArrayList;
46 import java.util.Collections;
47 import java.util.Comparator;
48 import java.util.EnumSet;
49 import java.util.HashMap;
50 import java.util.HashSet;
51 import java.util.List;
53 import java.util.Map.Entry;
54 import java.util.ServiceLoader;
56 import java.util.concurrent.ExecutorService;
57 import java.util.concurrent.Executors;
58 import java.util.concurrent.TimeUnit;
59 import java.util.logging.Level;
60 import java.util.logging.LogRecord;
61 import java.util.logging.Logger;
62 import javax.sql.rowset.RowSetMetaDataImpl;
65 * Displays info like help, version etc.
67 * @author Ing. František Kučera (frantovo.cz)
69 public class InfoLister {
71 private static final Logger log = Logger.getLogger(InfoLister.class.getName());
73 * Fake database name for output formatting
75 public static final String CONFIG_DB_NAME = "sqldk_configuration";
76 private final PrintStream out;
77 private final ConfigurationProvider configurationProvider;
78 private final CLIOptions options;
79 private Formatter formatter;
81 public InfoLister(PrintStream out, ConfigurationProvider configurationProvider, CLIOptions options) {
83 this.configurationProvider = configurationProvider;
84 this.options = options;
87 public void showInfo() throws ConfigurationException, FormatterException {
88 EnumSet<InfoType> commands = options.getShowInfo();
90 boolean formattinNeeded = false;
92 for (InfoType infoType : commands) {
99 case FORMATTER_PROPERTIES:
101 case JAVA_PROPERTIES:
102 case ENVIRONMENT_VARIABLES:
103 formattinNeeded = true;
108 if (formattinNeeded) {
109 try (Formatter f = getFormatter()) {
111 formatter.writeStartBatch();
112 DatabaseDefinition dd = new DatabaseDefinition();
113 dd.setName(CONFIG_DB_NAME);
114 formatter.writeStartDatabase(dd);
116 formatter.writeEndDatabase();
117 formatter.writeEndBatch();
125 private void showInfos(EnumSet<InfoType> commands) throws ConfigurationException, FormatterException {
126 for (InfoType infoType : commands) {
127 infoType.showInfo(this);
131 private void listJavaProperties() throws FormatterException, ConfigurationException {
132 ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("value", SQLType.VARCHAR));
133 List<Object[]> data = new ArrayList<>();
134 for (Entry<Object, Object> e : System.getProperties().entrySet()) {
135 data.add(new Object[]{e.getKey(), e.getValue()});
137 printTable(formatter, header, "-- Java system properties", null, data, 0);
140 private void listEnvironmentVariables() throws FormatterException, ConfigurationException {
141 ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("value", SQLType.VARCHAR));
142 List<Object[]> data = new ArrayList<>();
143 for (Entry<String, String> e : System.getenv().entrySet()) {
144 data.add(new Object[]{e.getKey(), e.getValue()});
146 printTable(formatter, header, "-- environment variables", null, data, 0);
149 private void listFormatters() throws ConfigurationException, FormatterException {
150 ColumnsHeader header = constructHeader(
151 new HeaderField("name", SQLType.VARCHAR),
152 new HeaderField("built_in", SQLType.BOOLEAN),
153 new HeaderField("default", SQLType.BOOLEAN),
154 new HeaderField("class_name", SQLType.VARCHAR),
155 new HeaderField("valid", SQLType.BOOLEAN));
156 List<Object[]> data = new ArrayList<>();
158 String defaultFormatter = configurationProvider.getConfiguration().getDefaultFormatter();
159 defaultFormatter = defaultFormatter == null ? Configuration.DEFAULT_FORMATTER : defaultFormatter;
161 for (FormatterDefinition fd : configurationProvider.getConfiguration().getBuildInFormatters()) {
162 data.add(new Object[]{fd.getName(), true, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
165 for (FormatterDefinition fd : configurationProvider.getConfiguration().getFormatters()) {
166 data.add(new Object[]{fd.getName(), false, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
169 printTable(formatter, header, "-- configured and built-in output formatters", null, data);
172 private boolean isInstantiable(FormatterDefinition fd) {
174 try (ByteArrayOutputStream testStream = new ByteArrayOutputStream()) {
175 fd.getInstance(new FormatterContext(testStream, new Properties(0), null));
178 } catch (Exception e) {
179 log.log(Level.SEVERE, "Unable to create an instance of formatter: " + fd.getName(), e);
184 private void listFormatterProperties() throws FormatterException, ConfigurationException {
185 for (String formatterName : options.getFormatterNamesToListProperties()) {
186 listFormatterProperties(formatterName);
190 private void listFormatterProperties(String formatterName) throws FormatterException, ConfigurationException {
191 FormatterDefinition fd = configurationProvider.getConfiguration().getFormatter(formatterName);
194 // currently only for debugging purposes
195 // TODO: introduce --info-lister-property or generic filtering capability in printTable() ?
196 boolean printDeclaredIn = options.getFormatterProperties().getBoolean("InfoLister:print:declared_in", false);
198 List<HeaderField> headerFields = new ArrayList<>();
199 headerFields.add(new HeaderField("name", SQLType.VARCHAR));
200 headerFields.add(new HeaderField("type", SQLType.VARCHAR));
201 headerFields.add(new HeaderField("default", SQLType.VARCHAR));
202 headerFields.add(new HeaderField("description", SQLType.VARCHAR));
203 if (printDeclaredIn) {
204 headerFields.add(new HeaderField("declared_in", SQLType.VARCHAR));
207 ColumnsHeader header = constructHeader(headerFields.toArray(new HeaderField[0]));
209 Map<String, Object[]> data = new HashMap<>();
210 Class<Formatter> formatterClass = (Class<Formatter>) Class.forName(fd.getClassName());
211 List<Class<? extends Formatter>> hierarchy = Functions.getClassHierarchy(formatterClass, Formatter.class);
212 Collections.reverse(hierarchy);
213 hierarchy.stream().forEach((c) -> {
214 for (PropertyDeclaration p : Functions.getPropertyDeclarations(c)) {
215 data.put(p.name(), propertyDeclarationToRow(p, c, printDeclaredIn));
219 List<Parameter> parameters = new ArrayList<>();
220 parameters.add(new NamedParameter("formatter", formatterName, SQLType.VARCHAR));
222 printTable(formatter, header, "-- formatter properties", parameters, new ArrayList<>(data.values()));
223 } catch (ClassNotFoundException e) {
224 throw new ConfigurationException("Unable to find class " + fd.getClassName() + " of formatter" + fd.getName(), e);
228 private static Object[] propertyDeclarationToRow(PropertyDeclaration p, Class formatterClass, boolean printDeclaredIn) {
229 List list = new ArrayList();
232 list.add(CommonProperties.getSimpleTypeName(p.type()));
233 list.add(p.defaultValue());
234 list.add(p.description());
235 if (printDeclaredIn) {
236 list.add(formatterClass.getName());
239 return list.toArray();
242 private void listTypes() throws FormatterException, ConfigurationException {
243 ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("code", SQLType.INTEGER));
244 List<Object[]> data = new ArrayList<>();
245 for (SQLType sqlType : SQLType.values()) {
246 data.add(new Object[]{sqlType.name(), sqlType.getCode()});
248 printTable(formatter, header, "-- data types", null, data);
249 log.log(Level.INFO, "Type names in --types option are case insensitive");
252 private void listDatabases() throws ConfigurationException, FormatterException {
253 ColumnsHeader header = constructHeader(
254 new HeaderField("database_name", SQLType.VARCHAR),
255 new HeaderField("user_name", SQLType.VARCHAR),
256 new HeaderField("database_url", SQLType.VARCHAR));
257 List<Object[]> data = new ArrayList<>();
259 final List<DatabaseDefinition> configuredDatabases = configurationProvider.getConfiguration().getDatabases();
260 if (configuredDatabases.isEmpty()) {
261 log.log(Level.WARNING, "No databases are configured.");
263 for (DatabaseDefinition dd : configuredDatabases) {
264 data.add(new Object[]{dd.getName(), dd.getUserName(), dd.getUrl()});
266 final TunnelDefinition tunnel = dd.getTunnel();
267 if (tunnel != null) {
268 log.log(Level.INFO, "Tunnel command: {0}", tunnel.getCommand());
269 for (CommandArgument ca : Functions.notNull(tunnel.getArguments())) {
270 log.log(Level.INFO, "\targument: {0}/{1}", new Object[]{ca.getType(), ca.getValue()});
277 printTable(formatter, header, "-- configured databases", null, data);
280 private void listJdbcDrivers() throws FormatterException, ConfigurationException {
281 ColumnsHeader header = constructHeader(
282 new HeaderField("class", SQLType.VARCHAR),
283 new HeaderField("version", SQLType.VARCHAR),
284 new HeaderField("major", SQLType.INTEGER),
285 new HeaderField("minor", SQLType.INTEGER),
286 new HeaderField("jdbc_compliant", SQLType.BOOLEAN));
287 List<Object[]> data = new ArrayList<>();
289 final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
290 for (Driver d : drivers) {
291 data.add(new Object[]{
292 d.getClass().getName(),
293 d.getMajorVersion() + "." + d.getMinorVersion(),
300 printTable(formatter, header, "-- discovered JDBC drivers (available on the CLASSPATH)", null, data);
303 private void listJdbcProperties() throws FormatterException, ConfigurationException {
304 for (String dbName : options.getDatabaseNamesToListProperties()) {
305 ColumnsHeader header = constructHeader(
306 new HeaderField("property_name", SQLType.VARCHAR),
307 new HeaderField("required", SQLType.BOOLEAN),
308 new HeaderField("choices", SQLType.ARRAY),
309 new HeaderField("configured_value", SQLType.VARCHAR),
310 new HeaderField("description", SQLType.VARCHAR));
311 List<Object[]> data = new ArrayList<>();
313 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
315 Driver driver = findDriver(dd);
317 if (driver == null) {
318 log.log(Level.WARNING, "No JDBC driver was found for DB: {0} with URL: {1}", new Object[]{dd.getName(), dd.getUrl()});
320 log.log(Level.INFO, "For DB: {0} was found JDBC driver: {1}", new Object[]{dd.getName(), driver.getClass().getName()});
323 DriverPropertyInfo[] propertyInfos = driver.getPropertyInfo(dd.getUrl(), dd.getProperties().getJavaProperties());
325 Set<String> standardProperties = new HashSet<>();
327 for (DriverPropertyInfo pi : propertyInfos) {
328 Array choices = new FakeSqlArray(pi.choices, SQLType.VARCHAR);
329 data.add(new Object[]{
332 choices.getArray() == null ? "" : choices,
333 pi.value == null ? "" : pi.value,
336 standardProperties.add(pi.name);
339 for (Property p : dd.getProperties()) {
340 if (!standardProperties.contains(p.getName())) {
341 data.add(new Object[]{
348 log.log(Level.WARNING, "Your configuration contains property „{0}“ not declared by the JDBC driver.", p.getName());
352 } catch (SQLException e) {
353 log.log(Level.WARNING, "Error during getting property infos.", e);
356 List<Parameter> parameters = new ArrayList<>();
357 parameters.add(new NamedParameter("database", dbName, SQLType.VARCHAR));
358 parameters.add(new NamedParameter("driver_class", driver.getClass().getName(), SQLType.VARCHAR));
359 parameters.add(new NamedParameter("driver_major_version", driver.getMajorVersion(), SQLType.INTEGER));
360 parameters.add(new NamedParameter("driver_minor_version", driver.getMinorVersion(), SQLType.INTEGER));
362 printTable(formatter, header, "-- configured and configurable JDBC driver properties", parameters, data);
368 private Driver findDriver(DatabaseDefinition dd) {
369 final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
370 for (Driver d : drivers) {
372 if (d.acceptsURL(dd.getUrl())) {
375 } catch (SQLException e) {
376 log.log(Level.WARNING, "Error during finding JDBC driver for: " + dd.getName(), e);
383 * Parallelism for connection testing – maximum concurrent database connections.
385 private static final int TESTING_THREAD_COUNT = 64;
387 * Time limit for all connection testing threads – particular timeouts per connection will be
390 private static final long TESTING_AWAIT_LIMIT = 1;
391 private static final TimeUnit TESTING_AWAIT_UNIT = TimeUnit.DAYS;
393 private void testConnections() throws FormatterException, ConfigurationException {
394 ColumnsHeader header = constructHeader(
395 new HeaderField("database_name", SQLType.VARCHAR),
396 new HeaderField("configured", SQLType.BOOLEAN),
397 new HeaderField("connected", SQLType.BOOLEAN),
398 new HeaderField("product_name", SQLType.VARCHAR),
399 new HeaderField("product_version", SQLType.VARCHAR));
401 log.log(Level.FINE, "Testing DB connections in {0} threads", TESTING_THREAD_COUNT);
403 ExecutorService es = Executors.newFixedThreadPool(TESTING_THREAD_COUNT);
405 final Formatter currentFormatter = formatter;
407 printHeader(currentFormatter, header, "-- database configuration and connectivity test", null);
409 for (final String dbName : options.getDatabaseNamesToTest()) {
410 preloadDriver(dbName);
413 for (final String dbName : options.getDatabaseNamesToTest()) {
415 final Object[] row = testConnection(dbName);
416 synchronized (currentFormatter) {
417 printRow(currentFormatter, row);
426 log.log(Level.FINEST, "Waiting for test results: {0} {1}", new Object[]{TESTING_AWAIT_LIMIT, TESTING_AWAIT_UNIT.name()});
427 boolean finished = es.awaitTermination(TESTING_AWAIT_LIMIT, TESTING_AWAIT_UNIT);
429 log.log(Level.FINEST, "All testing threads finished in time limit.");
431 throw new FormatterException("Exceeded total time limit for test threads – this should never happen");
433 } catch (InterruptedException e) {
434 throw new FormatterException("Interrupted while waiting for test results", e);
437 printFooter(currentFormatter);
441 * JDBC driver classes should be preloaded in single thread to avoid deadlocks while doing
442 * {@linkplain DriverManager#registerDriver(java.sql.Driver)} during parallel connections.
446 private void preloadDriver(String dbName) {
448 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
449 Driver driver = findDriver(dd);
450 if (driver == null) {
451 log.log(Level.WARNING, "No Driver found for DB: {0}", dbName);
453 log.log(Level.FINEST, "Driver preloading for DB: {0} was successfull", dbName);
455 } catch (Exception e) {
456 LogRecord r = new LogRecord(Level.WARNING, "Failed to preload the Driver for DB: {0}");
457 r.setParameters(new Object[]{dbName});
463 private Object[] testConnection(String dbName) {
464 log.log(Level.FINE, "Testing connection to database: {0}", dbName);
466 boolean succesfullyConnected = false;
467 boolean succesfullyConfigured = false;
468 String productName = null;
469 String productVersion = null;
472 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
473 log.log(Level.FINE, "Database definition was loaded from configuration");
474 succesfullyConfigured = true;
475 try (DatabaseConnection dc = dd.connect(options.getDatabaseProperties())) {
476 succesfullyConnected = dc.test();
477 productName = dc.getProductName();
478 productVersion = dc.getProductVersion();
480 log.log(Level.FINE, "Database connection test was successful");
481 } catch (ConfigurationException | SQLException | RuntimeException e) {
482 log.log(Level.SEVERE, "Error during testing connection " + dbName, e);
485 return new Object[]{dbName, succesfullyConfigured, succesfullyConnected, productName, productVersion};
488 private void printResource(String fileName) {
489 try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(fileName)))) {
491 String line = reader.readLine();
498 } catch (Exception e) {
499 log.log(Level.SEVERE, "Unable to print this info. Please see our website for it: " + Constants.WEBSITE, e);
503 private void println(String line) {
507 private void printTable(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters, List<Object[]> data) throws ConfigurationException, FormatterException {
508 printTable(formatter, header, sql, parameters, data, null);
511 private void printTable(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters, List<Object[]> data, final Integer sortByColumn) throws ConfigurationException, FormatterException {
512 printHeader(formatter, header, sql, parameters);
514 if (sortByColumn != null) {
515 Collections.sort(data, new Comparator<Object[]>() {
518 public int compare(Object[] o1, Object[] o2) {
519 String s1 = String.valueOf(o1[sortByColumn]);
520 String s2 = String.valueOf(o2[sortByColumn]);
521 return s1.compareTo(s2);
526 for (Object[] row : data) {
527 printRow(formatter, row);
530 printFooter(formatter);
533 private void printHeader(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters) {
534 formatter.writeStartStatement();
536 formatter.writeQuery(sql);
537 if (parameters != null) {
538 formatter.writeParameters(parameters);
541 formatter.writeStartResultSet(header);
544 private void printRow(Formatter formatter, Object[] row) {
545 formatter.writeStartRow();
546 for (Object cell : row) {
547 formatter.writeColumnValue(cell);
549 formatter.writeEndRow();
552 private void printFooter(Formatter formatter) {
553 formatter.writeEndResultSet();
554 formatter.writeEndStatement();
557 private Formatter getFormatter() throws ConfigurationException, FormatterException {
558 String formatterName = options.getFormatterName();
559 formatterName = formatterName == null ? Configuration.DEFAULT_FORMATTER_PREFETCHING : formatterName;
560 FormatterDefinition fd = configurationProvider.getConfiguration().getFormatter(formatterName);
561 FormatterContext context = new FormatterContext(out, options.getFormatterProperties(), options.getRelationNames());
562 return fd.getInstance(context);
565 private ColumnsHeader constructHeader(HeaderField... fields) throws FormatterException {
567 RowSetMetaDataImpl metaData = new RowSetMetaDataImpl();
568 metaData.setColumnCount(fields.length);
570 for (int i = 0; i < fields.length; i++) {
571 HeaderField hf = fields[i];
572 int sqlIndex = i + 1;
573 metaData.setColumnName(sqlIndex, hf.name);
574 metaData.setColumnLabel(sqlIndex, hf.name);
575 metaData.setColumnType(sqlIndex, hf.type.getCode());
576 metaData.setColumnTypeName(sqlIndex, hf.type.name());
579 return new ColumnsHeader(metaData);
580 } catch (SQLException e) {
581 throw new FormatterException("Error while constructing table headers", e);
585 private static class HeaderField {
590 public HeaderField(String name, SQLType type) {
596 public enum InfoType {
600 public void showInfo(InfoLister infoLister) {
601 infoLister.printResource(Constants.HELP_FILE);
606 public void showInfo(InfoLister infoLister) {
607 infoLister.printResource(Constants.VERSION_FILE);
612 public void showInfo(InfoLister infoLister) {
613 infoLister.printResource(Constants.LICENSE_FILE);
618 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
619 infoLister.listJavaProperties();
622 ENVIRONMENT_VARIABLES {
624 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
625 infoLister.listEnvironmentVariables();
630 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
631 infoLister.listFormatters();
634 FORMATTER_PROPERTIES {
636 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
637 infoLister.listFormatterProperties();
642 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
643 infoLister.listTypes();
648 public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
649 infoLister.listJdbcDrivers();
654 public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
655 infoLister.listJdbcProperties();
660 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
661 infoLister.listDatabases();
666 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
667 infoLister.testConnections();
671 public abstract void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException;