java/sql-dk/src/info/globalcode/sql/dk/DatabaseConnection.java
author František Kučera <franta-hg@frantovo.cz>
Wed, 09 Nov 2016 00:18:01 +0100
branchv_0
changeset 229 7699133f5a01
parent 192 a32bfcbdee51
permissions -rw-r--r--
InfoLister/test: show also database server name and version
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@192
    25
import info.globalcode.sql.dk.configuration.Loader;
franta-hg@106
    26
import info.globalcode.sql.dk.configuration.Properties;
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@29
    32
import java.sql.PreparedStatement;
franta-hg@29
    33
import java.sql.ResultSet;
franta-hg@28
    34
import java.sql.SQLException;
franta-hg@86
    35
import java.sql.SQLWarning;
franta-hg@55
    36
import java.util.logging.Level;
franta-hg@55
    37
import java.util.logging.Logger;
franta-hg@26
    38
franta-hg@26
    39
/**
franta-hg@155
    40
 * Represents connected database. Is derived from {@linkplain DatabaseDefinition}.
franta-hg@155
    41
 * Wraps {@linkplain Connection}.
franta-hg@155
    42
 *
franta-hg@155
    43
 * Is responsible for executing {@linkplain SQLCommand} and passing results to the
franta-hg@155
    44
 * {@linkplain Formatter}.
franta-hg@26
    45
 *
franta-hg@26
    46
 * @author Ing. František Kučera (frantovo.cz)
franta-hg@26
    47
 */
franta-hg@42
    48
public class DatabaseConnection implements AutoCloseable {
franta-hg@26
    49
franta-hg@55
    50
	private static final Logger log = Logger.getLogger(DatabaseConnection.class.getName());
franta-hg@192
    51
	public static final String JDBC_PROPERTY_USER = "user";
franta-hg@108
    52
	public static final String JDBC_PROPERTY_PASSWORD = "password";
franta-hg@178
    53
	private final DatabaseDefinition databaseDefinition;
franta-hg@178
    54
	private final Connection connection;
franta-hg@178
    55
	private final Properties properties;
franta-hg@179
    56
	/**
franta-hg@179
    57
	 * Could be null = JMX is disabled → must check, see functions in
franta-hg@179
    58
	 * {@linkplain ConnectionManagement}
franta-hg@179
    59
	 */
franta-hg@179
    60
	private final ConnectionManagement connectionMBean;
franta-hg@26
    61
franta-hg@179
    62
	/**
franta-hg@179
    63
	 *
franta-hg@179
    64
	 * @param databaseDefinition DB url, name, password etc.
franta-hg@179
    65
	 * @param properties additional properties from CLI
franta-hg@179
    66
	 * @param connectionMBean JMX management bean | null = disabled JMX reporting
franta-hg@179
    67
	 * @throws SQLException
franta-hg@179
    68
	 */
franta-hg@179
    69
	public DatabaseConnection(DatabaseDefinition databaseDefinition, Properties properties, ConnectionManagement connectionMBean) throws SQLException {
franta-hg@26
    70
		this.databaseDefinition = databaseDefinition;
franta-hg@106
    71
		this.properties = properties;
franta-hg@179
    72
		this.connectionMBean = connectionMBean;
franta-hg@192
    73
		this.connection = Loader.jdbcConnect(databaseDefinition, properties);
franta-hg@26
    74
	}
franta-hg@29
    75
franta-hg@29
    76
	public void executeQuery(SQLCommand sqlCommand, Formatter formatter) throws SQLException {
franta-hg@91
    77
		formatter.writeStartBatch();
franta-hg@29
    78
		formatter.writeStartDatabase(databaseDefinition);
franta-hg@142
    79
		formatter.writeStartStatement();
franta-hg@142
    80
		formatter.writeQuery(sqlCommand.getQuery());
franta-hg@142
    81
		formatter.writeParameters(sqlCommand.getParameters());
franta-hg@29
    82
		processCommand(sqlCommand, formatter);
franta-hg@142
    83
		formatter.writeEndStatement();
franta-hg@29
    84
		formatter.writeEndDatabase();
franta-hg@91
    85
		formatter.writeEndBatch();
franta-hg@29
    86
	}
franta-hg@29
    87
franta-hg@146
    88
	public void executeBatch(Batch batch, Formatter formatter) throws SQLException, BatchException {
franta-hg@91
    89
		formatter.writeStartBatch();
franta-hg@29
    90
		formatter.writeStartDatabase(databaseDefinition);
franta-hg@29
    91
		while (batch.hasNext()) {
franta-hg@142
    92
			SQLCommand sqlCommand = batch.next();
franta-hg@142
    93
			formatter.writeStartStatement();
franta-hg@142
    94
			formatter.writeQuery(sqlCommand.getQuery());
franta-hg@142
    95
			formatter.writeParameters(sqlCommand.getParameters());
franta-hg@142
    96
			processCommand(sqlCommand, formatter);
franta-hg@142
    97
			formatter.writeEndStatement();
franta-hg@29
    98
		}
franta-hg@29
    99
		formatter.writeEndDatabase();
franta-hg@91
   100
		formatter.writeEndBatch();
franta-hg@29
   101
	}
franta-hg@29
   102
franta-hg@29
   103
	private void processCommand(SQLCommand sqlCommand, Formatter formatter) throws SQLException {
franta-hg@179
   104
		incrementCounter(connectionMBean, COUNTER.COMMAND);
franta-hg@179
   105
		resetCounter(connectionMBean, COUNTER.RECORD_CURRENT);
franta-hg@192
   106
franta-hg@29
   107
		try (PreparedStatement ps = sqlCommand.prepareStatement(connection)) {
franta-hg@55
   108
			log.log(Level.FINE, "Statement prepared");
franta-hg@29
   109
			sqlCommand.parametrize(ps);
franta-hg@35
   110
franta-hg@35
   111
			boolean isRS = ps.execute();
franta-hg@55
   112
			log.log(Level.FINE, "Statement executed");
franta-hg@35
   113
			if (isRS) {
franta-hg@35
   114
				try (ResultSet rs = ps.getResultSet()) {
franta-hg@142
   115
					processResultSet(rs, formatter);
franta-hg@35
   116
				}
franta-hg@35
   117
			} else {
franta-hg@142
   118
				processUpdateResult(ps, formatter);
franta-hg@35
   119
			}
franta-hg@86
   120
			logWarnings(ps);
franta-hg@35
   121
franta-hg@35
   122
			while (ps.getMoreResults() || ps.getUpdateCount() > -1) {
franta-hg@37
   123
				ResultSet rs = ps.getResultSet();
franta-hg@37
   124
				if (rs == null) {
franta-hg@142
   125
					processUpdateResult(ps, formatter);
franta-hg@37
   126
				} else {
franta-hg@142
   127
					processResultSet(rs, formatter);
franta-hg@37
   128
					rs.close();
franta-hg@37
   129
				}
franta-hg@86
   130
				logWarnings(ps);
franta-hg@29
   131
			}
franta-hg@29
   132
		}
franta-hg@37
   133
	}
franta-hg@37
   134
franta-hg@142
   135
	private void processUpdateResult(PreparedStatement ps, Formatter formatter) throws SQLException {
franta-hg@142
   136
		formatter.writeUpdatesResult(ps.getUpdateCount());
franta-hg@37
   137
	}
franta-hg@37
   138
franta-hg@142
   139
	private void processResultSet(ResultSet rs, Formatter formatter) throws SQLException {
franta-hg@142
   140
		formatter.writeStartResultSet(new ColumnsHeader(rs.getMetaData()));
franta-hg@37
   141
franta-hg@34
   142
		int columnCount = rs.getMetaData().getColumnCount();
franta-hg@34
   143
franta-hg@29
   144
		while (rs.next()) {
franta-hg@179
   145
			incrementCounter(connectionMBean, COUNTER.RECORD_CURRENT);
franta-hg@179
   146
			incrementCounter(connectionMBean, COUNTER.RECORD_TOTAL);
franta-hg@192
   147
franta-hg@29
   148
			formatter.writeStartRow();
franta-hg@29
   149
franta-hg@34
   150
			for (int i = 1; i <= columnCount; i++) {
franta-hg@34
   151
				formatter.writeColumnValue(rs.getObject(i));
franta-hg@34
   152
			}
franta-hg@34
   153
franta-hg@29
   154
			formatter.writeEndRow();
franta-hg@29
   155
		}
franta-hg@34
   156
franta-hg@142
   157
		formatter.writeEndResultSet();
franta-hg@29
   158
	}
franta-hg@42
   159
franta-hg@86
   160
	private void logWarnings(PreparedStatement ps) throws SQLException {
franta-hg@86
   161
		SQLWarning w = ps.getWarnings();
franta-hg@86
   162
		while (w != null) {
franta-hg@86
   163
			log.log(Level.WARNING, "SQL: {0}", w.getLocalizedMessage());
franta-hg@86
   164
			w = w.getNextWarning();
franta-hg@86
   165
		}
franta-hg@86
   166
		ps.clearWarnings();
franta-hg@86
   167
	}
franta-hg@86
   168
franta-hg@65
   169
	/**
franta-hg@65
   170
	 * Tests if this connection is live.
franta-hg@65
   171
	 *
franta-hg@65
   172
	 * @return true if test was successful
franta-hg@65
   173
	 * @throws SQLException if test fails
franta-hg@65
   174
	 */
franta-hg@65
   175
	public boolean test() throws SQLException {
franta-hg@65
   176
		connection.getAutoCommit();
franta-hg@65
   177
		return true;
franta-hg@65
   178
	}
franta-hg@65
   179
franta-hg@229
   180
	public String getProductName() throws SQLException {
franta-hg@229
   181
		return connection.getMetaData().getDatabaseProductName();
franta-hg@229
   182
	}
franta-hg@229
   183
franta-hg@229
   184
	public String getProductVersion() throws SQLException {
franta-hg@229
   185
		return connection.getMetaData().getDatabaseProductVersion();
franta-hg@229
   186
	}
franta-hg@229
   187
franta-hg@42
   188
	@Override
franta-hg@42
   189
	public void close() throws SQLException {
franta-hg@42
   190
		connection.close();
franta-hg@42
   191
	}
franta-hg@26
   192
}