java/sql-dk/src/info/globalcode/sql/dk/DatabaseConnection.java
author František Kučera <franta-hg@frantovo.cz>
Wed, 15 Jan 2014 21:06:12 +0100
branchv_0
changeset 159 9632b23df30c
parent 155 eb3676c6929b
child 178 5a5fc66f11b1
permissions -rw-r--r--
InfoLister: list configured and configurable JDBC driver properties – option: --list-jdbc-properties
     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.batch.Batch;
    21 import info.globalcode.sql.dk.batch.BatchException;
    22 import info.globalcode.sql.dk.configuration.DatabaseDefinition;
    23 import info.globalcode.sql.dk.configuration.Properties;
    24 import info.globalcode.sql.dk.configuration.Property;
    25 import info.globalcode.sql.dk.formatting.ColumnsHeader;
    26 import info.globalcode.sql.dk.formatting.Formatter;
    27 import java.sql.Connection;
    28 import java.sql.DriverManager;
    29 import java.sql.PreparedStatement;
    30 import java.sql.ResultSet;
    31 import java.sql.SQLException;
    32 import java.sql.SQLWarning;
    33 import java.util.logging.Level;
    34 import java.util.logging.Logger;
    35 
    36 /**
    37  * Represents connected database. Is derived from {@linkplain DatabaseDefinition}.
    38  * Wraps {@linkplain Connection}.
    39  *
    40  * Is responsible for executing {@linkplain SQLCommand} and passing results to the
    41  * {@linkplain Formatter}.
    42  *
    43  * @author Ing. František Kučera (frantovo.cz)
    44  */
    45 public class DatabaseConnection implements AutoCloseable {
    46 
    47 	private static final Logger log = Logger.getLogger(DatabaseConnection.class.getName());
    48 	private static final String JDBC_PROPERTY_USER = "user";
    49 	public static final String JDBC_PROPERTY_PASSWORD = "password";
    50 	private DatabaseDefinition databaseDefinition;
    51 	private Connection connection;
    52 	private Properties properties;
    53 
    54 	public DatabaseConnection(DatabaseDefinition databaseDefinition, Properties properties) throws SQLException {
    55 		this.databaseDefinition = databaseDefinition;
    56 		this.properties = properties;
    57 
    58 		if (properties.hasProperty(JDBC_PROPERTY_PASSWORD)) {
    59 			log.log(Level.WARNING, "Passing DB password as CLI parameter is insecure!");
    60 		}
    61 
    62 		Properties credentials = new Properties();
    63 		credentials.add(new Property(JDBC_PROPERTY_USER, databaseDefinition.getUserName()));
    64 		credentials.add(new Property(JDBC_PROPERTY_PASSWORD, databaseDefinition.getPassword()));
    65 		credentials.setDefaults(databaseDefinition.getProperties());
    66 		properties.setDefaults(credentials);
    67 		java.util.Properties javaProperties = properties.getJavaProperties();
    68 
    69 		connection = DriverManager.getConnection(databaseDefinition.getUrl(), javaProperties);
    70 	}
    71 
    72 	public void executeQuery(SQLCommand sqlCommand, Formatter formatter) throws SQLException {
    73 		formatter.writeStartBatch();
    74 		formatter.writeStartDatabase(databaseDefinition);
    75 		formatter.writeStartStatement();
    76 		formatter.writeQuery(sqlCommand.getQuery());
    77 		formatter.writeParameters(sqlCommand.getParameters());
    78 		processCommand(sqlCommand, formatter);
    79 		formatter.writeEndStatement();
    80 		formatter.writeEndDatabase();
    81 		formatter.writeEndBatch();
    82 	}
    83 
    84 	public void executeBatch(Batch batch, Formatter formatter) throws SQLException, BatchException {
    85 		formatter.writeStartBatch();
    86 		formatter.writeStartDatabase(databaseDefinition);
    87 		while (batch.hasNext()) {
    88 			SQLCommand sqlCommand = batch.next();
    89 			formatter.writeStartStatement();
    90 			formatter.writeQuery(sqlCommand.getQuery());
    91 			formatter.writeParameters(sqlCommand.getParameters());
    92 			processCommand(sqlCommand, formatter);
    93 			formatter.writeEndStatement();
    94 		}
    95 		formatter.writeEndDatabase();
    96 		formatter.writeEndBatch();
    97 	}
    98 
    99 	private void processCommand(SQLCommand sqlCommand, Formatter formatter) throws SQLException {
   100 		try (PreparedStatement ps = sqlCommand.prepareStatement(connection)) {
   101 			log.log(Level.FINE, "Statement prepared");
   102 			sqlCommand.parametrize(ps);
   103 
   104 			boolean isRS = ps.execute();
   105 			log.log(Level.FINE, "Statement executed");
   106 			if (isRS) {
   107 				try (ResultSet rs = ps.getResultSet()) {
   108 					processResultSet(rs, formatter);
   109 				}
   110 			} else {
   111 				processUpdateResult(ps, formatter);
   112 			}
   113 			logWarnings(ps);
   114 
   115 			while (ps.getMoreResults() || ps.getUpdateCount() > -1) {
   116 				ResultSet rs = ps.getResultSet();
   117 				if (rs == null) {
   118 					processUpdateResult(ps, formatter);
   119 				} else {
   120 					processResultSet(rs, formatter);
   121 					rs.close();
   122 				}
   123 				logWarnings(ps);
   124 			}
   125 		}
   126 	}
   127 
   128 	private void processUpdateResult(PreparedStatement ps, Formatter formatter) throws SQLException {
   129 		formatter.writeUpdatesResult(ps.getUpdateCount());
   130 	}
   131 
   132 	private void processResultSet(ResultSet rs, Formatter formatter) throws SQLException {
   133 		formatter.writeStartResultSet(new ColumnsHeader(rs.getMetaData()));
   134 
   135 		int columnCount = rs.getMetaData().getColumnCount();
   136 
   137 		while (rs.next()) {
   138 			formatter.writeStartRow();
   139 
   140 			for (int i = 1; i <= columnCount; i++) {
   141 				formatter.writeColumnValue(rs.getObject(i));
   142 			}
   143 
   144 			formatter.writeEndRow();
   145 		}
   146 
   147 		formatter.writeEndResultSet();
   148 	}
   149 
   150 	private void logWarnings(PreparedStatement ps) throws SQLException {
   151 		SQLWarning w = ps.getWarnings();
   152 		while (w != null) {
   153 			log.log(Level.WARNING, "SQL: {0}", w.getLocalizedMessage());
   154 			w = w.getNextWarning();
   155 		}
   156 		ps.clearWarnings();
   157 	}
   158 
   159 	/**
   160 	 * Tests if this connection is live.
   161 	 *
   162 	 * @return true if test was successful
   163 	 * @throws SQLException if test fails
   164 	 */
   165 	public boolean test() throws SQLException {
   166 		connection.getAutoCommit();
   167 		return true;
   168 	}
   169 
   170 	@Override
   171 	public void close() throws SQLException {
   172 		connection.close();
   173 	}
   174 }