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