java/sql-dk/src/main/java/info/globalcode/sql/dk/InfoLister.java
author František Kučera <franta-hg@frantovo.cz>
Thu, 24 Oct 2019 21:43:08 +0200
branchv_0
changeset 250 aae5009bd0af
parent 246 277c18b48762
permissions -rw-r--r--
fix license version: GNU GPLv3
     1 /**
     2  * SQL-DK
     3  * Copyright © 2013 František Kučera (frantovo.cz)
     4  *
     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.
     8  *
     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.
    13  *
    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/>.
    16  */
    17 package info.globalcode.sql.dk;
    18 
    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;
    51 import java.util.Map;
    52 import java.util.Map.Entry;
    53 import java.util.ServiceLoader;
    54 import java.util.Set;
    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;
    62 
    63 /**
    64  * Displays info like help, version etc.
    65  *
    66  * @author Ing. František Kučera (frantovo.cz)
    67  */
    68 public class InfoLister {
    69 
    70 	private static final Logger log = Logger.getLogger(InfoLister.class.getName());
    71 	/**
    72 	 * Fake database name for output formatting
    73 	 */
    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;
    79 
    80 	public InfoLister(PrintStream out, ConfigurationProvider configurationProvider, CLIOptions options) {
    81 		this.out = out;
    82 		this.configurationProvider = configurationProvider;
    83 		this.options = options;
    84 	}
    85 
    86 	public void showInfo() throws ConfigurationException, FormatterException {
    87 		EnumSet<InfoType> commands = options.getShowInfo();
    88 
    89 		boolean formattinNeeded = false;
    90 
    91 		for (InfoType infoType : commands) {
    92 			switch (infoType) {
    93 				case CONNECTION:
    94 				case JDBC_DRIVERS:
    95 				case JDBC_PROPERTIES:
    96 				case DATABASES:
    97 				case FORMATTERS:
    98 				case FORMATTER_PROPERTIES:
    99 				case TYPES:
   100 				case JAVA_PROPERTIES:
   101 				case ENVIRONMENT_VARIABLES:
   102 					formattinNeeded = true;
   103 					break;
   104 			}
   105 		}
   106 
   107 		if (formattinNeeded) {
   108 			try (Formatter f = getFormatter()) {
   109 				formatter = f;
   110 				formatter.writeStartBatch();
   111 				DatabaseDefinition dd = new DatabaseDefinition();
   112 				dd.setName(CONFIG_DB_NAME);
   113 				formatter.writeStartDatabase(dd);
   114 				showInfos(commands);
   115 				formatter.writeEndDatabase();
   116 				formatter.writeEndBatch();
   117 				formatter.close();
   118 			}
   119 		} else {
   120 			showInfos(commands);
   121 		}
   122 	}
   123 
   124 	private void showInfos(EnumSet<InfoType> commands) throws ConfigurationException, FormatterException {
   125 		for (InfoType infoType : commands) {
   126 			infoType.showInfo(this);
   127 		}
   128 	}
   129 
   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()});
   135 		}
   136 		printTable(formatter, header, "-- Java system properties", null, data, 0);
   137 	}
   138 
   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()});
   144 		}
   145 		printTable(formatter, header, "-- environment variables", null, data, 0);
   146 	}
   147 
   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<>();
   156 
   157 		String defaultFormatter = configurationProvider.getConfiguration().getDefaultFormatter();
   158 		defaultFormatter = defaultFormatter == null ? Configuration.DEFAULT_FORMATTER : defaultFormatter;
   159 
   160 		for (FormatterDefinition fd : configurationProvider.getConfiguration().getBuildInFormatters()) {
   161 			data.add(new Object[]{fd.getName(), true, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
   162 		}
   163 
   164 		for (FormatterDefinition fd : configurationProvider.getConfiguration().getFormatters()) {
   165 			data.add(new Object[]{fd.getName(), false, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
   166 		}
   167 
   168 		printTable(formatter, header, "-- configured and built-in output formatters", null, data);
   169 	}
   170 
   171 	private boolean isInstantiable(FormatterDefinition fd) {
   172 		try {
   173 			try (ByteArrayOutputStream testStream = new ByteArrayOutputStream()) {
   174 				fd.getInstance(new FormatterContext(testStream, new Properties(0), null));
   175 				return true;
   176 			}
   177 		} catch (Exception e) {
   178 			log.log(Level.SEVERE, "Unable to create an instance of formatter: " + fd.getName(), e);
   179 			return false;
   180 		}
   181 	}
   182 
   183 	private void listFormatterProperties() throws FormatterException, ConfigurationException {
   184 		for (String formatterName : options.getFormatterNamesToListProperties()) {
   185 			listFormatterProperties(formatterName);
   186 		}
   187 	}
   188 
   189 	private void listFormatterProperties(String formatterName) throws FormatterException, ConfigurationException {
   190 		FormatterDefinition fd = configurationProvider.getConfiguration().getFormatter(formatterName);
   191 		try {
   192 
   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);
   196 
   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));
   204 			}
   205 
   206 			ColumnsHeader header = constructHeader(headerFields.toArray(new HeaderField[0]));
   207 
   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));
   215 				}
   216 			});
   217 
   218 			List<Parameter> parameters = new ArrayList<>();
   219 			parameters.add(new NamedParameter("formatter", formatterName, SQLType.VARCHAR));
   220 
   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);
   224 		}
   225 	}
   226 
   227 	private static Object[] propertyDeclarationToRow(PropertyDeclaration p, Class formatterClass, boolean printDeclaredIn) {
   228 		List list = new ArrayList();
   229 
   230 		list.add(p.name());
   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());
   236 		}
   237 
   238 		return list.toArray();
   239 	}
   240 
   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()});
   246 		}
   247 		printTable(formatter, header, "-- data types", null, data);
   248 		log.log(Level.INFO, "Type names in --types option are case insensitive");
   249 	}
   250 
   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<>();
   257 
   258 		final List<DatabaseDefinition> configuredDatabases = configurationProvider.getConfiguration().getDatabases();
   259 		if (configuredDatabases.isEmpty()) {
   260 			log.log(Level.WARNING, "No databases are configured.");
   261 		} else {
   262 			for (DatabaseDefinition dd : configuredDatabases) {
   263 				data.add(new Object[]{dd.getName(), dd.getUserName(), dd.getUrl()});
   264 
   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()});
   270 					}
   271 				}
   272 
   273 			}
   274 		}
   275 
   276 		printTable(formatter, header, "-- configured databases", null, data);
   277 	}
   278 
   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<>();
   287 
   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(),
   293 				d.getMajorVersion(),
   294 				d.getMinorVersion(),
   295 				d.jdbcCompliant()
   296 			});
   297 		}
   298 
   299 		printTable(formatter, header, "-- discovered JDBC drivers (available on the CLASSPATH)", null, data);
   300 	}
   301 
   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<>();
   311 
   312 			DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
   313 
   314 			Driver driver = findDriver(dd);
   315 
   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()});
   318 			} else {
   319 				log.log(Level.INFO, "For DB: {0} was found JDBC driver: {1}", new Object[]{dd.getName(), driver.getClass().getName()});
   320 
   321 				try {
   322 					DriverPropertyInfo[] propertyInfos = driver.getPropertyInfo(dd.getUrl(), dd.getProperties().getJavaProperties());
   323 
   324 					Set<String> standardProperties = new HashSet<>();
   325 
   326 					for (DriverPropertyInfo pi : propertyInfos) {
   327 						Array choices = new FakeSqlArray(pi.choices, SQLType.VARCHAR);
   328 						data.add(new Object[]{
   329 							pi.name,
   330 							pi.required,
   331 							choices.getArray() == null ? "" : choices,
   332 							pi.value == null ? "" : pi.value,
   333 							pi.description
   334 						});
   335 						standardProperties.add(pi.name);
   336 					}
   337 
   338 					for (Property p : dd.getProperties()) {
   339 						if (!standardProperties.contains(p.getName())) {
   340 							data.add(new Object[]{
   341 								p.getName(),
   342 								"",
   343 								"",
   344 								p.getValue(),
   345 								""
   346 							});
   347 							log.log(Level.WARNING, "Your configuration contains property „{0}“ not declared by the JDBC driver.", p.getName());
   348 						}
   349 					}
   350 
   351 				} catch (SQLException e) {
   352 					log.log(Level.WARNING, "Error during getting property infos.", e);
   353 				}
   354 
   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));
   360 
   361 				printTable(formatter, header, "-- configured and configurable JDBC driver properties", parameters, data);
   362 			}
   363 		}
   364 
   365 	}
   366 
   367 	private Driver findDriver(DatabaseDefinition dd) {
   368 		final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
   369 		for (Driver d : drivers) {
   370 			try {
   371 				if (d.acceptsURL(dd.getUrl())) {
   372 					return d;
   373 				}
   374 			} catch (SQLException e) {
   375 				log.log(Level.WARNING, "Error during finding JDBC driver for: " + dd.getName(), e);
   376 			}
   377 		}
   378 		return null;
   379 	}
   380 
   381 	/**
   382 	 * Parallelism for connection testing – maximum concurrent database connections.
   383 	 */
   384 	private static final int TESTING_THREAD_COUNT = 64;
   385 	/**
   386 	 * Time limit for all connection testing threads – particular timeouts per connection will be
   387 	 * much smaller.
   388 	 */
   389 	private static final long TESTING_AWAIT_LIMIT = 1;
   390 	private static final TimeUnit TESTING_AWAIT_UNIT = TimeUnit.DAYS;
   391 
   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));
   399 
   400 		log.log(Level.FINE, "Testing DB connections in {0} threads", TESTING_THREAD_COUNT);
   401 
   402 		ExecutorService es = Executors.newFixedThreadPool(TESTING_THREAD_COUNT);
   403 
   404 		final Formatter currentFormatter = formatter;
   405 
   406 		printHeader(currentFormatter, header, "-- database configuration and connectivity test", null);
   407 
   408 		for (final String dbName : options.getDatabaseNamesToTest()) {
   409 			preloadDriver(dbName);
   410 		}
   411 
   412 		for (final String dbName : options.getDatabaseNamesToTest()) {
   413 			es.submit(() -> {
   414 				final Object[] row = testConnection(dbName);
   415 				synchronized (currentFormatter) {
   416 					printRow(currentFormatter, row);
   417 				}
   418 			}
   419 			);
   420 		}
   421 
   422 		es.shutdown();
   423 
   424 		try {
   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);
   427 			if (finished) {
   428 				log.log(Level.FINEST, "All testing threads finished in time limit.");
   429 			} else {
   430 				throw new FormatterException("Exceeded total time limit for test threads – this should never happen");
   431 			}
   432 		} catch (InterruptedException e) {
   433 			throw new FormatterException("Interrupted while waiting for test results", e);
   434 		}
   435 
   436 		printFooter(currentFormatter);
   437 	}
   438 
   439 	/**
   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.
   442 	 *
   443 	 * @param dbName
   444 	 */
   445 	private void preloadDriver(String dbName) {
   446 		try {
   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);
   451 			} else {
   452 				log.log(Level.FINEST, "Driver preloading for DB: {0} was successfull", dbName);
   453 			}
   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});
   457 			r.setThrown(e);
   458 			log.log(r);
   459 		}
   460 	}
   461 
   462 	private Object[] testConnection(String dbName) {
   463 		log.log(Level.FINE, "Testing connection to database: {0}", dbName);
   464 
   465 		boolean succesfullyConnected = false;
   466 		boolean succesfullyConfigured = false;
   467 		String productName = null;
   468 		String productVersion = null;
   469 
   470 		try {
   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();
   478 			}
   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);
   482 		}
   483 
   484 		return new Object[]{dbName, succesfullyConfigured, succesfullyConnected, productName, productVersion};
   485 	}
   486 
   487 	private void printResource(String fileName) {
   488 		try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(fileName)))) {
   489 			while (true) {
   490 				String line = reader.readLine();
   491 				if (line == null) {
   492 					break;
   493 				} else {
   494 					println(line);
   495 				}
   496 			}
   497 		} catch (Exception e) {
   498 			log.log(Level.SEVERE, "Unable to print this info. Please see our website for it: " + Constants.WEBSITE, e);
   499 		}
   500 	}
   501 
   502 	private void println(String line) {
   503 		out.println(line);
   504 	}
   505 
   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);
   508 	}
   509 
   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);
   512 
   513 		if (sortByColumn != null) {
   514 			Collections.sort(data, new Comparator<Object[]>() {
   515 
   516 				@Override
   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);
   521 				}
   522 			});
   523 		}
   524 
   525 		for (Object[] row : data) {
   526 			printRow(formatter, row);
   527 		}
   528 
   529 		printFooter(formatter);
   530 	}
   531 
   532 	private void printHeader(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters) {
   533 		formatter.writeStartStatement();
   534 		if (sql != null) {
   535 			formatter.writeQuery(sql);
   536 			if (parameters != null) {
   537 				formatter.writeParameters(parameters);
   538 			}
   539 		}
   540 		formatter.writeStartResultSet(header);
   541 	}
   542 
   543 	private void printRow(Formatter formatter, Object[] row) {
   544 		formatter.writeStartRow();
   545 		for (Object cell : row) {
   546 			formatter.writeColumnValue(cell);
   547 		}
   548 		formatter.writeEndRow();
   549 	}
   550 
   551 	private void printFooter(Formatter formatter) {
   552 		formatter.writeEndResultSet();
   553 		formatter.writeEndStatement();
   554 	}
   555 
   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);
   562 	}
   563 
   564 	private ColumnsHeader constructHeader(HeaderField... fields) throws FormatterException {
   565 		try {
   566 			RowSetMetaDataImpl metaData = new RowSetMetaDataImpl();
   567 			metaData.setColumnCount(fields.length);
   568 
   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());
   576 			}
   577 
   578 			return new ColumnsHeader(metaData);
   579 		} catch (SQLException e) {
   580 			throw new FormatterException("Error while constructing table headers", e);
   581 		}
   582 	}
   583 
   584 	private static class HeaderField {
   585 
   586 		String name;
   587 		SQLType type;
   588 
   589 		public HeaderField(String name, SQLType type) {
   590 			this.name = name;
   591 			this.type = type;
   592 		}
   593 	}
   594 
   595 	public enum InfoType {
   596 
   597 		HELP {
   598 			@Override
   599 			public void showInfo(InfoLister infoLister) {
   600 				infoLister.printResource(Constants.HELP_FILE);
   601 			}
   602 		},
   603 		VERSION {
   604 			@Override
   605 			public void showInfo(InfoLister infoLister) {
   606 				infoLister.printResource(Constants.VERSION_FILE);
   607 			}
   608 		},
   609 		LICENSE {
   610 			@Override
   611 			public void showInfo(InfoLister infoLister) {
   612 				infoLister.printResource(Constants.LICENSE_FILE);
   613 			}
   614 		},
   615 		JAVA_PROPERTIES {
   616 			@Override
   617 			public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   618 				infoLister.listJavaProperties();
   619 			}
   620 		},
   621 		ENVIRONMENT_VARIABLES {
   622 			@Override
   623 			public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   624 				infoLister.listEnvironmentVariables();
   625 			}
   626 		},
   627 		FORMATTERS {
   628 			@Override
   629 			public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   630 				infoLister.listFormatters();
   631 			}
   632 		},
   633 		FORMATTER_PROPERTIES {
   634 			@Override
   635 			public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   636 				infoLister.listFormatterProperties();
   637 			}
   638 		},
   639 		TYPES {
   640 			@Override
   641 			public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   642 				infoLister.listTypes();
   643 			}
   644 		},
   645 		JDBC_DRIVERS {
   646 			@Override
   647 			public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
   648 				infoLister.listJdbcDrivers();
   649 			}
   650 		},
   651 		JDBC_PROPERTIES {
   652 			@Override
   653 			public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
   654 				infoLister.listJdbcProperties();
   655 			}
   656 		},
   657 		DATABASES {
   658 			@Override
   659 			public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   660 				infoLister.listDatabases();
   661 			}
   662 		},
   663 		CONNECTION {
   664 			@Override
   665 			public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   666 				infoLister.testConnections();
   667 			}
   668 		};
   669 
   670 		public abstract void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException;
   671 	}
   672 }