Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug-354] Database Migration #396

Merged
merged 1 commit into from
Aug 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ public class DatabaseMigrationAware implements ApplicationContextAware, Ordered
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
String migrationEnable = applicationContext.getEnvironment().getProperty("datasophon.migration.enable");
log.info("Database Migration enable is {}", migrationEnable);
if (migrationEnable == null || "false".equals(migrationEnable)) {
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,22 +22,6 @@
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import com.datasophon.common.utils.FileUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.ibatis.jdbc.SQL;
Expand All @@ -52,6 +36,12 @@
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Component
public class DatabaseMigration {
Expand All @@ -65,12 +55,12 @@ public class DatabaseMigration {
public final static String SPLIT = "__";

private static final String TABLE_CREATE_SQL = "CREATE TABLE `migration_history` (" +
" `version` varchar(128) NOT NULL," +
" `execute_user` varchar(128) NOT NULL," +
" `execute_date` timestamp NOT NULL," +
" `success` tinyint(1) NOT NULL," +
" PRIMARY KEY (`version`)" +
");";
" `version` varchar(128) NOT NULL," +
" `execute_user` varchar(128) NOT NULL," +
" `execute_date` timestamp NOT NULL," +
" `success` tinyint(1) NOT NULL," +
" PRIMARY KEY (`version`)" +
");";

@Value("${spring.datasource.url}")
private String url;
Expand Down Expand Up @@ -179,16 +169,16 @@ private synchronized TreeSet<Migration> getAllMigrations() {
}
File home = new File(FileUtils.concatPath(System.getProperty("user.dir"), MIGRATION_HOME));
if (home.exists() && home.isDirectory()) {
File[] sqlFiles = home.listFiles(pathname ->
"sql".equals(FileUtil.getSuffix(pathname.getName()))
List<File> sqlFiles = FileUtil.loopFiles(home ,pathname ->
"sql".equals(FileUtil.getSuffix(pathname.getName()))
);
if (sqlFiles != null) {
resources = Arrays.stream(sqlFiles).map(FileSystemResource::new).toArray(Resource[]::new);
resources = sqlFiles.stream().map(FileSystemResource::new).toArray(Resource[]::new);
}
}
Map<String, List<Resource>> resourceMap = Arrays.stream(resources)
.filter(Migration::isMigrationFile)
.collect(Collectors.groupingBy(r -> Objects.requireNonNull(r.getFilename()).substring(1, r.getFilename().indexOf(SPLIT))));
.filter(Migration::isMigrationFile)
.collect(Collectors.groupingBy(r -> Objects.requireNonNull(r.getFilename()).substring(1, r.getFilename().indexOf(SPLIT))));

for (Map.Entry<String, List<Resource>> entries : resourceMap.entrySet()) {
Resource ddl = null, dml = null, rollback = null;
Expand Down Expand Up @@ -218,20 +208,20 @@ private synchronized TreeSet<Migration> getAllMigrations() {
private void upsertMigration(Migration migration) {
SQL query = new SQL();
query.SELECT("*").FROM(MIGRATION_TABLE_NAME)
.WHERE("`version` = '" + migration.getVersion() + "'");
.WHERE("`version` = '" + migration.getVersion() + "'");
List<Migration> migrations = jdbcTemplate.query(query.toString(), new BeanPropertyRowMapper<>(Migration.class));
SQL sql = new SQL();
if (!CollectionUtils.isEmpty(migrations) && !migrations.get(0).isSuccess()) {
sql.UPDATE(MIGRATION_TABLE_NAME)
.SET("success = " + String.format("'%s'", (migration.isSuccess() ? "1" : "0"))
, "execute_date = " + String.format("'%s'", DateFormatUtils.format(new Date(), DEFAULT_DATE_FORMAT)))
.WHERE("`version` = " + String.format("'%s'", migration.getVersion()));
.SET("success = " + String.format("'%s'", (migration.isSuccess() ? "1" : "0"))
, "execute_date = " + String.format("'%s'", DateFormatUtils.format(new Date(), DEFAULT_DATE_FORMAT)))
.WHERE("`version` = " + String.format("'%s'", migration.getVersion()));
} else {
sql.INSERT_INTO(MIGRATION_TABLE_NAME)
.INTO_VALUES(String.format("'%s'", migration.getVersion())
, String.format("'%s'", migration.getExecuteUser())
, String.format("'%s'", DateFormatUtils.format(migration.getExecuteDate(), DEFAULT_DATE_FORMAT))
, String.format("'%s'", migration.isSuccess() ? "1" : "0"));
.INTO_VALUES(String.format("'%s'", migration.getVersion())
, String.format("'%s'", migration.getExecuteUser())
, String.format("'%s'", DateFormatUtils.format(migration.getExecuteDate(), DEFAULT_DATE_FORMAT))
, String.format("'%s'", migration.isSuccess() ? "1" : "0"));
}
jdbcTemplate.execute(sql.toString());
}
Expand Down Expand Up @@ -292,4 +282,4 @@ public void write(String s) {
}
}

}
}