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