All Downloads are FREE. Search and download functionalities are using the official Maven repository.

ch.inftec.flyway.core.SqlFileRunner Maven / Gradle / Ivy

There is a newer version: 3.2.1-Final
Show newest version
/**
 * Copyright 2014 by Inftec GmbH, Switzerland
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ch.inftec.flyway.core;

import org.flywaydb.core.internal.dbsupport.DbSupport;
import org.flywaydb.core.internal.dbsupport.DbSupportFactory;
import org.flywaydb.core.internal.dbsupport.SqlScript;
import org.flywaydb.core.internal.util.jdbc.DriverDataSource;
import org.flywaydb.core.internal.util.logging.Log;
import org.flywaydb.core.internal.util.logging.LogFactory;
import org.flywaydb.core.internal.util.scanner.Resource;
import org.flywaydb.core.internal.util.scanner.filesystem.FileSystemResource;

import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Helper class for executing sql files against a datasource
 *
 * @author Roger Brechbühl
 */
public class SqlFileRunner {
    private static final Log LOG = LogFactory.getLog(SqlFileRunner.class);

    /**
     * collect and execute all files against a database.
     *
     * @param baseDirectory the directory to search for files named *.sql, search is done recursively in
     *                      subdirectories
     * @param jdbcUrl the database connect url
     * @param jdbcUser the database user
     * @param jdbcPassword the database password
     * @param initSql initial sql which is executed when connection is created
     * @return the number of successfully executed files
     * @throws IOException if baseDirectory is not a directory
     * @throws SQLException when the database connection can't be created, or a script contains errors
     */
    public static int execute(File baseDirectory, String jdbcUrl, String jdbcUser, String jdbcPassword,
                              String... initSql) throws IOException, SQLException {

        if (baseDirectory == null || !baseDirectory.exists() || !baseDirectory.isDirectory()) {
            throw new IOException(String.format("directory %s should exists and be a directory", baseDirectory));
        }

        // used for Flyway 3.0:
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        DataSource ds = new DriverDataSource(classLoader, null, jdbcUrl, jdbcUser, jdbcPassword, initSql);
        DbSupport support = DbSupportFactory.createDbSupport(ds.getConnection(), false);

        try {
            int filesExecuted = 0;
            List sqlFiles = new ArrayList<>();
            collectSqlFiles(baseDirectory, sqlFiles);

            for (File sqlFile : sqlFiles) {
                Resource resource = new FileSystemResource(sqlFile.getAbsolutePath());
                SqlScript script = new SqlScript(resource.loadAsString("UTF-8"), support);
                LOG.info(String.format("execute sql file: %s", sqlFile.getAbsolutePath()));
                script.execute(support.getJdbcTemplate());
                filesExecuted++;
            }

            return filesExecuted;
        } finally {
            try {
                support.getJdbcTemplate().getConnection().close();
            } catch (SQLException e) {
                LOG.error(e.getMessage(), e);
            }
        }
    }

    /**
     * recursively search for sql files
     * 
     * @param directory the directory name
     * @param collectedFiles the result list of all collected files
     */
    static void collectSqlFiles(File directory, List collectedFiles) {

        for (String fileName : directory.list()) {
            File file = new File(directory, fileName);
            if (file.isDirectory()) {
                collectSqlFiles(file, collectedFiles);
            } else {
                if (fileName.endsWith(".sql")) {
                    collectedFiles.add(file);
                }
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy