com.anji.plus.gaea.archiver.service.DBOperatorService Maven / Gradle / Ivy
package com.anji.plus.gaea.archiver.service;
import com.anji.plus.gaea.archiver.config.ArchiverTable;
import com.anji.plus.gaea.archiver.consant.DBType;
import com.anji.plus.gaea.archiver.sqlbuilder.ISQLBuilder;
import com.anji.plus.gaea.archiver.sqlbuilder.SQLBuilderFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.sql.SQLException;
import java.util.*;
/**
* 数据库操作实现类
*
* @author 木子李·De
* @since 2021/2/3 14:16
*/
@Service
public class DBOperatorService implements IDBOperatorService {
private static DBType dbType;
@Autowired
private JdbcTemplate jdbcTemplate;
private DBType getDBType() throws SQLException {
if(dbType != null){
return dbType;
}
String databaseProductName=jdbcTemplate.getDataSource().getConnection().getMetaData().getDatabaseProductName();
if(databaseProductName == null || databaseProductName.trim().length() == 0){
throw new RuntimeException(String.format("%s database not supported", databaseProductName));
}
dbType=DBType.getDbType(databaseProductName);
return Optional.ofNullable(dbType).orElseThrow(()->
new RuntimeException(String.format("%s database not supported", databaseProductName))
);
}
private ISQLBuilder getSQLBuilder(){
try{
return SQLBuilderFactory.getSQLBuilder(getDBType());
}catch (Exception e){
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
@Override
public boolean existTable(String tableName) {
try{
String sql = getSQLBuilder().existTable(tableName);
jdbcTemplate.queryForRowSet(sql);
return true;
}catch (Exception e){
return false;
}
}
@Override
public boolean existTableField(String tableName, String fieldName) {
try{
String sql = getSQLBuilder().existTableField(tableName, fieldName);
SqlRowSet sqlRowSet = jdbcTemplate.queryForRowSet(sql);
boolean existField = false;
while (sqlRowSet.next()){
String fileName = sqlRowSet.getString("Field");
if(fileName.toLowerCase().trim().equals(fieldName.trim())){
existField = true;
break;
}
}
return existField;
}catch (Exception e){
return false;
}
}
@Override
public Date getNow() {
String sql = getSQLBuilder().getNow();
Map map = jdbcTemplate.queryForMap(sql);
Date now = (Date)map.get("now");
return null;
}
@Override
public Long countRows(String sourceTableName) {
return null;
}
@Override
public List getCrossMonthList(String tablename, String timefield, Integer maxDaysBeforeArchive) {
String sql = getSQLBuilder().getCrossMonthList(tablename, timefield, maxDaysBeforeArchive);
List