org.test4j.module.database.IDataSourceScript Maven / Gradle / Ivy
package org.test4j.module.database;
import cn.org.atool.fluent.mybatis.metadata.DbType;
import lombok.Data;
import lombok.experimental.Accessors;
import org.test4j.module.database.script.EntityScriptParser;
import java.util.*;
import java.util.stream.Collectors;
import static org.test4j.module.database.script.DBHelper.buildH2Index;
import static org.test4j.module.database.script.DBHelper.buildH2Unique;
/**
* IDataSourceScript
*
* @author darui.wu
*/
@SuppressWarnings({"rawtypes", "unused"})
public interface IDataSourceScript {
/**
* 指定的类型转换
*/
Map SPEC_TYPES = new HashMap<>();
/**
* 返回数据库表定义对象
*
* @return List
*/
List getTableKlass();
/**
* 返回索引定义对象
*
* @return IndexList
*/
IndexList getIndexList();
/**
* 生成数据库脚本
*
* @param type 数据库类型
* @return create script
*/
default String script(DbType type) {
String script = EntityScriptParser.script(type, this.dbTypeConvert(), this.getTableKlass());
String index = IndexList.script(this.getIndexList());
return script + "\n\n" + index;
}
/**
* 构造测试库字段类型和原生库字段类型映射器
*
* @return EntityScriptParser
*/
default EntityScriptParser.DbTypeConvert dbTypeConvert() {
if (SPEC_TYPES.size() == 0) {
return EntityScriptParser.NonDbTypeConvert.INSTANCE;
} else {
return type -> {
String _type = type.toLowerCase();
return SPEC_TYPES.getOrDefault(_type, _type);
};
}
}
/**
* 构造列表
*
* @param objs objs
* @param Item Type
* @return list
*/
default List list(T... objs) {
List list = new ArrayList<>(objs.length);
Collections.addAll(list, objs);
return list;
}
@Data
@Accessors(chain = true)
class Index {
private boolean isUnique;
private String table;
private String[] columns;
public String buildIndex() {
return isUnique ? buildH2Unique(this.table, columns) : buildH2Index(this.table, columns);
}
}
class IndexList {
List indexList = new ArrayList<>();
public IndexList unique(String table, String... columns) {
this.indexList.add(new Index().setUnique(true).setTable(table).setColumns(columns));
return this;
}
public IndexList index(String table, String... columns) {
this.indexList.add(new Index().setUnique(false).setTable(table).setColumns(columns));
return this;
}
/**
* 构建数据库索引
*
* @return index script
*/
public static String script(IndexList indexList) {
if (indexList == null || indexList.indexList == null || indexList.indexList.size() == 0) {
return "";
} else {
return indexList.indexList.stream()
.map(Index::buildIndex)
.collect(Collectors.joining("\n"));
}
}
}
}