com.rapiddweller.jdbacl.DBUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of rd-lib-jdbacl Show documentation
Show all versions of rd-lib-jdbacl Show documentation
'jdbacl' stands for 'Java DataBase ACcess Layer' and provides utilities for accessing JDBC databases from
Java programs, retrieving meta information in an object model and querying database data.
'rapiddweller jdbacl' is forked from Databene jdbacl by Volker Bergmann.
The newest version!
/*
* (c) Copyright 2007-2012 by Volker Bergmann. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, is permitted under the terms of the
* GNU General Public License.
*
* For redistributing this software or a derivative work under a license other
* than the GPL-compatible Free Software License as defined by the Free
* Software Foundation or approved by OSI, you must first obtain a commercial
* license to this software product from Volker Bergmann.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* WITHOUT A WARRANTY OF ANY KIND. ALL EXPRESS OR IMPLIED CONDITIONS,
* REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE
* HEREBY EXCLUDED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.rapiddweller.jdbacl;
import com.rapiddweller.common.ArrayBuilder;
import com.rapiddweller.common.ArrayFormat;
import com.rapiddweller.common.ArrayUtil;
import com.rapiddweller.common.BeanUtil;
import com.rapiddweller.common.ConfigUtil;
import com.rapiddweller.common.ErrorHandler;
import com.rapiddweller.common.HF;
import com.rapiddweller.common.HeavyweightIterator;
import com.rapiddweller.common.IOUtil;
import com.rapiddweller.common.LogCategoriesConstants;
import com.rapiddweller.common.ReaderLineIterator;
import com.rapiddweller.common.StringUtil;
import com.rapiddweller.common.SystemInfo;
import com.rapiddweller.common.converter.AnyConverter;
import com.rapiddweller.common.converter.ToStringConverter;
import com.rapiddweller.common.debug.Debug;
import com.rapiddweller.common.depend.DependencyModel;
import com.rapiddweller.common.exception.ExceptionFactory;
import com.rapiddweller.common.iterator.ConvertingIterator;
import com.rapiddweller.jdbacl.model.DBConstraint;
import com.rapiddweller.jdbacl.model.DBPrimaryKeyConstraint;
import com.rapiddweller.jdbacl.model.DBTable;
import com.rapiddweller.jdbacl.model.DBUniqueConstraint;
import com.rapiddweller.jdbacl.model.TableHolder;
import com.rapiddweller.jdbacl.proxy.LoggingPreparedStatementHandler;
import com.rapiddweller.jdbacl.proxy.LoggingResultSetHandler;
import com.rapiddweller.jdbacl.proxy.LoggingStatementHandler;
import com.rapiddweller.jdbacl.proxy.PooledConnectionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sql.PooledConnection;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.Array;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static com.rapiddweller.jdbacl.SQLUtil.createCatSchTabString;
/**
* Provides database related utility methods.
* Created: 06.01.2007 19:27:02
* @author Volker Bergmann
*/
public class DBUtil {
private static final Logger logger = LoggerFactory.getLogger(DBUtil.class);
private static final Logger jdbcLogger = LoggerFactory.getLogger(LogCategoriesConstants.JDBC);
private static final Logger sqlLogger = LoggerFactory.getLogger(LogCategoriesConstants.SQL);
public static final String ENV_PROPERTIES_SUFFIX = ".env.properties";
public static final String DATABASE_QUERY_FAILED_COLON = "Database query failed: ";
private DBUtil() {
// private constructor for preventing instantiation.
}
// connection handling ---------------------------------------------------------------------------------------------
public static String[] getEnvironmentNames() {
File rapiddwellerFolder = new File(SystemInfo.getUserHome(), "rapiddweller");
String[] fileNames = rapiddwellerFolder.list((dir, name) -> (name.toLowerCase().endsWith(ENV_PROPERTIES_SUFFIX)));
String[] result = new String[Objects.requireNonNull(fileNames).length];
for (int i = 0; i < fileNames.length; i++) {
String fileName = fileNames[i];
result[i] = fileName.substring(0, fileName.length() - ENV_PROPERTIES_SUFFIX.length());
}
return result;
}
/** Determines if a configuration exists for the specified environment.
* Read {@link #environmentFilePath(String, String)} to find out where the
* configuration file is searched. */
public static boolean existsEnvironment(String environment, String folder) {
try {
getConnectData(environment, folder);
return true;
} catch (Exception e) {
return false;
}
}
public static Map getEnvironmentData(String environment, String folder) {
return IOUtil.readProperties(environmentFilePath(environment, folder));
}
public static JDBCConnectData getConnectData(String environment, String folder) {
try {
String path = environmentFilePath(environment, folder);
return JDBCConnectData.parseSingleDbProperties(path);
} catch (IOException e) {
throw ExceptionFactory.getInstance().configurationError("Error reading environment data for '" + environment + "'");
}
}
/**
* Determines the name and location of an environment properties file and provides it as
* canonical path (as defined in java.io.{@link File}).
* It builds the file name and checks, in which folders it is present and
* returns the first match. The search order is
*
* - the directory specified by the 'folder' parameter (which can be absolute or relative)
* - a sub directory 'conf' of the directory specified by the 'folder' parameter
* - the current working directory
* - the directory ${USER_HOME}/rapiddweller
*
*/
public static String environmentFilePath(String environment, String folder) {
String filename = environment + ENV_PROPERTIES_SUFFIX;
return ConfigUtil.configFilePathDefaultLocations(filename, folder);
}
public static Connection connect(String environment, String folder, boolean readOnly) {
JDBCConnectData connectData = DBUtil.getConnectData(environment, folder);
return connect(connectData, readOnly);
}
public static Connection connect(JDBCConnectData data, boolean readOnly) {
if (StringUtil.isEmpty(data.url)) {
throw ExceptionFactory.getInstance().configurationError("No JDBC URL specified");
}
if (StringUtil.isEmpty(data.driver)) {
throw ExceptionFactory.getInstance().configurationError("No JDBC driver class name specified");
}
if (!readOnly && data.readOnly) {
throw ExceptionFactory.getInstance().configurationError("Environment is configured to be read only but was connected for read/write access");
}
return connect(data.url, data.driver, data.user, data.password, readOnly);
}
public static Connection connect(String url, String driverClassName, String user, String password, boolean readOnly) {
try {
if (driverClassName == null) {
throw ExceptionFactory.getInstance().configurationError("No JDBC driver class name provided");
}
// Wrap connection properties
java.util.Properties info = new java.util.Properties();
if (user != null) {
info.put("user", user);
}
if (password != null) {
info.put("password", password);
}
// Instantiate driver
Class driverClass = BeanUtil.forName(driverClassName);
Driver driver = driverClass.getDeclaredConstructor().newInstance();
// connect
jdbcLogger.debug("opening connection to {}", url);
Connection connection = driver.connect(url, info);
if (connection == null) {
throw ExceptionFactory.getInstance().connectFailed("Connecting the database failed silently - " +
"probably due to wrong driver (" + driverClassName + ") or wrong URL format (" + url + ")", null);
}
connection = wrapWithPooledConnection(connection, readOnly);
return connection;
} catch (Exception e) {
throw ExceptionFactory.getInstance().connectFailed("Connect to database at " + url + " failed", e);
}
}
public static boolean available(String url, String driverClass, String user, String password) {
try {
Connection connection = connect(url, driverClass, user, password, false);
close(connection);
return true;
} catch (Exception e) {
return false;
}
}
public static void close(Connection connection) {
if (connection == null) {
return;
}
try {
connection.close();
} catch (SQLException e) {
logger.error("Error closing connection", e);
}
}
public static Connection wrapWithPooledConnection(Connection connection, boolean readOnly) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
return (Connection) Proxy.newProxyInstance(classLoader,
new Class[] {Connection.class, PooledConnection.class},
new PooledConnectionHandler(connection, readOnly));
}
public static int getOpenConnectionCount() {
return PooledConnectionHandler.getOpenConnectionCount();
}
public static void resetMonitors() {
LoggingPreparedStatementHandler.resetMonitors();
LoggingResultSetHandler.resetMonitors();
LoggingStatementHandler.resetMonitors();
PooledConnectionHandler.resetMonitors();
}
// statement handling ----------------------------------------------------------------------------------------------
public static Statement createLoggingStatementHandler(Statement statement, boolean readOnly) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
statement = (Statement) Proxy.newProxyInstance(classLoader,
new Class[] {Statement.class},
new LoggingStatementHandler(statement, readOnly));
return statement;
}
public static PreparedStatement prepareStatement(Connection connection, String sql, boolean readOnly) throws SQLException {
return prepareStatement(connection, sql, readOnly,
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT);
}
public static PreparedStatement prepareStatement(
Connection connection,
String sql,
boolean readOnly,
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
jdbcLogger.debug("preparing statement: {}", sql);
checkReadOnly(sql, readOnly);
if (connection instanceof PooledConnection) {
connection = ((PooledConnection) connection).getConnection();
}
int _resultSetHoldability = connection.getMetaData().getResultSetHoldability();
PreparedStatement statement = connection.prepareStatement(
sql, resultSetType, resultSetConcurrency, _resultSetHoldability);
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (sqlLogger.isDebugEnabled() || jdbcLogger.isDebugEnabled()) {
statement = (PreparedStatement) Proxy.newProxyInstance(classLoader,
new Class[] {PreparedStatement.class},
new LoggingPreparedStatementHandler(statement, sql));
}
return statement;
}
public static void close(Statement statement) {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
throw ExceptionFactory.getInstance().configurationError("Closing statement failed", e);
}
}
}
public static int getOpenStatementCount() {
return LoggingStatementHandler.getOpenStatementCount();
}
public static int getOpenPreparedStatementCount() {
return LoggingPreparedStatementHandler.getOpenStatementCount();
}
// ResultSet handling ----------------------------------------------------------------------------------------------
public static ResultSet createLoggingResultSet(ResultSet realResultSet, Statement statement) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
return (ResultSet) Proxy.newProxyInstance(classLoader,
new Class[] {ResultSet.class},
new LoggingResultSetHandler(realResultSet, statement));
}
public static Statement getStatement(ResultSet resultSet) {
try {
return resultSet.getStatement();
} catch (SQLException e) {
throw ExceptionFactory.getInstance().operationFailed("Error getting statement from result set", e);
}
}
public static void close(ResultSet resultSet) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
throw ExceptionFactory.getInstance().operationFailed("Closing statement failed", e);
}
}
}
public static void closeResultSetAndStatement(ResultSet resultSet) {
if (resultSet != null) {
closeResultSetAndStatement(resultSet, getStatement(resultSet));
}
}
public static void closeResultSetAndStatement(ResultSet resultSet, Statement statement) {
if (resultSet != null) {
try {
close(resultSet);
} finally {
close(statement);
}
} else {
close(statement);
}
}
public static int getOpenResultSetCount() {
// if -1 return 0
int openResultSetCount = LoggingResultSetHandler.getOpenResultSetCount();
return Math.max(openResultSetCount, 0);
}
public static Object parseAndSimplifyResultSet(ResultSet resultSet) throws SQLException {
List