DatabaseConnection.java

  1. /*
  2.  *
  3.  * The DbUnit Database Testing Framework
  4.  * Copyright (C)2002-2004, DbUnit.org
  5.  *
  6.  * This library is free software; you can redistribute it and/or
  7.  * modify it under the terms of the GNU Lesser General Public
  8.  * License as published by the Free Software Foundation; either
  9.  * version 2.1 of the License, or (at your option) any later version.
  10.  *
  11.  * This library is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  14.  * Lesser General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU Lesser General Public
  17.  * License along with this library; if not, write to the Free Software
  18.  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  19.  *
  20.  */

  21. package org.dbunit.database;

  22. import java.sql.Connection;
  23. import java.sql.SQLException;

  24. import org.dbunit.DatabaseUnitException;
  25. import org.dbunit.util.SQLHelper;
  26. import org.slf4j.Logger;
  27. import org.slf4j.LoggerFactory;

  28. /**
  29.  * This class adapts a JDBC <code>Connection</code> to a
  30.  * {@link IDatabaseConnection}.
  31.  *
  32.  * @author Manuel Laflamme
  33.  * @version $Revision$
  34.  * @since Feb 21, 2002
  35.  */
  36. public class DatabaseConnection extends AbstractDatabaseConnection
  37.         implements IDatabaseConnection
  38. {

  39.     /**
  40.      * Logger for this class
  41.      */
  42.     private static final Logger logger = LoggerFactory.getLogger(DatabaseConnection.class);

  43.     private final Connection _connection;
  44.     private final String _schema;

  45.     /**
  46.      * Creates a new <code>DatabaseConnection</code>.
  47.      *
  48.      * @param connection the adapted JDBC connection
  49.      * @throws DatabaseUnitException
  50.      */
  51.     public DatabaseConnection(Connection connection) throws DatabaseUnitException
  52.     {
  53.       this( connection, null );
  54.     }

  55.     /**
  56.      * Creates a new <code>DatabaseConnection</code> using a specific schema.
  57.      *
  58.      * @param connection the adapted JDBC connection
  59.      * @param schema the database schema. Note that the schema name is case sensitive. This
  60.      * is necessary because schemas with the same name but different case can coexist on one
  61.      * database. <br>
  62.      * Here an example that creates two users/schemas for oracle where only the case is different:<br>
  63.      * <code>
  64.      * create user dbunittest identified by dbunittest;
  65.      * create user "dbunittest" identified by "dbunittest";
  66.      * </code>
  67.      * The first one creates the "default" user where everything is interpreted by oracle in uppercase.
  68.      * The second one is completely lowercase because of the quotes.
  69.      * @throws DatabaseUnitException
  70.      */
  71.     public DatabaseConnection(Connection connection, String schema) throws DatabaseUnitException
  72.     {
  73.         this(connection, schema, false);
  74.     }

  75.     /**
  76.      * Creates a new <code>DatabaseConnection</code> using a specific schema.
  77.      *
  78.      * @param connection the adapted JDBC connection
  79.      * @param schema the database schema. Note that the schema name is case sensitive. This
  80.      * is necessary because schemas with the same name but different case can coexist on one
  81.      * database. <br>
  82.      * Here an example that creates two users/schemas for oracle where only the case is different:<br>
  83.      * <code>
  84.      * create user dbunittest identified by dbunittest;
  85.      * create user "dbunittest" identified by "dbunittest";
  86.      * </code>
  87.      * The first one creates the "default" user where everything is interpreted by oracle in uppercase.
  88.      * The second one is completely lowercase because of the quotes.
  89.      * @param validate If <code>true</code> an exception is thrown when the given schema
  90.      * does not exist according to the DatabaseMetaData. If <code>false</code> the validation
  91.      * will only print a warning if the schema was not found.
  92.      * @since 2.3.0
  93.      * @throws DatabaseUnitException If the <code>validate</code> parameter is <code>true</code> and the
  94.      * validation of the given connection/schema was not successful (added with 2.3.0). This can happen if the given
  95.      * schema does not exist or if the jdbc driver does not implement the metaData.getSchemas() method properly.
  96.      */
  97.     public DatabaseConnection(Connection connection, String schema, boolean validate) throws DatabaseUnitException
  98.     {
  99.         if(connection == null)
  100.         {
  101.             throw new NullPointerException("The parameter 'connection' must not be null");
  102.         }
  103.         _connection = connection;
  104.        
  105.         if(schema != null)
  106.         {
  107.             _schema = SQLHelper.correctCase(schema, connection);
  108.             SQLHelper.logInfoIfValueChanged(schema, _schema, "Corrected schema name:", DatabaseConnection.class);
  109.         }
  110.         else
  111.         {
  112.             _schema = null;
  113.         }

  114.         printConnectionInfo();
  115.         validateSchema(validate);
  116.     }

  117.     ////////////////////////////////////////////////////////////////////////////
  118.     // IDatabaseConnection interface

  119.     public Connection getConnection() throws SQLException
  120.     {
  121.         return _connection;
  122.     }

  123.     public String getSchema()
  124.     {
  125.         return _schema;
  126.     }

  127.     public void close() throws SQLException
  128.     {
  129.         logger.debug("close() - start");
  130.         _connection.close();
  131.     }
  132.    
  133.    
  134.     /**
  135.      * Prints debugging information about the current JDBC connection
  136.      */
  137.     private void printConnectionInfo()
  138.     {
  139.         if(logger.isDebugEnabled())
  140.         {
  141.             try {
  142.                 logger.debug("Database connection info: " + SQLHelper.getDatabaseInfo(_connection.getMetaData()));
  143.             }
  144.             catch (SQLException e) {
  145.                 logger.warn("Exception while trying to retrieve database info from connection", e);
  146.             }
  147.         }
  148.     }

  149.     /**
  150.      * Validates if the database schema exists for this connection.
  151.      * @param validateStrict If <code>true</code> an exception is thrown when the given schema
  152.      * does not exist according to the DatabaseMetaData. If <code>false</code> the validation
  153.      * will only print a warning if the schema was not found.
  154.      * @throws DatabaseUnitException
  155.      */
  156.     private void validateSchema(boolean validateStrict) throws DatabaseUnitException
  157.     {
  158.         logger.debug("validateSchema(validateStrict={}) - start", validateStrict);
  159.        
  160.         if(this._schema == null)
  161.         {
  162.             logger.debug("Schema is null. Nothing to validate.");
  163.             return;
  164.         }
  165.        
  166.         try
  167.         {
  168.             boolean schemaExists = SQLHelper.schemaExists(this._connection, this._schema);
  169.             if(!schemaExists)
  170.             {
  171.                 // Under certain circumstances the cause might be that the JDBC driver
  172.                 // implementation of 'DatabaseMetaData.getSchemas()' is not correct
  173.                 // (known issue of MySQL driver).
  174.                 String msg = "The given schema '" + this._schema + "' does not exist.";
  175.                 // If strict validation is wished throw an exception
  176.                 if(validateStrict)
  177.                     throw new DatabaseUnitException(msg);
  178.                 else
  179.                     logger.warn(msg);
  180.             }
  181.         }
  182.         catch(SQLException e)
  183.         {
  184.             throw new DatabaseUnitException("Exception while checking the schema for validity", e);
  185.         }
  186.     }
  187.    
  188.     public String toString()
  189.     {
  190.         final StringBuilder sb = new StringBuilder();
  191.         sb.append(getClass().getName()).append("[");
  192.         sb.append("schema=").append(_schema);
  193.         sb.append(", connection=").append(_connection);
  194.         sb.append(", super=").append(super.toString());
  195.         sb.append("]");
  196.         return sb.toString();
  197.     }
  198. }