package com.tiesheng.migration.config;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.sql.SQLException;
import java.util.List;

/**
 * 数据库表版本对比
 *
 * @author hao
 */
@Configuration
@ConfigurationProperties(prefix = "tiesheng.db-migration")
public class DbMigrationConfig {

    private String table = "core_db_migration";
    private List<String> locations = CollUtil.newArrayList("classpath:db/migration/*.sql");
    private String ignoreSqls = "drop,delete";

    /**
     * 检查数据库是否存在
     *
     * @param db
     * @throws SQLException
     */
    public void checkDbExists(Db db) throws SQLException {
        try {
            db.count(Entity.create(getTable()));
        } catch (SQLException ignored) {
            db.execute("CREATE TABLE `" + getTable() + "`  (\n" +
                    "  `id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,\n" +
                    "  `create_time` datetime(0) NOT NULL,\n" +
                    "  `update_time` datetime(0) NOT NULL,\n" +
                    "  `is_deleted` int(6) NOT NULL DEFAULT 0,\n" +
                    "  `file` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '文件名称',\n" +
                    "  `checksum` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '文件checksum',\n" +
                    "  PRIMARY KEY (`id`) USING BTREE\n" +
                    ") ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = 'db-合并' ROW_FORMAT = Dynamic;");
        }
    }

    ///////////////////////////////////////////////////////////////////////////
    // setter\getter
    ///////////////////////////////////////////////////////////////////////////

    public String getTable() {
        return table;
    }

    public void setTable(String table) {
        this.table = table;
    }

    public List<String> getLocations() {
        return locations;
    }

    public void setLocations(List<String> locations) {
        this.locations = locations;
    }

    public String getIgnoreSqls() {
        return ignoreSqls;
    }

    public void setIgnoreSqls(String ignoreSqls) {
        this.ignoreSqls = ignoreSqls;
    }
}
