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