java/sql-dk/src/info/globalcode/sql/dk/InfoLister.java
author František Kučera <franta-hg@frantovo.cz>
Sun, 16 Aug 2015 01:25:01 +0200
branchv_0
changeset 220 0bc544b38cfa
parent 216 0eb9aec16bf4
child 229 7699133f5a01
permissions -rw-r--r--
bash-completion: --formatter-property names
     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, either version 3 of the License, or
     8  * (at your option) any later version.
     9  *
    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.
    14  *
    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/>.
    17  */
    18 package info.globalcode.sql.dk;
    19 
    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.PropertyDeclarations;
    30 import info.globalcode.sql.dk.configuration.TunnelDefinition;
    31 import info.globalcode.sql.dk.formatting.ColumnsHeader;
    32 import info.globalcode.sql.dk.formatting.CommonProperties;
    33 import info.globalcode.sql.dk.formatting.FakeSqlArray;
    34 import info.globalcode.sql.dk.formatting.Formatter;
    35 import info.globalcode.sql.dk.formatting.FormatterContext;
    36 import info.globalcode.sql.dk.formatting.FormatterException;
    37 import java.io.BufferedReader;
    38 import java.io.ByteArrayOutputStream;
    39 import java.io.InputStreamReader;
    40 import java.io.PrintStream;
    41 import java.sql.Array;
    42 import java.sql.Driver;
    43 import java.sql.DriverManager;
    44 import java.sql.DriverPropertyInfo;
    45 import java.sql.SQLException;
    46 import java.util.ArrayList;
    47 import java.util.Collections;
    48 import java.util.Comparator;
    49 import java.util.EnumSet;
    50 import java.util.HashMap;
    51 import java.util.HashSet;
    52 import java.util.List;
    53 import java.util.Map;
    54 import java.util.Map.Entry;
    55 import java.util.ServiceLoader;
    56 import java.util.Set;
    57 import java.util.concurrent.ExecutorService;
    58 import java.util.concurrent.Executors;
    59 import java.util.concurrent.TimeUnit;
    60 import java.util.logging.Level;
    61 import java.util.logging.LogRecord;
    62 import java.util.logging.Logger;
    63 import javax.sql.rowset.RowSetMetaDataImpl;
    64 
    65 /**
    66  * Displays info like help, version etc.
    67  *
    68  * @author Ing. František Kučera (frantovo.cz)
    69  */
    70 public class InfoLister {
    71 
    72 	private static final Logger log = Logger.getLogger(InfoLister.class.getName());
    73 	/**
    74 	 * Fake database name for output formatting
    75 	 */
    76 	public static final String CONFIG_DB_NAME = "sqldk_configuration";
    77 	private final PrintStream out;
    78 	private final ConfigurationProvider configurationProvider;
    79 	private final CLIOptions options;
    80 	private Formatter formatter;
    81 
    82 	public InfoLister(PrintStream out, ConfigurationProvider configurationProvider, CLIOptions options) {
    83 		this.out = out;
    84 		this.configurationProvider = configurationProvider;
    85 		this.options = options;
    86 	}
    87 
    88 	public void showInfo() throws ConfigurationException, FormatterException {
    89 		EnumSet<InfoType> commands = options.getShowInfo();
    90 
    91 		boolean formattinNeeded = false;
    92 
    93 		for (InfoType infoType : commands) {
    94 			switch (infoType) {
    95 				case CONNECTION:
    96 				case JDBC_DRIVERS:
    97 				case JDBC_PROPERTIES:
    98 				case DATABASES:
    99 				case FORMATTERS:
   100 				case FORMATTER_PROPERTIES:
   101 				case TYPES:
   102 				case JAVA_PROPERTIES:
   103 				case ENVIRONMENT_VARIABLES:
   104 					formattinNeeded = true;
   105 					break;
   106 			}
   107 		}
   108 
   109 		if (formattinNeeded) {
   110 			try (Formatter f = getFormatter()) {
   111 				formatter = f;
   112 				formatter.writeStartBatch();
   113 				DatabaseDefinition dd = new DatabaseDefinition();
   114 				dd.setName(CONFIG_DB_NAME);
   115 				formatter.writeStartDatabase(dd);
   116 				showInfos(commands);
   117 				formatter.writeEndDatabase();
   118 				formatter.writeEndBatch();
   119 				formatter.close();
   120 			}
   121 		} else {
   122 			showInfos(commands);
   123 		}
   124 	}
   125 
   126 	private void showInfos(EnumSet<InfoType> commands) throws ConfigurationException, FormatterException {
   127 		for (InfoType infoType : commands) {
   128 			infoType.showInfo(this);
   129 		}
   130 	}
   131 
   132 	private void listJavaProperties() throws FormatterException, ConfigurationException {
   133 		ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("value", SQLType.VARCHAR));
   134 		List<Object[]> data = new ArrayList<>();
   135 		for (Entry<Object, Object> e : System.getProperties().entrySet()) {
   136 			data.add(new Object[]{e.getKey(), e.getValue()});
   137 		}
   138 		printTable(formatter, header, "-- Java system properties", null, data, 0);
   139 	}
   140 
   141 	private void listEnvironmentVariables() throws FormatterException, ConfigurationException {
   142 		ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("value", SQLType.VARCHAR));
   143 		List<Object[]> data = new ArrayList<>();
   144 		for (Entry<String, String> e : System.getenv().entrySet()) {
   145 			data.add(new Object[]{e.getKey(), e.getValue()});
   146 		}
   147 		printTable(formatter, header, "-- environment variables", null, data, 0);
   148 	}
   149 
   150 	private void listFormatters() throws ConfigurationException, FormatterException {
   151 		ColumnsHeader header = constructHeader(
   152 				new HeaderField("name", SQLType.VARCHAR),
   153 				new HeaderField("built_in", SQLType.BOOLEAN),
   154 				new HeaderField("default", SQLType.BOOLEAN),
   155 				new HeaderField("class_name", SQLType.VARCHAR),
   156 				new HeaderField("valid", SQLType.BOOLEAN));
   157 		List<Object[]> data = new ArrayList<>();
   158 
   159 		String defaultFormatter = configurationProvider.getConfiguration().getDefaultFormatter();
   160 		defaultFormatter = defaultFormatter == null ? Configuration.DEFAULT_FORMATTER : defaultFormatter;
   161 
   162 		for (FormatterDefinition fd : configurationProvider.getConfiguration().getBuildInFormatters()) {
   163 			data.add(new Object[]{fd.getName(), true, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
   164 		}
   165 
   166 		for (FormatterDefinition fd : configurationProvider.getConfiguration().getFormatters()) {
   167 			data.add(new Object[]{fd.getName(), false, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
   168 		}
   169 
   170 		printTable(formatter, header, "-- configured and built-in output formatters", null, data);
   171 	}
   172 
   173 	private boolean isInstantiable(FormatterDefinition fd) {
   174 		try {
   175 			try (ByteArrayOutputStream testStream = new ByteArrayOutputStream()) {
   176 				fd.getInstance(new FormatterContext(testStream, new Properties(0)));
   177 				return true;
   178 			}
   179 		} catch (Exception e) {
   180 			log.log(Level.SEVERE, "Unable to create an instance of formatter: " + fd.getName(), e);
   181 			return false;
   182 		}
   183 	}
   184 
   185 	private void listFormatterProperties() throws FormatterException, ConfigurationException {
   186 		for (String formatterName : options.getFormatterNamesToListProperties()) {
   187 			listFormatterProperties(formatterName);
   188 		}
   189 	}
   190 
   191 	private void listFormatterProperties(String formatterName) throws FormatterException, ConfigurationException {
   192 		FormatterDefinition fd = configurationProvider.getConfiguration().getFormatter(formatterName);
   193 		try {
   194 
   195 			// currently only for debugging purposes
   196 			// TODO: introduce --info-lister-property or generic filtering capability in printTable() ?
   197 			boolean printDeclaredIn = options.getFormatterProperties().getBoolean("InfoLister:print:declared_in", false);
   198 
   199 			List<HeaderField> headerFields = new ArrayList<>();
   200 			headerFields.add(new HeaderField("name", SQLType.VARCHAR));
   201 			headerFields.add(new HeaderField("type", SQLType.VARCHAR));
   202 			headerFields.add(new HeaderField("default", SQLType.VARCHAR));
   203 			headerFields.add(new HeaderField("description", SQLType.VARCHAR));
   204 			if (printDeclaredIn) {
   205 				headerFields.add(new HeaderField("declared_in", SQLType.VARCHAR));
   206 			}
   207 
   208 			ColumnsHeader header = constructHeader(headerFields.toArray(new HeaderField[0]));
   209 
   210 			Map<String, Object[]> data = new HashMap<>();
   211 			Class<Formatter> formatterClass = (Class<Formatter>) Class.forName(fd.getClassName());
   212 			List<Class<? extends Formatter>> hierarchy = Functions.getClassHierarchy(formatterClass, Formatter.class);
   213 			Collections.reverse(hierarchy);
   214 			hierarchy.stream().forEach((c) -> {
   215 				for (PropertyDeclaration p : Functions.getPropertyDeclarations(c)) {
   216 					data.put(p.name(), propertyDeclarationToRow(p, c, printDeclaredIn));
   217 				}
   218 			});
   219 
   220 			List<Parameter> parameters = new ArrayList<>();
   221 			parameters.add(new NamedParameter("formatter", formatterName, SQLType.VARCHAR));
   222 
   223 			printTable(formatter, header, "-- formatter properties", parameters, new ArrayList<>(data.values()));
   224 		} catch (ClassNotFoundException e) {
   225 			throw new ConfigurationException("Unable to find class " + fd.getClassName() + " of formatter" + fd.getName(), e);
   226 		}
   227 	}
   228 
   229 	private static Object[] propertyDeclarationToRow(PropertyDeclaration p, Class formatterClass, boolean printDeclaredIn) {
   230 		List list = new ArrayList();
   231 
   232 		list.add(p.name());
   233 		list.add(CommonProperties.getSimpleTypeName(p.type()));
   234 		list.add(p.defaultValue());
   235 		list.add(p.description());
   236 		if (printDeclaredIn) {
   237 			list.add(formatterClass.getName());
   238 		}
   239 
   240 		return list.toArray();
   241 	}
   242 
   243 	private void listTypes() throws FormatterException, ConfigurationException {
   244 		ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("code", SQLType.INTEGER));
   245 		List<Object[]> data = new ArrayList<>();
   246 		for (SQLType sqlType : SQLType.values()) {
   247 			data.add(new Object[]{sqlType.name(), sqlType.getCode()});
   248 		}
   249 		printTable(formatter, header, "-- data types", null, data);
   250 		log.log(Level.INFO, "Type names in --types option are case insensitive");
   251 	}
   252 
   253 	private void listDatabases() throws ConfigurationException, FormatterException {
   254 		ColumnsHeader header = constructHeader(
   255 				new HeaderField("database_name", SQLType.VARCHAR),
   256 				new HeaderField("user_name", SQLType.VARCHAR),
   257 				new HeaderField("database_url", SQLType.VARCHAR));
   258 		List<Object[]> data = new ArrayList<>();
   259 
   260 		final List<DatabaseDefinition> configuredDatabases = configurationProvider.getConfiguration().getDatabases();
   261 		if (configuredDatabases.isEmpty()) {
   262 			log.log(Level.WARNING, "No databases are configured.");
   263 		} else {
   264 			for (DatabaseDefinition dd : configuredDatabases) {
   265 				data.add(new Object[]{dd.getName(), dd.getUserName(), dd.getUrl()});
   266 
   267 				final TunnelDefinition tunnel = dd.getTunnel();
   268 				if (tunnel != null) {
   269 					log.log(Level.INFO, "Tunnel command: {0}", tunnel.getCommand());
   270 					for (CommandArgument ca : Functions.notNull(tunnel.getArguments())) {
   271 						log.log(Level.INFO, "\targument: {0}/{1}", new Object[]{ca.getType(), ca.getValue()});
   272 					}
   273 				}
   274 
   275 			}
   276 		}
   277 
   278 		printTable(formatter, header, "-- configured databases", null, data);
   279 	}
   280 
   281 	private void listJdbcDrivers() throws FormatterException, ConfigurationException {
   282 		ColumnsHeader header = constructHeader(
   283 				new HeaderField("class", SQLType.VARCHAR),
   284 				new HeaderField("version", SQLType.VARCHAR),
   285 				new HeaderField("major", SQLType.INTEGER),
   286 				new HeaderField("minor", SQLType.INTEGER),
   287 				new HeaderField("jdbc_compliant", SQLType.BOOLEAN));
   288 		List<Object[]> data = new ArrayList<>();
   289 
   290 		final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
   291 		for (Driver d : drivers) {
   292 			data.add(new Object[]{
   293 				d.getClass().getName(),
   294 				d.getMajorVersion() + "." + d.getMinorVersion(),
   295 				d.getMajorVersion(),
   296 				d.getMinorVersion(),
   297 				d.jdbcCompliant()
   298 			});
   299 		}
   300 
   301 		printTable(formatter, header, "-- discovered JDBC drivers (available on the CLASSPATH)", null, data);
   302 	}
   303 
   304 	private void listJdbcProperties() throws FormatterException, ConfigurationException {
   305 		for (String dbName : options.getDatabaseNamesToListProperties()) {
   306 			ColumnsHeader header = constructHeader(
   307 					new HeaderField("property_name", SQLType.VARCHAR),
   308 					new HeaderField("required", SQLType.BOOLEAN),
   309 					new HeaderField("choices", SQLType.ARRAY),
   310 					new HeaderField("configured_value", SQLType.VARCHAR),
   311 					new HeaderField("description", SQLType.VARCHAR));
   312 			List<Object[]> data = new ArrayList<>();
   313 
   314 			DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
   315 
   316 			Driver driver = findDriver(dd);
   317 
   318 			if (driver == null) {
   319 				log.log(Level.WARNING, "No JDBC driver was found for DB: {0} with URL: {1}", new Object[]{dd.getName(), dd.getUrl()});
   320 			} else {
   321 				log.log(Level.INFO, "For DB: {0} was found JDBC driver: {1}", new Object[]{dd.getName(), driver.getClass().getName()});
   322 
   323 				try {
   324 					DriverPropertyInfo[] propertyInfos = driver.getPropertyInfo(dd.getUrl(), dd.getProperties().getJavaProperties());
   325 
   326 					Set<String> standardProperties = new HashSet<>();
   327 
   328 					for (DriverPropertyInfo pi : propertyInfos) {
   329 						Array choices = new FakeSqlArray(pi.choices, SQLType.VARCHAR);
   330 						data.add(new Object[]{
   331 							pi.name,
   332 							pi.required,
   333 							choices.getArray() == null ? "" : choices,
   334 							pi.value == null ? "" : pi.value,
   335 							pi.description
   336 						});
   337 						standardProperties.add(pi.name);
   338 					}
   339 
   340 					for (Property p : dd.getProperties()) {
   341 						if (!standardProperties.contains(p.getName())) {
   342 							data.add(new Object[]{
   343 								p.getName(),
   344 								"",
   345 								"",
   346 								p.getValue(),
   347 								""
   348 							});
   349 							log.log(Level.WARNING, "Your configuration contains property „{0}“ not declared by the JDBC driver.", p.getName());
   350 						}
   351 					}
   352 
   353 				} catch (SQLException e) {
   354 					log.log(Level.WARNING, "Error during getting property infos.", e);
   355 				}
   356 
   357 				List<Parameter> parameters = new ArrayList<>();
   358 				parameters.add(new NamedParameter("database", dbName, SQLType.VARCHAR));
   359 				parameters.add(new NamedParameter("driver_class", driver.getClass().getName(), SQLType.VARCHAR));
   360 				parameters.add(new NamedParameter("driver_major_version", driver.getMajorVersion(), SQLType.INTEGER));
   361 				parameters.add(new NamedParameter("driver_minor_version", driver.getMinorVersion(), SQLType.INTEGER));
   362 
   363 				printTable(formatter, header, "-- configured and configurable JDBC driver properties", parameters, data);
   364 			}
   365 		}
   366 
   367 	}
   368 
   369 	private Driver findDriver(DatabaseDefinition dd) {
   370 		final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
   371 		for (Driver d : drivers) {
   372 			try {
   373 				if (d.acceptsURL(dd.getUrl())) {
   374 					return d;
   375 				}
   376 			} catch (SQLException e) {
   377 				log.log(Level.WARNING, "Error during finding JDBC driver for: " + dd.getName(), e);
   378 			}
   379 		}
   380 		return null;
   381 	}
   382 
   383 	/**
   384 	 * Parallelism for connection testing – maximum concurrent database connections.
   385 	 */
   386 	private static final int TESTING_THREAD_COUNT = 64;
   387 	/**
   388 	 * Time limit for all connection testing threads – particular timeouts per connection will be
   389 	 * much smaller.
   390 	 */
   391 	private static final long TESTING_AWAIT_LIMIT = 1;
   392 	private static final TimeUnit TESTING_AWAIT_UNIT = TimeUnit.DAYS;
   393 
   394 	private void testConnections() throws FormatterException, ConfigurationException {
   395 		ColumnsHeader header = constructHeader(
   396 				new HeaderField("database_name", SQLType.VARCHAR),
   397 				new HeaderField("configured", SQLType.BOOLEAN),
   398 				new HeaderField("connected", SQLType.BOOLEAN));
   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 
   468 		try {
   469 			DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
   470 			log.log(Level.FINE, "Database definition was loaded from configuration");
   471 			succesfullyConfigured = true;
   472 			try (DatabaseConnection dc = dd.connect(options.getDatabaseProperties())) {
   473 				succesfullyConnected = dc.test();
   474 			}
   475 			log.log(Level.FINE, "Database connection test was successful");
   476 		} catch (ConfigurationException | SQLException | RuntimeException e) {
   477 			log.log(Level.SEVERE, "Error during testing connection " + dbName, e);
   478 		}
   479 
   480 		return new Object[]{dbName, succesfullyConfigured, succesfullyConnected};
   481 	}
   482 
   483 	private void printResource(String fileName) {
   484 		try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(fileName)))) {
   485 			while (true) {
   486 				String line = reader.readLine();
   487 				if (line == null) {
   488 					break;
   489 				} else {
   490 					println(line);
   491 				}
   492 			}
   493 		} catch (Exception e) {
   494 			log.log(Level.SEVERE, "Unable to print this info. Please see our website for it: " + Constants.WEBSITE, e);
   495 		}
   496 	}
   497 
   498 	private void println(String line) {
   499 		out.println(line);
   500 	}
   501 
   502 	private void printTable(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters, List<Object[]> data) throws ConfigurationException, FormatterException {
   503 		printTable(formatter, header, sql, parameters, data, null);
   504 	}
   505 
   506 	private void printTable(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters, List<Object[]> data, final Integer sortByColumn) throws ConfigurationException, FormatterException {
   507 		printHeader(formatter, header, sql, parameters);
   508 
   509 		if (sortByColumn != null) {
   510 			Collections.sort(data, new Comparator<Object[]>() {
   511 
   512 				@Override
   513 				public int compare(Object[] o1, Object[] o2) {
   514 					String s1 = String.valueOf(o1[sortByColumn]);
   515 					String s2 = String.valueOf(o2[sortByColumn]);
   516 					return s1.compareTo(s2);
   517 				}
   518 			});
   519 		}
   520 
   521 		for (Object[] row : data) {
   522 			printRow(formatter, row);
   523 		}
   524 
   525 		printFooter(formatter);
   526 	}
   527 
   528 	private void printHeader(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters) {
   529 		formatter.writeStartStatement();
   530 		if (sql != null) {
   531 			formatter.writeQuery(sql);
   532 			if (parameters != null) {
   533 				formatter.writeParameters(parameters);
   534 			}
   535 		}
   536 		formatter.writeStartResultSet(header);
   537 	}
   538 
   539 	private void printRow(Formatter formatter, Object[] row) {
   540 		formatter.writeStartRow();
   541 		for (Object cell : row) {
   542 			formatter.writeColumnValue(cell);
   543 		}
   544 		formatter.writeEndRow();
   545 	}
   546 
   547 	private void printFooter(Formatter formatter) {
   548 		formatter.writeEndResultSet();
   549 		formatter.writeEndStatement();
   550 	}
   551 
   552 	private Formatter getFormatter() throws ConfigurationException, FormatterException {
   553 		String formatterName = options.getFormatterName();
   554 		formatterName = formatterName == null ? Configuration.DEFAULT_FORMATTER_PREFETCHING : formatterName;
   555 		FormatterDefinition fd = configurationProvider.getConfiguration().getFormatter(formatterName);
   556 		FormatterContext context = new FormatterContext(out, options.getFormatterProperties());
   557 		return fd.getInstance(context);
   558 	}
   559 
   560 	private ColumnsHeader constructHeader(HeaderField... fields) throws FormatterException {
   561 		try {
   562 			RowSetMetaDataImpl metaData = new RowSetMetaDataImpl();
   563 			metaData.setColumnCount(fields.length);
   564 
   565 			for (int i = 0; i < fields.length; i++) {
   566 				HeaderField hf = fields[i];
   567 				int sqlIndex = i + 1;
   568 				metaData.setColumnName(sqlIndex, hf.name);
   569 				metaData.setColumnLabel(sqlIndex, hf.name);
   570 				metaData.setColumnType(sqlIndex, hf.type.getCode());
   571 				metaData.setColumnTypeName(sqlIndex, hf.type.name());
   572 			}
   573 
   574 			return new ColumnsHeader(metaData);
   575 		} catch (SQLException e) {
   576 			throw new FormatterException("Error while constructing table headers", e);
   577 		}
   578 	}
   579 
   580 	private static class HeaderField {
   581 
   582 		String name;
   583 		SQLType type;
   584 
   585 		public HeaderField(String name, SQLType type) {
   586 			this.name = name;
   587 			this.type = type;
   588 		}
   589 	}
   590 
   591 	public enum InfoType {
   592 
   593 		HELP {
   594 					@Override
   595 					public void showInfo(InfoLister infoLister) {
   596 						infoLister.printResource(Constants.HELP_FILE);
   597 					}
   598 				},
   599 		VERSION {
   600 					@Override
   601 					public void showInfo(InfoLister infoLister) {
   602 						infoLister.printResource(Constants.VERSION_FILE);
   603 					}
   604 				},
   605 		LICENSE {
   606 					@Override
   607 					public void showInfo(InfoLister infoLister) {
   608 						infoLister.printResource(Constants.LICENSE_FILE);
   609 					}
   610 				},
   611 		JAVA_PROPERTIES {
   612 					@Override
   613 					public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   614 						infoLister.listJavaProperties();
   615 					}
   616 				},
   617 		ENVIRONMENT_VARIABLES {
   618 					@Override
   619 					public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   620 						infoLister.listEnvironmentVariables();
   621 					}
   622 				},
   623 		FORMATTERS {
   624 					@Override
   625 					public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   626 						infoLister.listFormatters();
   627 					}
   628 				},
   629 		FORMATTER_PROPERTIES {
   630 					@Override
   631 					public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   632 						infoLister.listFormatterProperties();
   633 					}
   634 				},
   635 		TYPES {
   636 					@Override
   637 					public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   638 						infoLister.listTypes();
   639 					}
   640 				},
   641 		JDBC_DRIVERS {
   642 					@Override
   643 					public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
   644 						infoLister.listJdbcDrivers();
   645 					}
   646 				},
   647 		JDBC_PROPERTIES {
   648 					@Override
   649 					public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
   650 						infoLister.listJdbcProperties();
   651 					}
   652 				},
   653 		DATABASES {
   654 					@Override
   655 					public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   656 						infoLister.listDatabases();
   657 					}
   658 				},
   659 		CONNECTION {
   660 					@Override
   661 					public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   662 						infoLister.testConnections();
   663 					}
   664 				};
   665 
   666 		public abstract void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException;
   667 	}
   668 }