/*
 * Copyright (c) 2018-2028, aokunsang All rights reserved.
 * 我问青山何时老，青山问我几时闲，
 * 不是闲人闲不得，能闲必非等闲人。
 */
package org.springblade.core.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import lombok.extern.slf4j.Slf4j;
import org.flywaydb.core.Flyway;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * Flyway 迁移sql配置类
 *
 * @author wookvn
 * @datetime 2024-11-08 12:27:08
 */
@Slf4j
@Configuration
@ConditionalOnProperty(value = "blade.flyway.enabled", havingValue = "true", matchIfMissing = true)
public class FlywayConfiguration {

    @Value("${spring.application.name}")
    private String applicationName;

    @Autowired
    private DynamicRoutingDataSource dynamicRoutingDataSource;

    @Bean
    public void migrate() {
        long startTime = System.currentTimeMillis();
        //每个模块的flyway表
        String flywayModuleTable = String.format("flyway_%s", applicationName.toLowerCase().replaceAll("gmetry|geometry|\\-", ""));
        log.info("flyway开始执行脚本[{}]", flywayModuleTable);
        DataSource masterDs = dynamicRoutingDataSource.getDataSource("master");
        Flyway flyway = Flyway.configure()
                .dataSource(masterDs)
                .table(flywayModuleTable)
                .locations("classpath:db")
                .baselineVersion("1.0.0")
                .baselineDescription("初始化")
                //设置为 true 后 flyway 将在需要 baseline 的时候, 自动执行一次 baseline，创建表。
                .baselineOnMigrate(true)
                //每次迁移前不校验SQL脚本文件
                .validateOnMigrate(false)
                //flyway 的 clean 命令会删除指定 schema 下的所有 table, 生产务必禁掉
                .cleanDisabled(true)
                .load();
        flyway.migrate();
        log.info("flyway执行脚本结束[{}]，耗时{} ms", flywayModuleTable, System.currentTimeMillis() - startTime);
    }
}
