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

com.jslsolucoes.db.migrate.se.Migrate Maven / Gradle / Ivy

There is a newer version: 1.0.24
Show newest version
package com.jslsolucoes.db.migrate.se;

import java.nio.file.Files;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jslsolucoes.db.migrate.se.config.MigrateConfiguration;
import com.jslsolucoes.db.migrate.se.config.MigrateDatabaseConfiguration;
import com.jslsolucoes.db.migrate.se.model.MigrateHistory;
import com.jslsolucoes.db.migrate.se.repository.MigrateHistoryRepository;
import com.jslsolucoes.db.migrate.se.repository.impl.MigrateHistoryRepositoryImpl;
import com.jslsolucoes.db.migrate.se.repository.impl.driver.PostgresSqlQuery;
import com.jslsolucoes.db.migrate.se.repository.impl.driver.Query;

public class Migrate {

    private MigrateConfiguration migrateConfiguration;
    private final static Logger logger = LoggerFactory.getLogger(Migrate.class);

    private Migrate() {

    }

    public static Migrate newMigration() {
	return new Migrate();
    }

    public Migrate withConfiguration(MigrateConfiguration migrateConfiguration) {
	this.migrateConfiguration = migrateConfiguration;
	return this;
    }

    public void migrate() throws Exception {
	try (Connection connection = connection()) {
	    MigrateHistoryRepository migrateHistoryRepository = new MigrateHistoryRepositoryImpl(connection,
		    driverQuery());

	    if (!migrateHistoryRepository.exists()) {
		logger.info("Migrate history table not found in database.Table will be created");
		migrateHistoryRepository.create();
		logger.info("Migrate history table created");
	    } else {
		logger.info("Migrate history table already exists in database. Nothing to do.");
	    }
	    MigrateHistory migrateHistory = migrateHistoryRepository.max();
	    logger.info("Current version is {}", migrateHistory.getDescription());

	    for (MigrateResource migrationResource : migrateResources()) {
		String fileName = migrationResource.getFile().getName();
		Long version = migrationResource.getVersion();
		if (version > migrateHistory.getVersion()) {
		    	logger.info("Trying apply file {} on database ",fileName);
		    	String fileContent = new String(Files.readAllBytes(migrationResource.getFile().toPath()), "UTF-8");
		    	if(!StringUtils.isEmpty(fileContent) && !StringUtils.isBlank(fileContent)){
        		    	try (PreparedStatement preparedStatement = connection
        				.prepareStatement(fileContent)) {
                			preparedStatement.execute();
                		} catch (SQLException e) {
                		    logger.error("Could not apply file {} on database, content {} contains errors. See stack track for more information =>",fileName,fileContent,e);
                		    throw new SQLException(e);
                		}
		    	} else {
		    	    logger.info("File {} is empty.",fileName);
		    	}
			migrateHistoryRepository.insert(new MigrateHistory(fileName,version));
			logger.info("File {} was applyed successfully on database ",fileName);
		} else {
			logger.info("File {} was ignored because is lower or equals than current version {}",fileName,migrateHistory.getDescription());
		}
	    }
	}
    }

    private Query driverQuery() {
	return new PostgresSqlQuery(migrateConfiguration.getDatabase());
    }

    private Connection connection() {
	try {
	    MigrateDatabaseConfiguration migrateDatabaseConfiguration = migrateConfiguration.getDatabase();
	    logger.info("Getting connection, url: {}, user: {}", migrateDatabaseConfiguration.getUrl(),
		    migrateDatabaseConfiguration.getUser());
	    DriverManager.registerDriver(migrateDatabaseConfiguration.getDriver());
	    return DriverManager.getConnection(migrateDatabaseConfiguration.getUrl(),
		    migrateDatabaseConfiguration.getUser(), migrateDatabaseConfiguration.getPassword());
	} catch (Exception e) {
	    throw new RuntimeException(e);
	}
    }

    private Integer group(String group) {
	if (!StringUtils.isEmpty(group)) {
	    return Integer.valueOf(StringUtils.rightPad(group, 3, '0'));
	} else {
	    return 0;
	}
    }

    public List migrateResources() {
	try {
	    return Files.walk(migrateConfiguration.getScript()).filter(path -> !Files.isDirectory(path)).map(path -> {
		Matcher matcher = Pattern.compile("(v\\.)?([0-9]{1,})(\\.([0-9]{1,}))?(\\.([0-9]{1,}))?(\\.([0-9]{1,}))?")
			.matcher(path.getFileName().toString());
		if (matcher.find()) {
		    Integer group1 = group(matcher.group(2));
		    Integer group2 = group(matcher.group(4));
		    Integer group3 = group(matcher.group(6));
		    Integer group4 = group(matcher.group(8));
		    return new MigrateResource(path,
			    Long.valueOf(String.format("%03d%03d%03d%03d", group1, group2, group3, group4)));
		}
		throw new RuntimeException("File name not match pattern v.x.x.x.x (v.1,v.1.0,v.1.0.0,v.1.0.0.0");
	    }).collect(Collectors.toList()).stream().sorted((c1, c2) -> {
		return c1.getVersion().compareTo(c2.getVersion());
	    }).collect(Collectors.toList());
	} catch (Exception e) {
	    throw new RuntimeException(e);
	}
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy