SQL编辑器自动提示库、表、列逻辑优化,更加好用

This commit is contained in:
暮光:城中城
2021-06-20 17:47:46 +08:00
parent a30d9318da
commit 5abe56caad
14 changed files with 209 additions and 174 deletions

View File

@@ -83,31 +83,15 @@ public class DatabaseDocController {
} }
/** /**
* 不再使用此接口,优化了 * 获取数据源基本信息
* 获取编辑器所需的所有信息,用于自动补全 * @param sourceId 数据源ID
* 此接口会返回所有库表结构,介意的话请自己手动屏蔽调此接口 * @return 基本信息
*
* @param sourceId
* @return
*/ */
@Deprecated @PostMapping(value = "/getSourceBaseInfo")
@PostMapping(value = "/getEditorData") public ResponseJson getSourceBaseInfo(Long sourceId) {
public ResponseJson getEditorData(Long sourceId) {
// 没权限,返回空
if (!DocUserUtil.haveAuth(DocAuthConst.DB_DATASOURCE_MANAGE)
&& !DocUserUtil.haveCustomAuth(DbAuthType.VIEW.getName(), DocAuthConst.DB + sourceId)) {
return DocDbResponseJson.ok();
}
String cacheKey = CachePrefix.DB_EDITOR_DATA_CACHE + sourceId;
Object resultObj = CacheUtil.get(cacheKey);
if (resultObj != null) {
return DocDbResponseJson.ok(resultObj);
}
DbBaseService dbBaseService = databaseServiceFactory.getDbBaseService(sourceId); DbBaseService dbBaseService = databaseServiceFactory.getDbBaseService(sourceId);
Map<String, Object> dbResultMap = dbBaseService.getEditorData(sourceId); Map<String, Object> dbResultMap = new HashMap<>();
dbResultMap.put("product", dbBaseService.getDatabaseProduct().name().toLowerCase()); dbResultMap.put("product", dbBaseService.getDatabaseProduct().name().toLowerCase());
// 缓存10分钟如果10分钟内库里面增删改了表或字段则提示不出来
CacheUtil.put(cacheKey, dbResultMap, 6000);
return DocDbResponseJson.ok(dbResultMap); return DocDbResponseJson.ok(dbResultMap);
} }

View File

@@ -215,58 +215,6 @@ public abstract class DbBaseService {
return tableStatusVo; return tableStatusVo;
} }
/**
* 获取编辑器所需的所有信息,用于自动补全
* 此接口会返回所有库表结构,介意的话请自己手动屏蔽调此接口
*
* @param sourceId sourceId
* @author 暮光:城中城
* @since 2019年9月1日
*/
public Map<String, Object> getEditorData(Long sourceId) {
BaseMapper baseMapper = this.getViewAuthBaseMapper(sourceId);
DatabaseFactoryBean databaseFactoryBean = databaseRegistrationBean.getOrCreateFactoryById(sourceId);
List<DatabaseInfoDto> dbNameDtoList = baseMapper.getDatabaseList();
Map<String, List<TableInfoDto>> dbTableMap = new HashMap<>();
Map<String, List<TableColumnDescDto>> tableColumnsMap = new HashMap<>();
Map<String, List<TableInfoDto>> tableMapList = new HashMap<>();
// MYSQL可以一次性查询所有库表
if (databaseFactoryBean.getDatabaseProduct() == DatabaseProductEnum.MYSQL) {
List<TableInfoDto> dbTableList = baseMapper.getTableList(null);
tableMapList = dbTableList.stream().collect(Collectors.groupingBy(TableInfoDto::getDbName));
}
for (DatabaseInfoDto infoDto : dbNameDtoList) {
List<TableInfoDto> tableInfoDtoList = tableMapList.get(infoDto.getDbName());
// SQLSERVER必须要库才能查
if (databaseFactoryBean.getDatabaseProduct() == DatabaseProductEnum.SQLSERVER) {
tableInfoDtoList = baseMapper.getTableList(infoDto.getDbName());
}
if (CollectionUtils.isEmpty(tableInfoDtoList)) {
continue;
}
dbTableMap.put(infoDto.getDbName(), tableInfoDtoList);
// 小于10个库查所有库否则只查询当前链接的库防止库表太多数据量太大
// 如果觉得没必要就自己改吧!
Map<String, List<TableColumnDescDto>> columnDescDtoMap = new HashMap<>();
if (dbNameDtoList.size() <= 10 || Objects.equals(databaseFactoryBean.getDbName(), infoDto.getDbName())) {
List<TableColumnDescDto> columnDescDto = baseMapper.getTableColumnList(infoDto.getDbName(), null);
columnDescDtoMap = columnDescDto.stream().collect(Collectors.groupingBy(TableColumnDescDto::getTableName));
}
for (TableInfoDto tableInfoDto : tableInfoDtoList) {
List<TableColumnDescDto> descDtoList = columnDescDtoMap.get(tableInfoDto.getTableName());
if (CollectionUtils.isNotEmpty(descDtoList)) {
tableColumnsMap.put(tableInfoDto.getTableName(), descDtoList);
}
}
}
Map<String, Object> dbResultMap = new HashMap<>();
dbResultMap.put("db", dbNameDtoList);
dbResultMap.put("table", dbTableMap);
dbResultMap.put("column", tableColumnsMap);
return dbResultMap;
}
/** /**
* 获取存储过程列表 * 获取存储过程列表
* *

View File

@@ -1 +1 @@
<!DOCTYPE html><html lang=en><head><meta charset=utf-8><meta http-equiv=X-UA-Compatible content="IE=edge"><meta name=viewport content="width=device-width,initial-scale=1"><link rel=icon href=favicon-db.png><title>数据库文档管理</title><link href=css/app.f232fb4e.css rel=preload as=style><link href=css/chunk-vendors.8924efc6.css rel=preload as=style><link href=js/app.582f8c0f.js rel=preload as=script><link href=js/chunk-vendors.d15e5982.js rel=preload as=script><link href=css/chunk-vendors.8924efc6.css rel=stylesheet><link href=css/app.f232fb4e.css rel=stylesheet></head><body><noscript><strong>We're sorry but zyplayer-db-ui doesn't work properly without JavaScript enabled. Please enable it to continue.</strong></noscript><div id=app></div><script src=js/chunk-vendors.d15e5982.js></script><script src=js/app.582f8c0f.js></script></body></html> <!DOCTYPE html><html lang=en><head><meta charset=utf-8><meta http-equiv=X-UA-Compatible content="IE=edge"><meta name=viewport content="width=device-width,initial-scale=1"><link rel=icon href=favicon-db.png><title>数据库文档管理</title><link href=css/app.f232fb4e.css rel=preload as=style><link href=css/chunk-vendors.8924efc6.css rel=preload as=style><link href=js/app.1c02b763.js rel=preload as=script><link href=js/chunk-vendors.22b87709.js rel=preload as=script><link href=css/chunk-vendors.8924efc6.css rel=stylesheet><link href=css/app.f232fb4e.css rel=stylesheet></head><body><noscript><strong>We're sorry but zyplayer-db-ui doesn't work properly without JavaScript enabled. Please enable it to continue.</strong></noscript><div id=app></div><script src=js/chunk-vendors.22b87709.js></script><script src=js/app.1c02b763.js></script></body></html>

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -8,8 +8,8 @@ export default {
queryTableDdl: data => { queryTableDdl: data => {
return request({url: '/zyplayer-doc-db/doc-db/getTableDdl', method: 'post', data: Qs.stringify(data)}); return request({url: '/zyplayer-doc-db/doc-db/getTableDdl', method: 'post', data: Qs.stringify(data)});
}, },
getEditorData: data => { getSourceBaseInfo: data => {
return request({url: '/zyplayer-doc-db/doc-db/getEditorData', method: 'post', data: Qs.stringify(data)}); return request({url: '/zyplayer-doc-db/doc-db/getSourceBaseInfo', method: 'post', data: Qs.stringify(data)});
}, },
datasourceList: data => { datasourceList: data => {
return request({url: '/zyplayer-doc-db/doc-db/getDataSourceList', method: 'post', data: Qs.stringify(data)}); return request({url: '/zyplayer-doc-db/doc-db/getDataSourceList', method: 'post', data: Qs.stringify(data)});

View File

@@ -8,6 +8,7 @@ export default {
source: {}, source: {},
databaseInfo: {}, databaseInfo: {},
tableInfo: {}, tableInfo: {},
columnInfo: {},
lastCallbackArr: [], lastCallbackArr: [],
change(source) { change(source) {
this.source = source; this.source = source;
@@ -19,6 +20,7 @@ export default {
let languageTools = ace.acequire("ace/ext/language_tools"); let languageTools = ace.acequire("ace/ext/language_tools");
languageTools.addCompleter(this); languageTools.addCompleter(this);
} }
// 初始加载
if (!!this.source.sourceId) { if (!!this.source.sourceId) {
// 加载所有库 // 加载所有库
let databaseList = this.databaseInfo[this.source.sourceId] || []; let databaseList = this.databaseInfo[this.source.sourceId] || [];
@@ -29,36 +31,52 @@ export default {
} }
// 加载库下所有表 // 加载库下所有表
if (!!this.source.dbName) { if (!!this.source.dbName) {
let tableList = this.tableInfo[this.source.sourceId + '_' + this.source.dbName] || []; let tableKey = this.source.sourceId + '_' + this.source.dbName;
let tableList = this.tableInfo[tableKey] || [];
if (tableList.length <= 0) { if (tableList.length <= 0) {
datasourceApi.tableList({sourceId: this.source.sourceId, dbName: this.source.dbName}).then(json => { datasourceApi.tableList({sourceId: this.source.sourceId, dbName: this.source.dbName}).then(json => {
this.tableInfo[this.source.sourceId + '_' + this.source.dbName] = json.data || []; this.tableInfo[tableKey] = json.data || [];
});
}
}
// 加载表下所有字段
if (!!this.source.tableName) {
let columnKey = this.source.sourceId + '_' + this.source.dbName + '_' + this.source.tableName;
let columnList = this.columnInfo[columnKey] || [];
if (columnList.length <= 0) {
datasourceApi.tableColumnList({sourceId: this.source.sourceId, dbName: this.source.dbName, tableName: this.source.tableName}).then(json => {
this.columnInfo[columnKey] = json.data.columnList || [];
}); });
} }
} }
} }
}, },
getCompletions(editor, session, pos, prefix, callback) { async getCompletions(editor, session, pos, prefix, callback) {
let callbackArr = []; let callbackArr = [];
let lineStr = session.getLine(pos.row).substring(0, pos.column - 1); let lineStr = session.getLine(pos.row).substring(0, pos.column - 1);
// console.log("Executor.vue getCompletionssourceId" + JSON.stringify(this.source) + ' lineStr'+ lineStr, pos); console.log("Executor.vue getCompletionssourceId" + JSON.stringify(this.source) + ' lineStr' + lineStr, pos);
if (lineStr.endsWith("from ") || lineStr.endsWith("join ")) { if (!!this.source.tableName) {
this.getDatabasesAndTables(callbackArr); // 如果指定了表名,则只提示字段,其他都不用管,用在表数据查看页面
callbackArr = await this.getAssignTableColumns(this.source.dbName, this.source.tableName);
callback(null, callbackArr);
} else if (lineStr.endsWith("from ") || lineStr.endsWith("join ")) {
callbackArr = this.getDatabasesAndTables();
this.lastCallbackArr = callbackArr; this.lastCallbackArr = callbackArr;
callback(null, callbackArr); callback(null, callbackArr);
} else if (lineStr.endsWith(".")) { } else if (lineStr.endsWith(".")) {
this.getTablesAndColumns(callbackArr, lineStr); callbackArr = await this.getTablesAndColumns(lineStr);
this.lastCallbackArr = callbackArr; this.lastCallbackArr = callbackArr;
callback(null, callbackArr); callback(null, callbackArr);
} else if (lineStr.endsWith("select ") || lineStr.endsWith("where ") || lineStr.endsWith("and ")) { } else if (lineStr.endsWith("select ") || lineStr.endsWith("where ") || lineStr.endsWith("and ") || lineStr.endsWith("or ")) {
this.getTableColumns(callbackArr, session, pos); callbackArr = await this.getTableColumns(session, pos);
this.lastCallbackArr = callbackArr; this.lastCallbackArr = callbackArr;
callback(null, callbackArr); callback(null, callbackArr);
} else { } else {
callback(null, this.lastCallbackArr); callback(null, this.lastCallbackArr);
} }
}, },
getDatabasesAndTables(callbackArr) { getDatabasesAndTables() {
let callbackArr = [];
// 所有表 // 所有表
let tableList = this.tableInfo[this.source.sourceId + '_' + this.source.dbName] || []; let tableList = this.tableInfo[this.source.sourceId + '_' + this.source.dbName] || [];
tableList.forEach(item => callbackArr.push({ tableList.forEach(item => callbackArr.push({
@@ -77,12 +95,15 @@ export default {
type: "snippet", type: "snippet",
score: 1000 score: 1000
})); }));
return callbackArr;
}, },
getTablesAndColumns(callbackArr, lineStr) { async getTablesAndColumns(lineStr) {
let isFound = false; let isFound = false;
let callbackArr = [];
// 匹配 库名. 搜索表名 // 匹配 库名. 搜索表名
let databaseList = this.databaseInfo[this.source.sourceId] || []; let databaseList = this.databaseInfo[this.source.sourceId] || [];
databaseList.forEach(async item => { for (let i = 0; i < databaseList.length; i++) {
let item = databaseList[i];
if (lineStr.endsWith(item.dbName + ".")) { if (lineStr.endsWith(item.dbName + ".")) {
let tableList = this.tableInfo[this.source.sourceId + '_' + item.dbName] || []; let tableList = this.tableInfo[this.source.sourceId + '_' + item.dbName] || [];
if (tableList.length <= 0) { if (tableList.length <= 0) {
@@ -99,33 +120,20 @@ export default {
})); }));
isFound = true; isFound = true;
} }
}); }
// 未找到,匹配 表名. 搜索字段名 // 未找到,匹配 表名. 搜索字段名
// if (!isFound) { if (!isFound) {
// for (let key in this.editorColumnInfo) { let tableList = this.tableInfo[this.source.sourceId + '_' + this.source.dbName] || [];
// if (!lineStr.endsWith(key + ".")) { for (let i = 0; i < tableList.length; i++) {
// continue; let tableName = tableList[i].tableName;
// } if (lineStr.endsWith(tableName + ".")) {
// let columnInfo = this.editorColumnInfo[key]; callbackArr = await this.getAssignTableColumns(this.source.dbName, tableName);
// if (!!columnInfo) { }
// for (let i = 0; i < columnInfo.length; i++) { }
// let caption = (!!columnInfo[i].description) ? columnInfo[i].name + "-" + columnInfo[i].description : columnInfo[i].name; }
// callbackArr.push({ return callbackArr;
// caption: caption,
// snippet: columnInfo[i].name,
// meta: "column",
// type: "snippet",
// score: 1000
// });
// }
// isFound = true;
// }
// }
// }
}, },
getTableColumns(callbackArr, session, pos) { async getTableColumns(session, pos) {
return;
let isFound = false;
let queryText = ""; let queryText = "";
// 往前加 // 往前加
for (let i = pos.row; i >= 0; i--) { for (let i = pos.row; i >= 0; i--) {
@@ -144,27 +152,46 @@ export default {
} }
} }
// 所有表,找下面的字段列表 // 所有表,找下面的字段列表
for (let key in this.editorDbTableInfo) { let callbackArr = [];
let tableInfo = this.editorDbTableInfo[key]; let tableList = this.tableInfo[this.source.sourceId + '_' + this.source.dbName] || [];
for (let i = 0; i < tableInfo.length; i++) { for (let i = 0; i < tableList.length; i++) {
if (queryText.indexOf(tableInfo[i].tableName) < 0) { let tableName = tableList[i].tableName;
continue; if (queryText.indexOf(tableName) >= 0) {
let tempArr = await this.getAssignTableColumns(this.source.dbName, tableName);
callbackArr = callbackArr.concat(tempArr);
} }
let columnInfo = this.editorColumnInfo[tableInfo[i].tableName]; }
if (!!columnInfo) { return callbackArr;
for (let j = 0; j < columnInfo.length; j++) { },
let caption = (!!columnInfo[j].description) ? columnInfo[j].name + "-" + columnInfo[j].description : columnInfo[j].name;
/**
* 获取指定数据表的字段
* @param dbName
* @param tableName
*/
async getAssignTableColumns(dbName, tableName) {
let columnKey = this.source.sourceId + '_' + dbName + '_' + tableName;
let columnList = this.columnInfo[columnKey] || [];
if (columnList.length <= 0) {
let res = await datasourceApi.tableColumnList({
sourceId: this.source.sourceId,
dbName: dbName,
tableName: tableName
});
columnList = res.data.columnList || [];
this.columnInfo[columnKey] = columnList;
}
let callbackArr = [];
columnList.forEach(item => {
let caption = (!!item.description) ? item.name + "-" + item.description : item.name;
callbackArr.push({ callbackArr.push({
caption: caption, caption: caption,
snippet: columnInfo[j].name, snippet: item.name,
meta: "column", meta: "字段",
type: "snippet", type: "snippet",
score: 1000 score: 1000
}); });
} });
isFound = true; return callbackArr;
}
}
}
} }
} }

View File

@@ -5,7 +5,7 @@ import 'brace/snippets/sql';
import 'brace/mode/json'; import 'brace/mode/json';
import 'brace/snippets/json'; import 'brace/snippets/json';
import 'brace/theme/monokai'; import 'brace/theme/monokai';
import complater from './DatabaseCompleter' import completer from './DatabaseCompleter'
export default { export default {
render: function (h) { render: function (h) {
@@ -59,7 +59,7 @@ export default {
}) })
}, },
source: function (source) { source: function (source) {
complater.change(source); completer.change(source);
}, },
}, },
beforeDestroy: function () { beforeDestroy: function () {
@@ -67,7 +67,7 @@ export default {
this.editor.container.remove(); this.editor.container.remove();
}, },
activated: function () { activated: function () {
complater.change(this.source); completer.change(this.source);
}, },
mounted: function () { mounted: function () {
let vm = this; let vm = this;
@@ -88,14 +88,14 @@ export default {
let content = editor.getValue(); let content = editor.getValue();
vm.$emit('input', content); vm.$emit('input', content);
vm.contentBackup = content; vm.contentBackup = content;
// 内容改变就执行输入提示功能,todo 某些情况下应当不提示 // 内容改变就执行输入提示功能,和自动的冲突了,感觉自动的就符合了,但是按空格他不出现提示
// console.log('change content' + content); // console.log('change content' + content);
// editor.execCommand("startAutocomplete"); // editor.execCommand("startAutocomplete");
}); });
if (vm.options) { if (vm.options) {
editor.setOptions(vm.options); editor.setOptions(vm.options);
} }
complater.change(this.source); completer.change(this.source);
}, },
methods: { methods: {
px: function (n) { px: function (n) {

View File

@@ -346,8 +346,7 @@
let choiceData = this.choiceResultObj[this.executeShowTable] || []; let choiceData = this.choiceResultObj[this.executeShowTable] || [];
if (choiceData.length > 0) { if (choiceData.length > 0) {
let dataCols = this.executeResultList.find(item => item.name === this.executeShowTable).dataCols; let dataCols = this.executeResultList.find(item => item.name === this.executeShowTable).dataCols;
let tableName = '`' + this.pageParam.dbName + '`.`' + this.pageParam.tableName + '`'; let copyData = copyFormatter.format('update', this.pageParam.dbType, dataCols, choiceData, this.conditionDataColsChoice, this.pageParam.dbName, this.pageParam.tableName);
let copyData = copyFormatter.format('update', this.editorDbProduct, dataCols, choiceData, this.conditionDataColsChoice, tableName);
this.conditionDataColsChoice = []; this.conditionDataColsChoice = [];
this.exportConditionVisible = false; this.exportConditionVisible = false;
this.$copyText(copyData).then( this.$copyText(copyData).then(
@@ -366,8 +365,7 @@
this.exportConditionVisible = true; this.exportConditionVisible = true;
return; return;
} }
let tableName = '`' + this.pageParam.dbName + '`.`' + this.pageParam.tableName + '`'; let copyData = copyFormatter.format(type, this.pageParam.dbType, dataCols, choiceData, '', this.pageParam.dbName, this.pageParam.tableName);
let copyData = copyFormatter.format(type, this.editorDbProduct, dataCols, choiceData, '', tableName);
this.$copyText(copyData).then( this.$copyText(copyData).then(
res => this.$message.success("内容已复制到剪切板!"), res => this.$message.success("内容已复制到剪切板!"),
err => this.$message.error("抱歉,复制失败!") err => this.$message.error("抱歉,复制失败!")

View File

@@ -304,6 +304,7 @@
this.choiceDatasourceId = this.datasourceList[0].id; this.choiceDatasourceId = this.datasourceList[0].id;
this.executorSource = {sourceId: this.choiceDatasourceId}; this.executorSource = {sourceId: this.choiceDatasourceId};
this.loadDatabaseList(); this.loadDatabaseList();
this.loadSourceBaseInfo();
} }
}); });
}, },
@@ -319,13 +320,10 @@
} }
}); });
}, },
loadEditorData() { loadSourceBaseInfo() {
datasourceApi.getEditorData({sourceId: this.choiceDatasourceId}).then(json => { datasourceApi.getSourceBaseInfo({sourceId: this.choiceDatasourceId}).then(json => {
let data = json.data || {}; let data = json.data || {};
this.editorDbInfo = data.db || [];
this.editorDbProduct = data.product || ''; this.editorDbProduct = data.product || '';
this.editorDbTableInfo = data.table || {};
this.editorColumnInfo = data.column || {};
}); });
}, },
sourceGroupChangeEvents() { sourceGroupChangeEvents() {
@@ -341,11 +339,13 @@
this.choiceDatasourceId = datasourceOptions[0].id; this.choiceDatasourceId = datasourceOptions[0].id;
this.executorSource = {sourceId: this.choiceDatasourceId}; this.executorSource = {sourceId: this.choiceDatasourceId};
this.loadDatabaseList(); this.loadDatabaseList();
this.loadSourceBaseInfo();
} }
}, },
datasourceChangeEvents() { datasourceChangeEvents() {
this.executorSource = {sourceId: this.choiceDatasourceId}; this.executorSource = {sourceId: this.choiceDatasourceId};
this.loadDatabaseList(); this.loadDatabaseList();
this.loadSourceBaseInfo();
}, },
databaseChangeEvents() { databaseChangeEvents() {
this.executorSource = {sourceId: this.choiceDatasourceId, dbName: this.choiceDatabase}; this.executorSource = {sourceId: this.choiceDatasourceId, dbName: this.choiceDatabase};
@@ -392,7 +392,7 @@
let choiceData = this.choiceResultObj[this.executeShowTable] || []; let choiceData = this.choiceResultObj[this.executeShowTable] || [];
if (choiceData.length > 0) { if (choiceData.length > 0) {
let dataCols = this.executeResultList.find(item => item.name === this.executeShowTable).dataCols; let dataCols = this.executeResultList.find(item => item.name === this.executeShowTable).dataCols;
let copyData = copyFormatter.format('update', this.editorDbProduct, dataCols, choiceData, this.conditionDataColsChoice, '`table`'); let copyData = copyFormatter.format('update', this.editorDbProduct, dataCols, choiceData, this.conditionDataColsChoice);
this.conditionDataColsChoice = []; this.conditionDataColsChoice = [];
this.exportConditionVisible = false; this.exportConditionVisible = false;
this.$copyText(copyData).then( this.$copyText(copyData).then(
@@ -411,7 +411,7 @@
this.exportConditionVisible = true; this.exportConditionVisible = true;
return; return;
} }
let copyData = copyFormatter.format(type, this.editorDbProduct, dataCols, choiceData, '', '`table`'); let copyData = copyFormatter.format(type, this.editorDbProduct, dataCols, choiceData, '');
this.$copyText(copyData).then( this.$copyText(copyData).then(
res => this.$message.success("内容已复制到剪切板!"), res => this.$message.success("内容已复制到剪切板!"),
err => this.$message.error("抱歉,复制失败!") err => this.$message.error("抱歉,复制失败!")

View File

@@ -4,12 +4,14 @@
* @since 2021年5月23日 * @since 2021年5月23日
*/ */
export default { export default {
insert(dataCols, choiceData, tableName = '`table`') { insert(dataCols, choiceData, dbName, tableName) {
let tableNameRes = (!!dbName) ? '`' + dbName + '`.`' : '';
tableNameRes += (!!tableName) ? tableName : '`table`';
// 复制为insert语句 // 复制为insert语句
let copyData = ''; let copyData = '';
let names = ''; let names = '';
dataCols.forEach(col => { dataCols.forEach(col => {
if (names.length > 0) names += ', ' if (names.length > 0) names += ', ';
names += col.prop; names += col.prop;
}); });
choiceData.forEach(item => { choiceData.forEach(item => {
@@ -24,40 +26,44 @@ export default {
values += "'" + val + "'"; values += "'" + val + "'";
} }
}); });
copyData += 'insert into ' + tableName + ' (' + names + ') values (' + values + ');\n'; copyData += 'insert into ' + tableNameRes + ' (' + names + ') values (' + values + ');\n';
}); });
return copyData; return copyData;
}, },
update(dataCols, choiceData, condition=[], tableName = '`table`') { update(dataCols, choiceData, condition=[], dbName, tableName) {
let tableNameRes = (!!dbName) ? '`' + dbName + '`.`' : '';
tableNameRes += (!!tableName) ? tableName : '`table`';
// 复制为update语句 // 复制为update语句
let copyData = ''; let copyData = '';
choiceData.forEach(item => { choiceData.forEach(item => {
let values = '', where = ''; let values = '', where = '';
dataCols.forEach(col => { dataCols.forEach(col => {
if (values.length > 0) values += ', ';
values += col.prop + '=';
let val = item[col.prop] || ''; let val = item[col.prop] || '';
if (typeof val === 'number' && !isNaN(val)) {
values += val;
if (condition.indexOf(col.prop) >= 0) { if (condition.indexOf(col.prop) >= 0) {
if (typeof val === 'number' && !isNaN(val)) {
if (where.length > 0) where += ' and '; if (where.length > 0) where += ' and ';
where += col.prop + ' = ' + val; where += col.prop + ' = ' + val;
} else {
if (where.length > 0) where += ' and ';
where += col.prop + ' = ' + "'" + val + "'";
} }
} else {
if (values.length > 0) values += ', ';
values += col.prop + '=';
if (typeof val === 'number' && !isNaN(val)) {
values += val;
} else { } else {
val = String(val).replaceAll('\'', '\'\''); val = String(val).replaceAll('\'', '\'\'');
values += "'" + val + "'"; values += "'" + val + "'";
if (condition.indexOf(col.prop) >= 0) {
if (where.length > 0) where += ' and ';
where += col.prop + ' = ' + "'" + val + "'";
} }
} }
}); });
if (where.length > 0) where = ' where ' + where; if (where.length > 0) where = ' where ' + where;
copyData += 'update ' + tableName + ' set ' + values + where + ';\n'; copyData += 'update ' + tableNameRes + ' set ' + values + where + ';\n';
}); });
return copyData; return copyData;
}, },
json(dataCols, choiceData, tableName) { json(dataCols, choiceData, dbName, tableName) {
// 复制为json // 复制为json
return JSON.stringify(choiceData); return JSON.stringify(choiceData);
}, },

View File

@@ -1,22 +1,24 @@
import base from './base' import base from './base'
import sqlserver from './sqlserver'
export default { export default {
format(type, product, dataCols, choiceData, condition, tableName) { format(type, product, dataCols, choiceData, condition, dbName, tableName) {
let formatter = this.getProduct(product); let formatter = this.getProduct(product);
if (type === 'insert') { if (type === 'insert') {
// 复制为insert语句 // 复制为insert语句
return formatter.insert(dataCols, choiceData, tableName); return formatter.insert(dataCols, choiceData, dbName, tableName);
} else if (type === 'update') { } else if (type === 'update') {
// 复制为update语句 // 复制为update语句
return formatter.update(dataCols, choiceData, condition, tableName); return formatter.update(dataCols, choiceData, condition, dbName, tableName);
} else if (type === 'json') { } else if (type === 'json') {
// 复制为json // 复制为json
return formatter.json(dataCols, choiceData, tableName); return formatter.json(dataCols, choiceData, dbName, tableName);
} }
}, },
getProduct(product) { getProduct(product) {
if (product === 'mysql') { // 不同数据源类型可以用不用的处理器类型
// 不同数据源类型可以用不用的处理器类型,暂时只实现了一套基础的 if (product === 'sqlserver') {
return sqlserver;
} }
return base; return base;
}, },

View File

@@ -0,0 +1,70 @@
/**
* 通用的转换器,如果通用的不能满足需要添加转换器实现转换
* @author 暮光:城中城
* @since 2021年5月23日
*/
export default {
insert(dataCols, choiceData, dbName, tableName) {
let tableNameRes = (!!dbName) ? dbName + '..' : '';
tableNameRes += (!!tableName) ? tableName : 'table';
// 复制为insert语句
let copyData = '';
let names = '';
dataCols.forEach(col => {
if (names.length > 0) names += ', ';
names += col.prop;
});
choiceData.forEach(item => {
let values = '';
dataCols.forEach(col => {
if (values.length > 0) values += ', ';
let val = item[col.prop] || '';
if (typeof val === 'number' && !isNaN(val)) {
values += val;
} else {
val = String(val).replaceAll('\'', '\'\'');
values += "'" + val + "'";
}
});
copyData += 'insert into ' + tableNameRes + ' (' + names + ') values (' + values + ');\n';
});
return copyData;
},
update(dataCols, choiceData, condition=[], dbName, tableName) {
let tableNameRes = (!!dbName) ? dbName + '..' : '';
tableNameRes += (!!tableName) ? tableName : 'table';
// 复制为update语句
let copyData = '';
choiceData.forEach(item => {
let values = '', where = '';
dataCols.forEach(col => {
let val = item[col.prop] || '';
if (condition.indexOf(col.prop) >= 0) {
if (typeof val === 'number' && !isNaN(val)) {
if (where.length > 0) where += ' and ';
where += col.prop + ' = ' + val;
} else {
if (where.length > 0) where += ' and ';
where += col.prop + ' = ' + "'" + val + "'";
}
} else {
if (values.length > 0) values += ', ';
values += col.prop + '=';
if (typeof val === 'number' && !isNaN(val)) {
values += val;
} else {
val = String(val).replaceAll('\'', '\'\'');
values += "'" + val + "'";
}
}
});
if (where.length > 0) where = ' where ' + where;
copyData += 'update ' + tableNameRes + ' set ' + values + where + ';\n';
});
return copyData;
},
json(dataCols, choiceData, dbName, tableName) {
// 复制为json
return JSON.stringify(choiceData);
},
}