java/sql-dk/src/info/globalcode/sql/dk/DatabaseConnection.java
author František Kučera <franta-hg@frantovo.cz>
Sat, 16 May 2015 21:42:52 +0200
branchv_0
changeset 189 f4d879cbcee1
parent 179 236332caeb29
child 192 a32bfcbdee51
permissions -rw-r--r--
separate configuration loading into the Loader class
franta-hg@26
     1
/**
franta-hg@26
     2
 * SQL-DK
franta-hg@26
     3
 * Copyright © 2013 František Kučera (frantovo.cz)
franta-hg@26
     4
 *
franta-hg@26
     5
 * This program is free software: you can redistribute it and/or modify
franta-hg@26
     6
 * it under the terms of the GNU General Public License as published by
franta-hg@26
     7
 * the Free Software Foundation, either version 3 of the License, or
franta-hg@26
     8
 * (at your option) any later version.
franta-hg@26
     9
 *
franta-hg@26
    10
 * This program is distributed in the hope that it will be useful,
franta-hg@26
    11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
franta-hg@26
    12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
franta-hg@26
    13
 * GNU General Public License for more details.
franta-hg@26
    14
 *
franta-hg@26
    15
 * You should have received a copy of the GNU General Public License
franta-hg@26
    16
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
franta-hg@26
    17
 */
franta-hg@27
    18
package info.globalcode.sql.dk;
franta-hg@27
    19
franta-hg@179
    20
import static info.globalcode.sql.dk.jmx.ConnectionManagement.incrementCounter;
franta-hg@179
    21
import static info.globalcode.sql.dk.jmx.ConnectionManagement.resetCounter;
franta-hg@29
    22
import info.globalcode.sql.dk.batch.Batch;
franta-hg@146
    23
import info.globalcode.sql.dk.batch.BatchException;
franta-hg@27
    24
import info.globalcode.sql.dk.configuration.DatabaseDefinition;
franta-hg@106
    25
import info.globalcode.sql.dk.configuration.Properties;
franta-hg@107
    26
import info.globalcode.sql.dk.configuration.Property;
franta-hg@34
    27
import info.globalcode.sql.dk.formatting.ColumnsHeader;
franta-hg@29
    28
import info.globalcode.sql.dk.formatting.Formatter;
franta-hg@179
    29
import info.globalcode.sql.dk.jmx.ConnectionManagement;
franta-hg@179
    30
import info.globalcode.sql.dk.jmx.ConnectionManagement.COUNTER;
franta-hg@28
    31
import java.sql.Connection;
franta-hg@28
    32
import java.sql.DriverManager;
franta-hg@29
    33
import java.sql.PreparedStatement;
franta-hg@29
    34
import java.sql.ResultSet;
franta-hg@28
    35
import java.sql.SQLException;
franta-hg@86
    36
import java.sql.SQLWarning;
franta-hg@55
    37
import java.util.logging.Level;
franta-hg@55
    38
import java.util.logging.Logger;
franta-hg@26
    39
franta-hg@26
    40
/**
franta-hg@155
    41
 * Represents connected database. Is derived from {@linkplain DatabaseDefinition}.
franta-hg@155
    42
 * Wraps {@linkplain Connection}.
franta-hg@155
    43
 *
franta-hg@155
    44
 * Is responsible for executing {@linkplain SQLCommand} and passing results to the
franta-hg@155
    45
 * {@linkplain Formatter}.
franta-hg@26
    46
 *
franta-hg@26
    47
 * @author Ing. František Kučera (frantovo.cz)
franta-hg@26
    48
 */
franta-hg@42
    49
public class DatabaseConnection implements AutoCloseable {
franta-hg@26
    50
franta-hg@55
    51
	private static final Logger log = Logger.getLogger(DatabaseConnection.class.getName());
franta-hg@108
    52
	private static final String JDBC_PROPERTY_USER = "user";
franta-hg@108
    53
	public static final String JDBC_PROPERTY_PASSWORD = "password";
franta-hg@178
    54
	private final DatabaseDefinition databaseDefinition;
franta-hg@178
    55
	private final Connection connection;
franta-hg@178
    56
	private final Properties properties;
franta-hg@179
    57
	/**
franta-hg@179
    58
	 * Could be null = JMX is disabled → must check, see functions in
franta-hg@179
    59
	 * {@linkplain ConnectionManagement}
franta-hg@179
    60
	 */
franta-hg@179
    61
	private final ConnectionManagement connectionMBean;
franta-hg@26
    62
franta-hg@179
    63
	/**
franta-hg@179
    64
	 *
franta-hg@179
    65
	 * @param databaseDefinition DB url, name, password etc.
franta-hg@179
    66
	 * @param properties additional properties from CLI
franta-hg@179
    67
	 * @param connectionMBean JMX management bean | null = disabled JMX reporting
franta-hg@179
    68
	 * @throws SQLException
franta-hg@179
    69
	 */
franta-hg@179
    70
	public DatabaseConnection(DatabaseDefinition databaseDefinition, Properties properties, ConnectionManagement connectionMBean) throws SQLException {
franta-hg@26
    71
		this.databaseDefinition = databaseDefinition;
franta-hg@106
    72
		this.properties = properties;
franta-hg@179
    73
		this.connectionMBean = connectionMBean;
franta-hg@28
    74
franta-hg@108
    75
		if (properties.hasProperty(JDBC_PROPERTY_PASSWORD)) {
franta-hg@108
    76
			log.log(Level.WARNING, "Passing DB password as CLI parameter is insecure!");
franta-hg@108
    77
		}
franta-hg@108
    78
franta-hg@107
    79
		Properties credentials = new Properties();
franta-hg@108
    80
		credentials.add(new Property(JDBC_PROPERTY_USER, databaseDefinition.getUserName()));
franta-hg@108
    81
		credentials.add(new Property(JDBC_PROPERTY_PASSWORD, databaseDefinition.getPassword()));
franta-hg@107
    82
		credentials.setDefaults(databaseDefinition.getProperties());
franta-hg@107
    83
		properties.setDefaults(credentials);
franta-hg@106
    84
		java.util.Properties javaProperties = properties.getJavaProperties();
franta-hg@106
    85
franta-hg@106
    86
		connection = DriverManager.getConnection(databaseDefinition.getUrl(), javaProperties);
franta-hg@26
    87
	}
franta-hg@29
    88
franta-hg@29
    89
	public void executeQuery(SQLCommand sqlCommand, Formatter formatter) throws SQLException {
franta-hg@91
    90
		formatter.writeStartBatch();
franta-hg@29
    91
		formatter.writeStartDatabase(databaseDefinition);
franta-hg@142
    92
		formatter.writeStartStatement();
franta-hg@142
    93
		formatter.writeQuery(sqlCommand.getQuery());
franta-hg@142
    94
		formatter.writeParameters(sqlCommand.getParameters());
franta-hg@29
    95
		processCommand(sqlCommand, formatter);
franta-hg@142
    96
		formatter.writeEndStatement();
franta-hg@29
    97
		formatter.writeEndDatabase();
franta-hg@91
    98
		formatter.writeEndBatch();
franta-hg@29
    99
	}
franta-hg@29
   100
franta-hg@146
   101
	public void executeBatch(Batch batch, Formatter formatter) throws SQLException, BatchException {
franta-hg@91
   102
		formatter.writeStartBatch();
franta-hg@29
   103
		formatter.writeStartDatabase(databaseDefinition);
franta-hg@29
   104
		while (batch.hasNext()) {
franta-hg@142
   105
			SQLCommand sqlCommand = batch.next();
franta-hg@142
   106
			formatter.writeStartStatement();
franta-hg@142
   107
			formatter.writeQuery(sqlCommand.getQuery());
franta-hg@142
   108
			formatter.writeParameters(sqlCommand.getParameters());
franta-hg@142
   109
			processCommand(sqlCommand, formatter);
franta-hg@142
   110
			formatter.writeEndStatement();
franta-hg@29
   111
		}
franta-hg@29
   112
		formatter.writeEndDatabase();
franta-hg@91
   113
		formatter.writeEndBatch();
franta-hg@29
   114
	}
franta-hg@29
   115
franta-hg@29
   116
	private void processCommand(SQLCommand sqlCommand, Formatter formatter) throws SQLException {
franta-hg@179
   117
		incrementCounter(connectionMBean, COUNTER.COMMAND);
franta-hg@179
   118
		resetCounter(connectionMBean, COUNTER.RECORD_CURRENT);
franta-hg@179
   119
		
franta-hg@29
   120
		try (PreparedStatement ps = sqlCommand.prepareStatement(connection)) {
franta-hg@55
   121
			log.log(Level.FINE, "Statement prepared");
franta-hg@29
   122
			sqlCommand.parametrize(ps);
franta-hg@35
   123
franta-hg@35
   124
			boolean isRS = ps.execute();
franta-hg@55
   125
			log.log(Level.FINE, "Statement executed");
franta-hg@35
   126
			if (isRS) {
franta-hg@35
   127
				try (ResultSet rs = ps.getResultSet()) {
franta-hg@142
   128
					processResultSet(rs, formatter);
franta-hg@35
   129
				}
franta-hg@35
   130
			} else {
franta-hg@142
   131
				processUpdateResult(ps, formatter);
franta-hg@35
   132
			}
franta-hg@86
   133
			logWarnings(ps);
franta-hg@35
   134
franta-hg@35
   135
			while (ps.getMoreResults() || ps.getUpdateCount() > -1) {
franta-hg@37
   136
				ResultSet rs = ps.getResultSet();
franta-hg@37
   137
				if (rs == null) {
franta-hg@142
   138
					processUpdateResult(ps, formatter);
franta-hg@37
   139
				} else {
franta-hg@142
   140
					processResultSet(rs, formatter);
franta-hg@37
   141
					rs.close();
franta-hg@37
   142
				}
franta-hg@86
   143
				logWarnings(ps);
franta-hg@29
   144
			}
franta-hg@29
   145
		}
franta-hg@37
   146
	}
franta-hg@37
   147
franta-hg@142
   148
	private void processUpdateResult(PreparedStatement ps, Formatter formatter) throws SQLException {
franta-hg@142
   149
		formatter.writeUpdatesResult(ps.getUpdateCount());
franta-hg@37
   150
	}
franta-hg@37
   151
franta-hg@142
   152
	private void processResultSet(ResultSet rs, Formatter formatter) throws SQLException {
franta-hg@142
   153
		formatter.writeStartResultSet(new ColumnsHeader(rs.getMetaData()));
franta-hg@37
   154
franta-hg@34
   155
		int columnCount = rs.getMetaData().getColumnCount();
franta-hg@34
   156
franta-hg@29
   157
		while (rs.next()) {
franta-hg@179
   158
			incrementCounter(connectionMBean, COUNTER.RECORD_CURRENT);
franta-hg@179
   159
			incrementCounter(connectionMBean, COUNTER.RECORD_TOTAL);
franta-hg@179
   160
			
franta-hg@29
   161
			formatter.writeStartRow();
franta-hg@29
   162
franta-hg@34
   163
			for (int i = 1; i <= columnCount; i++) {
franta-hg@34
   164
				formatter.writeColumnValue(rs.getObject(i));
franta-hg@34
   165
			}
franta-hg@34
   166
franta-hg@29
   167
			formatter.writeEndRow();
franta-hg@29
   168
		}
franta-hg@34
   169
franta-hg@142
   170
		formatter.writeEndResultSet();
franta-hg@29
   171
	}
franta-hg@42
   172
franta-hg@86
   173
	private void logWarnings(PreparedStatement ps) throws SQLException {
franta-hg@86
   174
		SQLWarning w = ps.getWarnings();
franta-hg@86
   175
		while (w != null) {
franta-hg@86
   176
			log.log(Level.WARNING, "SQL: {0}", w.getLocalizedMessage());
franta-hg@86
   177
			w = w.getNextWarning();
franta-hg@86
   178
		}
franta-hg@86
   179
		ps.clearWarnings();
franta-hg@86
   180
	}
franta-hg@86
   181
franta-hg@65
   182
	/**
franta-hg@65
   183
	 * Tests if this connection is live.
franta-hg@65
   184
	 *
franta-hg@65
   185
	 * @return true if test was successful
franta-hg@65
   186
	 * @throws SQLException if test fails
franta-hg@65
   187
	 */
franta-hg@65
   188
	public boolean test() throws SQLException {
franta-hg@65
   189
		connection.getAutoCommit();
franta-hg@65
   190
		return true;
franta-hg@65
   191
	}
franta-hg@65
   192
franta-hg@42
   193
	@Override
franta-hg@42
   194
	public void close() throws SQLException {
franta-hg@42
   195
		connection.close();
franta-hg@42
   196
	}
franta-hg@26
   197
}