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