Advertisement
Guest User

LiquibaseUtilityClass

a guest
Mar 3rd, 2016
1,193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 4.61 KB | None | 0 0
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.SQLException;
  4. import java.util.Properties;
  5.  
  6. import liquibase.Liquibase;
  7. import liquibase.database.Database;
  8. import liquibase.database.DatabaseFactory;
  9. import liquibase.database.jvm.JdbcConnection;
  10. import liquibase.exception.LiquibaseException;
  11. import liquibase.resource.ClassLoaderResourceAccessor;
  12. import liquibase.resource.FileSystemResourceAccessor;
  13. import liquibase.resource.ResourceAccessor;
  14.  
  15. import org.apache.commons.lang.StringUtils;
  16. import org.slf4j.Logger;
  17. import org.slf4j.LoggerFactory;
  18.  
  19. import com.mycompany.arch.configuration.EnvironmentProperties;
  20.  
  21. /**
  22.  * Utility class for tasks related with Liquibase.
  23.  */
  24. public final class LiquibaseUtils {
  25.  
  26.     private static final Logger LOG = LoggerFactory.getLogger( LiquibaseUtils.class );
  27.  
  28.     public static final String ROOT_CHANGELOG_PATH = "db/changelog.xml";
  29.     public static final String FS_CHANGELOG_PREFIX = "file://";
  30.    
  31.     /**
  32.      * Apply any pending changes to the database.
  33.      *
  34.      * Uses environment properties for connection.
  35.      *
  36.      * @return
  37.      */
  38.     public static boolean applyDatabaseChanges() {
  39.         // Get database connection details from properties file
  40.         Properties envProps = EnvironmentProperties.get();
  41.         String dbDriver = envProps.getProperty( "db.driver" );
  42.         String dbURL = envProps.getProperty( "db.url" );
  43.         String dbUser = envProps.getProperty( "db.owner_username" );
  44.         String dbPass = envProps.getProperty( "db.owner_password" );
  45.         String dbDataUser = envProps.getProperty( "db.username" );
  46.         // Supplemental changelog (used for specific configurations, unit tests, development deployments...)
  47.         String extraChangelog = envProps.getProperty( "ddna.db.extra_changelog" );
  48.        
  49.         LOG.info( "Applying pending changes to the database..." );
  50.         if( StringUtils.isEmpty( extraChangelog ) ) {
  51.             return applyChangelogs( dbDriver, dbURL, dbUser, dbPass, dbDataUser, false, ROOT_CHANGELOG_PATH );
  52.         }
  53.         else {
  54.             return applyChangelogs( dbDriver, dbURL, dbUser, dbPass, dbDataUser, false, ROOT_CHANGELOG_PATH, FS_CHANGELOG_PREFIX + extraChangelog );
  55.         }
  56.     }
  57.    
  58.     /**
  59.      * Apply a Liquibase changelog to a database.
  60.      *
  61.      * NB: Changes will be applied directly to the database with no consideration for potential ORM caches.
  62.      *
  63.      * @param dbDriver Driver class for the database
  64.      * @param dbURL JDBC URL for the database to target
  65.      * @param dbUsername Username of the account used to apply changes
  66.      * @param dbPassword Password of the account used to apply changes
  67.      * @param dbDataUsername Username of the account used to manipulate data (used for grants)
  68.      * @param dropFirst Flag indicating if all object should be dropped before apply the changelog (used for unit tests)
  69.      * @param changelogRefs List of changelogs to apply
  70.      * @return
  71.      */
  72.     public static boolean applyChangelogs( String dbDriver, String dbURL, String dbUsername, String dbPassword,
  73.             String dbDataUsername, boolean dropFirst, String... changelogRefs ) {
  74.         boolean success = false;
  75.  
  76.         Connection conn = null;
  77.         try {
  78.             // Register JDBC driver in case it is not already.
  79.             Class.forName( dbDriver );
  80.  
  81.             conn = DriverManager.getConnection( dbURL, dbUsername, dbPassword );
  82.  
  83.             // Username properties for grants
  84.             System.setProperty( "db.changelog.datauser", dbDataUsername );
  85.             System.setProperty( "db.changelog.owneruser", dbUsername );
  86.            
  87.             Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation( new JdbcConnection( conn ) );
  88.             ResourceAccessor clRsrcAccessor = new ClassLoaderResourceAccessor(LiquibaseUtils.class.getClassLoader());
  89.             ResourceAccessor fileResourceAccessor = new FileSystemResourceAccessor();
  90.  
  91.             if( dropFirst ) {
  92.                 Liquibase liquibase = new Liquibase( "", clRsrcAccessor, database );
  93.                 liquibase.dropAll();
  94.             }
  95.            
  96.             for ( String changeLogRef : changelogRefs ) {
  97.                 Liquibase liquibase = null;
  98.                 if( changeLogRef.startsWith( FS_CHANGELOG_PREFIX ) ) {
  99.                     liquibase = new Liquibase( changeLogRef.substring( FS_CHANGELOG_PREFIX.length() ), fileResourceAccessor, database );
  100.                 }
  101.                 else {
  102.                     liquibase = new Liquibase( changeLogRef, clRsrcAccessor, database );
  103.                 }
  104.                 liquibase.update( "" );
  105.             }
  106.             success = true;
  107.  
  108.         } catch ( ClassNotFoundException | SQLException | LiquibaseException e ) {
  109.             LOG.warn( "Error apply [{}] changes to the database [{}]", changelogRefs, dbURL );
  110.             LOG.warn( "Error details: ", e );
  111.         } finally {
  112.             if ( conn != null ) {
  113.                 try {
  114.                     conn.rollback();
  115.                     conn.close();
  116.                 } catch ( SQLException e ) {
  117.                     // Not much to do at this stage.
  118.                 }
  119.             }
  120.         }
  121.  
  122.         return success;
  123.     }
  124. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement