java/sql-dk/src/main/java/info/globalcode/sql/dk/DatabaseConnection.java
author František Kučera <franta-hg@frantovo.cz>
Sat, 25 Jul 2020 17:25:19 +0200
branchv_0
changeset 252 a9d4a8d5c57f
parent 250 aae5009bd0af
permissions -rw-r--r--
improve multiple results support

The specification talks exactly about -1:
> Returns: the current result as an update count;
> -1 if the current result is a ResultSet object or there are no more results

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