提交 6aaeccf7 authored 作者: czq's avatar czq

Merge branch 'master' of 192.168.1.249:ty_wyl/adaptation-master1 into czq

...@@ -2,7 +2,6 @@ package com.zjty.adaptationmaster; ...@@ -2,7 +2,6 @@ package com.zjty.adaptationmaster;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication @SpringBootApplication
public class AdaptationMasterApplication { public class AdaptationMasterApplication {
......
...@@ -19,8 +19,8 @@ public class DBMigrateController { ...@@ -19,8 +19,8 @@ public class DBMigrateController {
} }
@PutMapping("/find") @PutMapping("/find")
public ServerResponse find(@RequestBody String dbType){ public ServerResponse find(@RequestBody Integer id){
return dbMigrateService.findDBByDBType(dbType); return dbMigrateService.findDBByDBType(id);
} }
} }
package com.zjty.adaptationmaster.adaptor.controller;
import com.zjty.adaptationmaster.adaptor.service.FileUploadService;
import com.zjty.adaptationmaster.base.response.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/file")
public class FileUploadController {
@Autowired
private FileUploadService fileUploadService;
//文件上传
@PutMapping("/upload")
public ServerResponse fileUpload(HttpServletRequest httpServletRequest){
return fileUploadService.fileUpload(httpServletRequest);
}
}
package com.zjty.adaptationmaster.adaptor.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Data
public class FileReturn {
private String name;//上传文件名称
private String path;//上传文件地址
}
package com.zjty.adaptationmaster.adaptor.entity;
import org.springframework.context.ApplicationContext;
public class SystemVariable {
public static ApplicationContext context;
}
...@@ -10,4 +10,5 @@ import lombok.NoArgsConstructor; ...@@ -10,4 +10,5 @@ import lombok.NoArgsConstructor;
public class DBDeleteResponse { public class DBDeleteResponse {
private String dbName;//数据库名称 private String dbName;//数据库名称
private String dbType;//数据库类型 private String dbType;//数据库类型
private Integer id;
} }
...@@ -4,10 +4,7 @@ import lombok.AllArgsConstructor; ...@@ -4,10 +4,7 @@ import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import javax.persistence.Entity; import javax.persistence.*;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@AllArgsConstructor @AllArgsConstructor
@NoArgsConstructor @NoArgsConstructor
...@@ -17,13 +14,17 @@ public class DBManage { ...@@ -17,13 +14,17 @@ public class DBManage {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id; private Integer id;
private String databaseName;//数据库名字 private String configName;//配置名称
private String userName;//用户名 private String userName;//用户名
private String password;//密码 private String password;//密码
private String databaseType;//数据库类型 private String databaseType;//数据库类型
private String driver;//数据库驱动
private String address;//连接地址 private String address;//连接地址
private String port;//数据库端口号 private String port;//数据库端口号
@Transient
private String databaseName;//可连接数据库名字
@Transient
private String connectionType;//数据库连接时的sql private String connectionType;//数据库连接时的sql
@Transient
private String driver;//数据库驱动
private Integer status;//逻辑删除 0-删除 1-未删除 private Integer status;//逻辑删除 0-删除 1-未删除
} }
package com.zjty.adaptationmaster.adaptor.entity.db;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@AllArgsConstructor
@NoArgsConstructor
@Data
public class DBNameReturn {
List<String> dbName;
Integer status;//连接状态1-连接0-未连接
}
...@@ -12,5 +12,5 @@ public class DatabaseResponse { ...@@ -12,5 +12,5 @@ public class DatabaseResponse {
private String sourceType;//原库类型 private String sourceType;//原库类型
private String createType;//生成库类型 private String createType;//生成库类型
private String sqlPath;//上传数据库地址 private String sqlPath;//上传数据库地址
private String userName;//用户名 private Integer id;//用户ID
} }
...@@ -10,7 +10,7 @@ import java.util.List; ...@@ -10,7 +10,7 @@ import java.util.List;
public interface DBManageDao extends JpaRepository<DBManage,Integer> { public interface DBManageDao extends JpaRepository<DBManage,Integer> {
DBManage findDatabaseManagementByDatabaseTypeAndStatus(String databaseType, Integer status); DBManage findDBManageByIdAndStatus(Integer id,Integer status);
List<DBManage> findDatabaseManagementByStatus(Integer status); List<DBManage> findDatabaseManagementByStatus(Integer status);
......
...@@ -8,6 +8,6 @@ public interface DBMigrateService { ...@@ -8,6 +8,6 @@ public interface DBMigrateService {
ServerResponse dbMigrate(DatabaseResponse databaseResponse); ServerResponse dbMigrate(DatabaseResponse databaseResponse);
ServerResponse findDBByDBType(String dbType); ServerResponse findDBByDBType(Integer id);
} }
package com.zjty.adaptationmaster.adaptor.service;
import com.zjty.adaptationmaster.base.response.ServerResponse;
import javax.servlet.http.HttpServletRequest;
public interface FileUploadService {
ServerResponse fileUpload(HttpServletRequest request);
}
package com.zjty.adaptationmaster.adaptor.service.Impl; package com.zjty.adaptationmaster.adaptor.service.Impl;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.zjty.adaptationmaster.adaptor.entity.db.DBManage; import com.zjty.adaptationmaster.adaptor.entity.db.DBManage;
import com.zjty.adaptationmaster.adaptor.entity.db.DBNameReturn;
import com.zjty.adaptationmaster.adaptor.entity.db.DBRecord; import com.zjty.adaptationmaster.adaptor.entity.db.DBRecord;
import com.zjty.adaptationmaster.adaptor.entity.db.DatabaseResponse; import com.zjty.adaptationmaster.adaptor.entity.db.DatabaseResponse;
import com.zjty.adaptationmaster.adaptor.repository.DBManageDao; import com.zjty.adaptationmaster.adaptor.repository.DBManageDao;
...@@ -10,8 +9,10 @@ import com.zjty.adaptationmaster.adaptor.repository.DBRecordDao; ...@@ -10,8 +9,10 @@ import com.zjty.adaptationmaster.adaptor.repository.DBRecordDao;
import com.zjty.adaptationmaster.adaptor.service.DBMigrateService; import com.zjty.adaptationmaster.adaptor.service.DBMigrateService;
import com.zjty.adaptationmaster.base.response.ServerResponse; import com.zjty.adaptationmaster.base.response.ServerResponse;
import com.zjty.adaptationmaster.utils.Regular; import com.zjty.adaptationmaster.utils.Regular;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.BufferedReader; import java.io.BufferedReader;
...@@ -26,6 +27,7 @@ import java.util.Date; ...@@ -26,6 +27,7 @@ import java.util.Date;
import java.util.List; import java.util.List;
@Service @Service
@Slf4j
public class DBMigrateServiceImpl implements DBMigrateService { public class DBMigrateServiceImpl implements DBMigrateService {
@Autowired @Autowired
...@@ -33,6 +35,13 @@ public class DBMigrateServiceImpl implements DBMigrateService { ...@@ -33,6 +35,13 @@ public class DBMigrateServiceImpl implements DBMigrateService {
@Autowired @Autowired
private DBRecordDao dbRecordDao; private DBRecordDao dbRecordDao;
@Value("${highgo.driver}")
private String highgoDriver;
@Value("${highgo.connectionType}")
private String highgoConnnectionType;
@Value("${highgo.dbName}")
private String highgoDBName;
/** /**
* 创建新数据库和数据库中的表 * 创建新数据库和数据库中的表
*/ */
...@@ -41,7 +50,7 @@ public class DBMigrateServiceImpl implements DBMigrateService { ...@@ -41,7 +50,7 @@ public class DBMigrateServiceImpl implements DBMigrateService {
if(databaseResponse != null && databaseResponse.getDatabaseName() != null){ if(databaseResponse != null && databaseResponse.getDatabaseName() != null){
String databaseName = databaseResponse.getDatabaseName(); String databaseName = databaseResponse.getDatabaseName();
//查询新建的数据库是否存在 //查询新建的数据库是否存在
ServerResponse serverResponse = findDBByDBType(databaseResponse.getCreateType()); ServerResponse serverResponse = findDBByDBType(databaseResponse.getId());
Object obj = serverResponse.getData(); Object obj = serverResponse.getData();
List<String> dbNameList = new ArrayList<>(); List<String> dbNameList = new ArrayList<>();
if(obj instanceof ArrayList<?>){ if(obj instanceof ArrayList<?>){
...@@ -50,16 +59,20 @@ public class DBMigrateServiceImpl implements DBMigrateService { ...@@ -50,16 +59,20 @@ public class DBMigrateServiceImpl implements DBMigrateService {
} }
} }
if(dbNameList.contains(databaseName)){ if(dbNameList.contains(databaseName)){
return ServerResponse.error("该数据库已存在,请重新填写"); log.info("该数据库已存在,请重新填写数据库名称");
return ServerResponse.error("该数据库已存在,请重新填写数据库名称");
} }
//转换后的.sql文件地址 //转换后的.sql文件地址
String path = ""; String path = "";
//根据传入的生成数据库类型,查找未被删除的配置文件
DBManage databaseManagement = dbManageDao.findDBManageByIdAndStatus(databaseResponse.getId(),1);
//mysql数据库 //mysql数据库
if(databaseResponse.getCreateType().equals("highgo") && databaseResponse.getSourceType().equals("mysql")){ if(databaseResponse.getCreateType().equals("highgo") && databaseResponse.getSourceType().equals("mysql")){
//生成数据库的名称 //生成数据库的名称
//连接系统数据库,建立新数据库 //连接系统数据库,建立新数据库
//根据传入的生成数据库类型,查找未被删除的配置文件 databaseManagement.setDatabaseName(highgoDBName);
DBManage databaseManagement = dbManageDao.findDatabaseManagementByDatabaseTypeAndStatus(databaseResponse.getCreateType(),1); databaseManagement.setDriver(highgoDriver);
databaseManagement.setConnectionType(highgoConnnectionType);
Connection connection = Regular.databaseConnection(databaseManagement); Connection connection = Regular.databaseConnection(databaseManagement);
if(connection != null){ if(connection != null){
PreparedStatement preparedStatement = null; PreparedStatement preparedStatement = null;
...@@ -69,6 +82,7 @@ public class DBMigrateServiceImpl implements DBMigrateService { ...@@ -69,6 +82,7 @@ public class DBMigrateServiceImpl implements DBMigrateService {
preparedStatement.execute(); preparedStatement.execute();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
log.info("创建数据库:" + databaseName + "出错");
return ServerResponse.error("创建数据库:" + databaseName + "出错"); return ServerResponse.error("创建数据库:" + databaseName + "出错");
}finally { }finally {
try { try {
...@@ -98,24 +112,18 @@ public class DBMigrateServiceImpl implements DBMigrateService { ...@@ -98,24 +112,18 @@ public class DBMigrateServiceImpl implements DBMigrateService {
try { try {
sql += s; sql += s;
if(s.contains(";")){ if(s.contains(";")){
/*if(Regular.lowerAndUpper(sql,"CREATE") && Regular.lowerAndUpper(sql,"TABLE")){
String endChar = sql.substring(sql.lastIndexOf("\"") + 1);
if(endChar.contains(",")){
String start = sql.substring(0,sql.lastIndexOf(","));
String end = sql.substring(sql.lastIndexOf(",") + 1);
sql = start + end;
}
}*/
preparedStatement1 = connection1.prepareStatement(sql); preparedStatement1 = connection1.prepareStatement(sql);
preparedStatement1.execute(); preparedStatement1.execute();
sql = ""; sql = "";
} }
}catch (SQLException e) { }catch (SQLException e) {
log.info("sql执行出错语句:" + sql);
sql = ""; sql = "";
e.printStackTrace(); e.printStackTrace();
continue; continue;
} }
} }
log.info(databaseResponse.getSqlPath() + "执行完成");
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
...@@ -129,6 +137,8 @@ public class DBMigrateServiceImpl implements DBMigrateService { ...@@ -129,6 +137,8 @@ public class DBMigrateServiceImpl implements DBMigrateService {
} }
} }
} }
}else {
return ServerResponse.error("创建数据库时连接数据库失败");
} }
} }
//保存迁移记录到数据库 //保存迁移记录到数据库
...@@ -142,8 +152,8 @@ public class DBMigrateServiceImpl implements DBMigrateService { ...@@ -142,8 +152,8 @@ public class DBMigrateServiceImpl implements DBMigrateService {
if(databaseResponse.getDatabaseName() != null){ if(databaseResponse.getDatabaseName() != null){
dbRecord.setDbName(databaseResponse.getDatabaseName()); dbRecord.setDbName(databaseResponse.getDatabaseName());
} }
if(databaseResponse.getUserName() != null){ if(databaseManagement.getUserName() != null){
dbRecord.setUserName(databaseResponse.getUserName()); dbRecord.setUserName(databaseManagement.getUserName());
} }
if(databaseResponse.getSqlPath() != null){ if(databaseResponse.getSqlPath() != null){
dbRecord.setSqlPath(databaseResponse.getSqlPath()); dbRecord.setSqlPath(databaseResponse.getSqlPath());
...@@ -158,17 +168,22 @@ public class DBMigrateServiceImpl implements DBMigrateService { ...@@ -158,17 +168,22 @@ public class DBMigrateServiceImpl implements DBMigrateService {
/** /**
* 根据传入的数据库类型查询所有的数据库 * 根据传入的数据库类型查询所有的数据库
* @param dbType * @param id
* @return * @return
*/ */
@Override @Override
public ServerResponse findDBByDBType(String dbType) { public ServerResponse findDBByDBType(Integer id) {
List<String> dbNameList = new ArrayList<>(); List<String> dbNameList = new ArrayList<>();
DBNameReturn dbNameReturn = new DBNameReturn();
DBManage databaseManagement = dbManageDao.findDBManageByIdAndStatus(id, 1);
//highgo查询所有数据库 //highgo查询所有数据库
if(dbType.equals("highgo")){ if(databaseManagement.getDatabaseType().equals("highgo")){
DBManage databaseManagement = dbManageDao.findDatabaseManagementByDatabaseTypeAndStatus(dbType, 1); databaseManagement.setDatabaseName(highgoDBName);
databaseManagement.setDriver(highgoDriver);
databaseManagement.setConnectionType(highgoConnnectionType);
Connection connection = Regular.databaseConnection(databaseManagement); Connection connection = Regular.databaseConnection(databaseManagement);
if (connection != null) { if (connection != null) {
dbNameReturn.setStatus(1);
PreparedStatement preparedStatement = null; PreparedStatement preparedStatement = null;
try { try {
String findDB = "select p.datname from pg_database p where p.datistemplate = false;"; String findDB = "select p.datname from pg_database p where p.datistemplate = false;";
...@@ -188,8 +203,11 @@ public class DBMigrateServiceImpl implements DBMigrateService { ...@@ -188,8 +203,11 @@ public class DBMigrateServiceImpl implements DBMigrateService {
e.printStackTrace(); e.printStackTrace();
} }
} }
}else {
dbNameReturn.setStatus(0);//未连接
} }
} }
return ServerResponse.success(dbNameList); dbNameReturn.setDbName(dbNameList);
return ServerResponse.success(dbNameReturn);
} }
} }
...@@ -62,7 +62,7 @@ public class DBRecordServiceImpl implements DBRecordService { ...@@ -62,7 +62,7 @@ public class DBRecordServiceImpl implements DBRecordService {
@Override @Override
@Transactional @Transactional
public ServerResponse deleteDB(DBDeleteResponse dbDeleteResponse) { public ServerResponse deleteDB(DBDeleteResponse dbDeleteResponse) {
DBManage dbManage = dbManageDao.findDatabaseManagementByDatabaseTypeAndStatus(dbDeleteResponse.getDbType(),1); DBManage dbManage = dbManageDao.findDBManageByIdAndStatus(dbDeleteResponse.getId(),1);
Connection connection = Regular.databaseConnection(dbManage); Connection connection = Regular.databaseConnection(dbManage);
if (connection != null) { if (connection != null) {
PreparedStatement preparedStatement = null; PreparedStatement preparedStatement = null;
......
package com.zjty.adaptationmaster.adaptor.service.Impl;
import com.zjty.adaptationmaster.adaptor.entity.FileReturn;
import com.zjty.adaptationmaster.adaptor.service.FileUploadService;
import com.zjty.adaptationmaster.base.response.ServerResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@Service
public class FileUploadServiceImpl implements FileUploadService {
/**
* 前台文件上传
* @param request
* @return
*/
@Override
public ServerResponse fileUpload(HttpServletRequest request) {
List<MultipartFile> multipartFiles = ((MultipartHttpServletRequest)request).getFiles("file");
List<FileReturn> fileReturns = new ArrayList<>();
for(MultipartFile multipartFile:multipartFiles){
InputStream is = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
FileReturn fileReturn = new FileReturn();
String sourceName = multipartFile.getOriginalFilename();
String fileName = UUID.randomUUID().toString() + ".sql";
//不存在该目录,创建目录
File file = new File("/sqlFile/uploads");
if(!file.exists()){
file.mkdirs();
}
String savePath = file.getAbsolutePath() + "/" + fileName;
fileReturn.setName(sourceName);
fileReturn.setPath(savePath);
fileReturns.add(fileReturn);
File createFile = new File(savePath);
try {
is = multipartFile.getInputStream();
bis = new BufferedInputStream(is);
fos = new FileOutputStream(createFile);
bos = new BufferedOutputStream(fos);
int len = -1;
byte[] b = new byte[1024];
while ((len = bis.read(b)) != -1){
bos.write(b,0,len);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bis.close();
is.close();
bos.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return ServerResponse.success(fileReturns);
}
}
package com.zjty.adaptationmaster.utils; package com.zjty.adaptationmaster.utils;
import com.zjty.adaptationmaster.adaptor.entity.SystemVariable;
import com.zjty.adaptationmaster.adaptor.entity.db.DBManage; import com.zjty.adaptationmaster.adaptor.entity.db.DBManage;
import org.springframework.core.env.Environment;
import java.io.*; import java.io.*;
import java.sql.Connection; import java.sql.Connection;
...@@ -18,7 +20,11 @@ public class Regular { ...@@ -18,7 +20,11 @@ public class Regular {
*/ */
public static String mySqlRegular(String path,String sqlName){ public static String mySqlRegular(String path,String sqlName){
File file = new File(path); File file = new File(path);
String savePath = file.getParent() + "/" + sqlName + ".sql"; File fileParent = new File(file.getParent() + "/transformSql");
if(!fileParent.exists()){
fileParent.mkdirs();
}
String savePath = fileParent.getAbsolutePath() + "/" + sqlName + ".sql";//导出的sql地址
File saveFile = new File(savePath); File saveFile = new File(savePath);
FileReader fileReader = null; FileReader fileReader = null;
BufferedReader bufferedReader = null; BufferedReader bufferedReader = null;
...@@ -30,116 +36,154 @@ public class Regular { ...@@ -30,116 +36,154 @@ public class Regular {
fileWriter = new FileWriter(saveFile); fileWriter = new FileWriter(saveFile);
bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter = new BufferedWriter(fileWriter);
String s = ""; String s = "";
boolean database = true;//去除.sql中使用数据库的sql语句 boolean isFirstDrop = false;//去除.sql中使用数据库的sql语句
String tableName = null; String tableName = "";//数据库名称
String incrementField = null; String incrementField = "";//自增长字段
List<String> foreignList = new ArrayList<>(); List<String> foreignList = new ArrayList<>();//外键集合
String previous = null; List<String> indexList = new ArrayList<>();//索引集合
String previous = "";//上一个读取的行
String createTableSql = "";
boolean createLock = true;
boolean executeOne = true;
while ((s = bufferedReader.readLine()) != null){ while ((s = bufferedReader.readLine()) != null){
s = s.replaceAll("`","\""); s = s.replaceAll("`","\"");
s += "\r\n"; s += "\r\n";
if(lowerAndUpper(s,"INSERT") && lowerAndUpper(s,"INTO")){
//将\0与\1替换为true或false
s = s.replace("'\\0'","'false'");
s = s.replace("'\\1'","'true'");
bufferedWriter.write(s);
continue;
}
//记录自增字段
if(lowerAndUpper(s,"PRIMARY") && lowerAndUpper(s,"KEY")){
incrementField = s.substring(s.indexOf("\"") + 1,s.lastIndexOf("\""));
}
//记录创建表时表的名字
if(lowerAndUpper(s,"CREATE") && lowerAndUpper(s,"TABLE")){
tableName = s.substring(s.indexOf("\"") + 1,s.lastIndexOf("\"")).trim();
createLock = false;
}
//转换mysql的int和bigint类型 //转换mysql的int和bigint类型
if(lowerAndUpper(s,"INT(")){ if(lowerAndUpper(s,"INT(")){
String dataType = s.substring(s.lastIndexOf("\"") + 1,s.indexOf("(")).trim(); String dataType = s.substring(s.lastIndexOf("\"") + 1,s.indexOf("(")).trim();
String startChar = s.substring(0,s.indexOf("("));
String endChar = s.substring(s.indexOf(")") + 1);
if(dataType.length() <= 4){ if(dataType.length() <= 4){
//int类型 //int类型
String startChar = s.substring(0,s.indexOf("("));
String endChar = s.substring(s.indexOf(")") + 1);
s = startChar + "4" + endChar; s = startChar + "4" + endChar;
if(lowerAndUpper(s,"AUTO_INCREMENT")){ if(lowerAndUpper(s,"AUTO_INCREMENT")){
s = replaceLowerAndUpper(s,"AUTO_INCREMENT","");
s = replaceLowerAndUpper(s,"INT4","serial"); s = replaceLowerAndUpper(s,"INT4","serial");
incrementField = s.substring(s.indexOf("\"") + 1,s.lastIndexOf("\""));
} }
}else { }else {
s = startChar + endChar;
//bigint类型 //bigint类型
if(lowerAndUpper(s,"BIGINT")){ if(lowerAndUpper(s,"BIGINT") && lowerAndUpper(s,"AUTO_INCREMENT")){
String startChar = s.substring(0,s.indexOf("(")); s = replaceLowerAndUpper(s,"BIGINT","bigserial");
String endChar = s.substring(s.indexOf(")") + 1); }else if(lowerAndUpper(s,"SMALLINT") && lowerAndUpper(s,"AUTO_INCREMENT")){
s = startChar + endChar; s = replaceLowerAndUpper(s,"SMALLINT","smallserial");
if(lowerAndUpper(s,"AUTO_INCREMENT")){
s = replaceLowerAndUpper(s,"AUTO_INCREMENT","");
s = replaceLowerAndUpper(s,"BIGINT","bigserial");
incrementField = s.substring(s.indexOf("\"") + 1,s.lastIndexOf("\""));
}
}else if(lowerAndUpper(s,"SMALLINT")){
String startChar = s.substring(0,s.indexOf("("));
String endChar = s.substring(s.indexOf(")") + 1);
s = startChar + endChar;
if(lowerAndUpper(s,"AUTO_INCREMENT")){
s = replaceLowerAndUpper(s,"AUTO_INCREMENT","");
s = replaceLowerAndUpper(s,"SMALLINT","smallserial");
incrementField = s.substring(s.indexOf("\"") + 1,s.lastIndexOf("\""));
}
} }
} }
s = replaceLowerAndUpper(s,"AUTO_INCREMENT","");
} }
//转换mysql的时间datetime类型 //转换mysql的时间datetime类型
s = StringType(s,"datetime","timestamp"); s = StringType(s,"datetime","timestamp");
//转换mysql的double类型 //转换mysql的double类型
s = StringType(s,"double","float"); s = StringType(s,"double","real");
//插入值时boolean类型转换 //插入值时boolean类型转换
if(s.contains("bit(1)")){ s = replaceLowerAndUpper(s,"BIT(1)","boolean");
s = replaceLowerAndUpper(s,"bit(1)","boolean"); //从第一个创建表的可执行命令开始
} if(lowerAndUpper(s,"DROP") && lowerAndUpper(s,"TABLE") && executeOne){
if(s.contains("'\\0'")){ isFirstDrop = true;
s = s.replace("'\\0'","'false'"); executeOne = false;
}
if(s.contains("'\\1'")){
s = s.replace("'\\1'","true");
}
//记录创建表时表的名字
if(lowerAndUpper(s,"CREATE") && lowerAndUpper(s,"TABLE")){
tableName = s.substring(s.indexOf("\"") + 1,s.lastIndexOf("\"")).trim();
} }
//去除表类型的定义 //去除表类型的定义
if(lowerAndUpper(s,"ENGINE") && lowerAndUpper(s,"CHARSET")){ if(lowerAndUpper(s,"ENGINE") && (lowerAndUpper(s,"CHARSET") || lowerAndUpper(s,"CHARACTER "))){
//String[] array = s.split(" ");
if(lowerAndUpper(s,"AUTO_INCREMENT")){ if(lowerAndUpper(s,"AUTO_INCREMENT")){
String[] array = s.split(" "); int begin = stringIndex(s,"AUTO_INCREMENT");
for(String a:array){ for(int i = begin;i < s.length();i++){
if(lowerAndUpper(a.trim(),"AUTO_INCREMENT")){ String ca = s.charAt(i) + "";
String num = a.substring(a.indexOf("=") + 1); if(ca.matches("\\d")){
String alterIncrementInital = "SELECT setval('\"" + tableName + "_" + incrementField + "_seq\"'," + (Integer.parseInt(num) - 1) + ", true);\r\n"; s = s.substring(i);
s = ");\r\n"; String num = s.substring(0,s.indexOf(" "));
s = s + alterIncrementInital; s = ");\r\nSELECT setval('\"" + tableName + "_" + incrementField + "_seq\"'," + (Integer.parseInt(num) - 1) + ", true);\r\n";
break;
} }
} }
}else { }else {
s = ");\r\n"; s = ");\r\n";
} }
} }
//去除.sql中使用数据库的sql语句 //msql的外键设置移动位置
if(s.contains("USE") && s.contains(";") && s.contains("\"") && database){ if(lowerAndUpper(s,"FOREIGN") && lowerAndUpper(s,"KEY") && lowerAndUpper(s,"CONSTRAINT")){
database = false; // ON DELETE NO ACTION ON UPDATE NO ACTION
}else { s = "ALTER TABLE \"public\".\"" + tableName + "\" ADD " + s.replace("\r\n","") + ";\r\n";
//逗号去除 foreignList.add(s);
//mysql的外键key值去除 s = "";
if(previous != null){ }
if(lowerAndUpper(s,"KEY") && !lowerAndUpper(s,"FOREIGN") && !lowerAndUpper(s,"PRIMARY")) { if(previous != null && isFirstDrop){
String startChar = s.substring(0,s.indexOf("\"")); //对创建表再做一次检查
if(lowerAndUpper(startChar,"KEY")){ if(lowerAndUpper(s,");")){
previous = previous.substring(0,previous.lastIndexOf(",")) +"\r\n"; createLock = true;
s = ""; }
createTableSql += s;
if(createLock){
if(createTableSql != null && createTableSql != "" && createTableSql.contains(");") && lowerAndUpper(createTableSql,"CREATE") && lowerAndUpper(createTableSql,"TABLE")){
//mysql的外键key值去除
String[] array = createTableSql.split("\r\n");
createTableSql = "";
for(int i = 0;i < array.length;i++){
String startChar = "";
if(array[i].contains("\"")){
startChar = array[i].substring(0,array[i].indexOf("\""));
}
//不是索引,只有KEY
if(!((lowerAndUpper(startChar,"KEY") || lowerAndUpper(startChar,"INDEX")) && !(lowerAndUpper(startChar,"FOREIGN") || lowerAndUpper(startChar,"PRIMARY")))){
if(i != (array.length - 1) && array[i + 1].contains(");") && array[i].charAt(array[i].length() - 1) == ','){
array[i] = array[i].substring(0,array[i].lastIndexOf(","));
}
createTableSql += array[i] + "\r\n";
}else {
String elseName = "";
int firstYinhaoIndex = array[i].indexOf("\"") + 1;
for(int j = firstYinhaoIndex;j < array[i].length();j++){
if(array[i].charAt(j) == '\"'){
break;
}
elseName += array[i].charAt(j);
}
String indexName = array[i].substring(array[i].indexOf("(") + 1,array[i].lastIndexOf(")"));
String indexSql = "CREATE INDEX " + elseName + " ON " + tableName + "(" + indexName + ");\r\n";
indexList.add(indexSql);
}
}
//逗号去除
String removeCommas = "";
if(createTableSql.contains(",") && createTableSql.contains(");")){
removeCommas = createTableSql.substring(createTableSql.lastIndexOf(",") + 1,createTableSql.lastIndexOf(");"));
}
if(removeCommas.equals("\r\n")){
String startChar = createTableSql.substring(0,createTableSql.lastIndexOf(","));
String endChar = createTableSql.substring(createTableSql.lastIndexOf(",") + 1);
createTableSql = startChar + endChar;
} }
} }
//msql的外键设置移动位置 previous = createTableSql;
if(lowerAndUpper(s,"FOREIGN") && lowerAndUpper(s,"KEY") && lowerAndUpper(s,"CONSTRAINT")){ createTableSql = "";
s = "ALTER TABLE \"public\".\"" + tableName + "\" ADD " + s + " ON DELETE NO ACTION ON UPDATE NO ACTION;\r\n"; bufferedWriter.write(previous);
foreignList.add(s);
s = "";
}else {
bufferedWriter.write(previous);
}
} }
previous = s;
} }
previous = s;
} }
//写入最后一句
bufferedWriter.write(previous);
//写入创建外键的sql语句 //写入创建外键的sql语句
for(String list:foreignList){ for(String list:foreignList){
bufferedWriter.write(list); bufferedWriter.write(list);
} }
//写入索引的sql语句
for(String list:indexList){
bufferedWriter.write(list);
}
bufferedWriter.flush(); bufferedWriter.flush();
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
...@@ -169,6 +213,14 @@ public class Regular { ...@@ -169,6 +213,14 @@ public class Regular {
} }
} }
public static int stringIndex(String s,String upper){
int index = s.indexOf(upper);
if(index == -1){
index = s.indexOf(upper.toLowerCase());
}
return index;
}
/** /**
* 大小写都替换 * 大小写都替换
*/ */
...@@ -219,12 +271,14 @@ public class Regular { ...@@ -219,12 +271,14 @@ public class Regular {
e.printStackTrace(); e.printStackTrace();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
} }
return null; return null;
} }
public static void main(String[] args) { public static void main(String[] args) {
mySqlRegular("C:\\Users\\admin\\Desktop\\database\\hrm.sql","else"); mySqlRegular("C:\\Users\\admin\\Desktop\\database\\hrm.sql","hrm");
} }
} }
...@@ -20,7 +20,7 @@ logging.file.path=./log/master.log ...@@ -20,7 +20,7 @@ logging.file.path=./log/master.log
# 指jpa对表生成的策略 # 指jpa对表生成的策略
spring.jpa.hibernate.ddl-auto=update spring.jpa.hibernate.ddl-auto=update
# 是否显示sql语句 # 是否显示sql语句
spring.jpa.show-sql=true spring.jpa.show-sql=false
# 格式化sql # 格式化sql
spring.jpa.properties.hibernate.format_sql=true spring.jpa.properties.hibernate.format_sql=true
spring.jpa.open-in-view=true spring.jpa.open-in-view=true
...@@ -33,4 +33,9 @@ spring.servlet.multipart.max-request-size=100MB ...@@ -33,4 +33,9 @@ spring.servlet.multipart.max-request-size=100MB
spring.thymeleaf.cache=false spring.thymeleaf.cache=false
spring.mvc.static-path-pattern=/** spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/uploads/ spring.resources.static-locations=classpath:/uploads/
\ No newline at end of file
#highgo
highgo.driver=org.postgresql.Driver
highgo.connectionType=postgresql
highgo.dbName=template1
\ No newline at end of file
...@@ -2,16 +2,13 @@ package com.zjty.adaptationmaster; ...@@ -2,16 +2,13 @@ package com.zjty.adaptationmaster;
public class Test4 { public class Test4 {
public static void main(String[] args) { public static void main(String[] args) {
String a = "CREATE TABLE \"routine_human_list\" (\n" + String a = "sdaf = df ccc = 18 adfasdf = utf8";
" \"routine_routine_id\" varchar(255) NOT NULL,\n" + int begin= a.indexOf("ccc");
" \"human_list\" varchar(255) DEFAULT NULL,\n" + for(int i = begin;i < a.length();i++){
")"; String m = a.charAt(i) + "";
String endChar = a.substring(a.lastIndexOf("\"") + 1); if(m.matches("\\d")){
if(endChar.contains(",")){ System.out.println(m);
String start = a.substring(0,a.lastIndexOf(",")); }
String end = a.substring(a.lastIndexOf(",") + 1);
a = start + end;
System.out.println(a);
} }
} }
} }
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论