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