java/sql-dk/src/info/globalcode/sql/dk/DatabaseConnection.java
author František Kučera <franta-hg@frantovo.cz>
Thu, 02 Jan 2014 19:59:33 +0100
branchv_0
changeset 113 575a8c6b91ad
parent 108 d06d90b28217
child 142 da1e38386d84
permissions -rw-r--r--
Relax NG schema for XML configuration
     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 		processCommand(sqlCommand, formatter);
    70 		formatter.writeEndDatabase();
    71 		formatter.writeEndBatch();
    72 	}
    73 
    74 	public void executeBatch(Batch batch, Formatter formatter) throws SQLException {
    75 		formatter.writeStartBatch();
    76 		formatter.writeStartDatabase(databaseDefinition);
    77 		while (batch.hasNext()) {
    78 			processCommand(batch.next(), formatter);
    79 		}
    80 		formatter.writeEndDatabase();
    81 		formatter.writeEndBatch();
    82 	}
    83 
    84 	private void processCommand(SQLCommand sqlCommand, Formatter formatter) throws SQLException {
    85 		try (PreparedStatement ps = sqlCommand.prepareStatement(connection)) {
    86 			log.log(Level.FINE, "Statement prepared");
    87 			sqlCommand.parametrize(ps);
    88 
    89 			boolean isRS = ps.execute();
    90 			log.log(Level.FINE, "Statement executed");
    91 			if (isRS) {
    92 				try (ResultSet rs = ps.getResultSet()) {
    93 					processResultSet(sqlCommand, rs, formatter);
    94 				}
    95 			} else {
    96 				processUpdateResult(sqlCommand, ps, formatter);
    97 			}
    98 			logWarnings(ps);
    99 
   100 			while (ps.getMoreResults() || ps.getUpdateCount() > -1) {
   101 				ResultSet rs = ps.getResultSet();
   102 				if (rs == null) {
   103 					processUpdateResult(sqlCommand, ps, formatter);
   104 				} else {
   105 					processResultSet(sqlCommand, rs, formatter);
   106 					rs.close();
   107 				}
   108 				logWarnings(ps);
   109 			}
   110 		}
   111 	}
   112 
   113 	private void processUpdateResult(SQLCommand sqlCommand, PreparedStatement ps, Formatter formatter) throws SQLException {
   114 		formatter.writeStartUpdatesResult();
   115 		formatter.writeQuery(sqlCommand.getQuery());
   116 		formatter.writeParameters(sqlCommand.getParameters());
   117 		formatter.writeUpdatedRowsCount(ps.getUpdateCount());
   118 		formatter.writeEndUpdatesResult();
   119 	}
   120 
   121 	private void processResultSet(SQLCommand sqlCommand, ResultSet rs, Formatter formatter) throws SQLException {
   122 		formatter.writeStartResultSet();
   123 		formatter.writeQuery(sqlCommand.getQuery());
   124 		formatter.writeParameters(sqlCommand.getParameters());
   125 
   126 		processResultSetRows(rs, formatter);
   127 
   128 		formatter.writeEndResultSet();
   129 	}
   130 
   131 	private void processResultSetRows(ResultSet rs, Formatter formatter) throws SQLException {
   132 		formatter.writeColumnsHeader(new ColumnsHeader(rs.getMetaData()));
   133 		int columnCount = rs.getMetaData().getColumnCount();
   134 
   135 		while (rs.next()) {
   136 			formatter.writeStartRow();
   137 
   138 			for (int i = 1; i <= columnCount; i++) {
   139 				formatter.writeColumnValue(rs.getObject(i));
   140 			}
   141 
   142 			formatter.writeEndRow();
   143 		}
   144 
   145 	}
   146 
   147 	private void logWarnings(PreparedStatement ps) throws SQLException {
   148 		SQLWarning w = ps.getWarnings();
   149 		while (w != null) {
   150 			log.log(Level.WARNING, "SQL: {0}", w.getLocalizedMessage());
   151 			w = w.getNextWarning();
   152 		}
   153 		ps.clearWarnings();
   154 	}
   155 
   156 	/**
   157 	 * Tests if this connection is live.
   158 	 *
   159 	 * @return true if test was successful
   160 	 * @throws SQLException if test fails
   161 	 */
   162 	public boolean test() throws SQLException {
   163 		connection.getAutoCommit();
   164 		return true;
   165 	}
   166 
   167 	@Override
   168 	public void close() throws SQLException {
   169 		connection.close();
   170 	}
   171 }