提交 89556ec4 编写于 作者: Mr.奇淼('s avatar Mr.奇淼(

可从数据库获取字段

上级 521f28c8
...@@ -2,6 +2,7 @@ package v1 ...@@ -2,6 +2,7 @@ package v1
import ( import (
"fmt" "fmt"
"gin-vue-admin/global"
"gin-vue-admin/global/response" "gin-vue-admin/global/response"
"gin-vue-admin/model" "gin-vue-admin/model"
"gin-vue-admin/service" "gin-vue-admin/service"
...@@ -87,3 +88,61 @@ func CreateTemp(c *gin.Context) { ...@@ -87,3 +88,61 @@ func CreateTemp(c *gin.Context) {
os.Remove("./ginvueadmin.zip") os.Remove("./ginvueadmin.zip")
} }
} }
// @Tags SysApi
// @Summary 获取当前数据库所有表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /autoCode/getTables [get]
func GetTables(c *gin.Context) {
dbName := c.DefaultQuery("dbName", global.GVA_CONFIG.Mysql.Dbname)
err, tables := service.GetTables(dbName)
if err != nil {
response.FailWithMessage(fmt.Sprintf("查询table失败,%v", err), c)
} else {
response.OkWithData(gin.H{
"tables": tables,
}, c)
}
}
// @Tags SysApi
// @Summary 获取当前所有数据库
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /autoCode/getDatabase [get]
func GetDB(c *gin.Context) {
err, dbs := service.GetDB()
if err != nil {
response.FailWithMessage(fmt.Sprintf("查询table失败,%v", err), c)
} else {
response.OkWithData(gin.H{
"dbs": dbs,
}, c)
}
}
// @Tags SysApi
// @Summary 获取当前表所有字段
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /autoCode/getDatabase [get]
func GetColume(c *gin.Context) {
dbName := c.DefaultQuery("dbName", global.GVA_CONFIG.Mysql.Dbname)
tableName := c.Query("tableName")
err, columes := service.GetColume(tableName, dbName)
if err != nil {
response.FailWithMessage(fmt.Sprintf("查询table失败,%v", err), c)
} else {
response.OkWithData(gin.H{
"columes": columes,
}, c)
}
}
...@@ -14,7 +14,7 @@ require ( ...@@ -14,7 +14,7 @@ require (
github.com/go-openapi/swag v0.19.8 // indirect github.com/go-openapi/swag v0.19.8 // indirect
github.com/go-playground/validator/v10 v10.3.0 // indirect github.com/go-playground/validator/v10 v10.3.0 // indirect
github.com/go-redis/redis v6.15.7+incompatible github.com/go-redis/redis v6.15.7+incompatible
github.com/go-sql-driver/mysql v1.5.0 // indirect github.com/go-sql-driver/mysql v1.5.0
github.com/golang/protobuf v1.4.2 // indirect github.com/golang/protobuf v1.4.2 // indirect
github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869 // indirect github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869 // indirect
github.com/jinzhu/gorm v1.9.12 github.com/jinzhu/gorm v1.9.12
...@@ -32,8 +32,8 @@ require ( ...@@ -32,8 +32,8 @@ require (
github.com/pelletier/go-toml v1.6.0 // indirect github.com/pelletier/go-toml v1.6.0 // indirect
github.com/piexlmax/gvaplug v0.0.8 github.com/piexlmax/gvaplug v0.0.8
github.com/pkg/errors v0.9.1 // indirect github.com/pkg/errors v0.9.1 // indirect
github.com/qiniu/x v1.10.5
github.com/qiniu/api.v7/v7 v7.4.1 github.com/qiniu/api.v7/v7 v7.4.1
github.com/qiniu/x v1.10.5
github.com/satori/go.uuid v1.2.0 github.com/satori/go.uuid v1.2.0
github.com/spf13/afero v1.2.2 // indirect github.com/spf13/afero v1.2.2 // indirect
github.com/spf13/cast v1.3.1 // indirect github.com/spf13/cast v1.3.1 // indirect
......
package request
type DBReq struct {
Database string `json:"database";gorm:"column:database"`
}
type TableReq struct {
TableName string `json:"tableName"`
}
type ColumeReq struct {
ColumeName string `json:"columeName";gorm:"column:colume_name"`
DataType string `json:"dataType";gorm:"column:data_type"`
ColumeComment string `json:"columeComment";gorm:"column:colume_comment"`
}
...@@ -2,13 +2,16 @@ package router ...@@ -2,13 +2,16 @@ package router
import ( import (
"gin-vue-admin/api/v1" "gin-vue-admin/api/v1"
"gin-vue-admin/middleware"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
func InitAutoCodeRouter(Router *gin.RouterGroup) { func InitAutoCodeRouter(Router *gin.RouterGroup) {
AutoCodeRouter := Router.Group("autoCode").Use(middleware.JWTAuth()).Use(middleware.CasbinHandler()) AutoCodeRouter := Router.Group("autoCode")
{ {
AutoCodeRouter.POST("createTemp", v1.CreateTemp) // 创建自动化代码 AutoCodeRouter.POST("createTemp", v1.CreateTemp) // 创建自动化代码
AutoCodeRouter.GET("getTables", v1.GetTables) // 获取对应数据库的表
AutoCodeRouter.GET("getDB", v1.GetDB) // 获取数据库
AutoCodeRouter.GET("getColume", v1.GetColume) // 获取指定表所有字段信息
} }
} }
package service package service
import ( import (
"gin-vue-admin/global"
"gin-vue-admin/model" "gin-vue-admin/model"
"gin-vue-admin/model/request"
"gin-vue-admin/utils" "gin-vue-admin/utils"
"io/ioutil" "io/ioutil"
"os" "os"
...@@ -115,3 +117,18 @@ func GetAllTplFile(pathName string, fileList []string) ([]string, error) { ...@@ -115,3 +117,18 @@ func GetAllTplFile(pathName string, fileList []string) ([]string, error) {
} }
return fileList, err return fileList, err
} }
func GetTables(dbName string) (err error, TableNames []request.TableReq) {
err = global.GVA_DB.Raw("select table_name from information_schema.tables where table_schema= ? and table_type= ? ", dbName, "base table").Scan(&TableNames).Error
return err, TableNames
}
func GetDB() (err error, DBNames []request.DBReq) {
err = global.GVA_DB.Raw("SELECT SCHEMA_NAME AS `database` FROM INFORMATION_SCHEMA.SCHEMATA;").Scan(&DBNames).Error
return err, DBNames
}
func GetColume(tableName string, dbName string) (err error, Columes []request.ColumeReq) {
err = global.GVA_DB.Raw("select COLUMN_NAME as 'colume_name', DATA_TYPE as 'data_type', COLUMN_COMMENT as 'colume_comment' from information_schema.COLUMNS where table_name = ? and table_schema = ?", tableName, dbName).Scan(&Columes).Error
return err, Columes
}
...@@ -18,4 +18,51 @@ export const createTemp = (data) => { ...@@ -18,4 +18,51 @@ export const createTemp = (data) => {
data, data,
responseType: 'blob' responseType: 'blob'
}) })
}
// @Tags SysApi
// @Summary 获取当前所有数据库
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /autoCode/getDatabase [get]
export const getDB = () => {
return service({
url: "/autoCode/getDB",
method: 'get',
})
}
// @Tags SysApi
// @Summary 获取当前数据库所有表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /autoCode/getTables [get]
export const getTable = (params) => {
return service({
url: "/autoCode/getTables",
method: 'get',
params,
})
}
// @Tags SysApi
// @Summary 获取当前数据库所有表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /autoCode/getColume [get]
export const getColume = (params) => {
return service({
url: "/autoCode/getColume",
method: 'get',
params,
})
} }
\ No newline at end of file
...@@ -29,7 +29,7 @@ ...@@ -29,7 +29,7 @@
</el-form-item> </el-form-item>
<el-form-item label="Field数据类型" prop="fieldType"> <el-form-item label="Field数据类型" prop="fieldType">
<el-col :span="8"> <el-col :span="8">
<el-select v-model="dialogMiddle.fieldType" placeholder="请选择field数据类型"> <el-select v-model="dialogMiddle.fieldType" placeholder="请选择field数据类型" @change="getDbfdOptions">
<el-option <el-option
v-for="item in typeOptions" v-for="item in typeOptions"
:key="item.value" :key="item.value"
...@@ -39,9 +39,22 @@ ...@@ -39,9 +39,22 @@
</el-select> </el-select>
</el-col> </el-col>
</el-form-item> </el-form-item>
<el-form-item label="数据库字段类型" prop="dbFieldType">
<el-col :span="8">
<el-select :disabled="!dialogMiddle.fieldType" v-model="dialogMiddle.dbFieldType" placeholder="请选择数据库字段类型">
<el-option
v-for="item in dbfdOptions"
:key="item.label"
:label="item.label"
:value="item.label">
</el-option>
</el-select>
</el-col>
</el-form-item>
<el-form-item label="Field查询条件" prop="fieldSearchType"> <el-form-item label="Field查询条件" prop="fieldSearchType">
<el-col :span="8"> <el-col :span="8">
<el-select v-model="dialogMiddle.fieldSearchType" placeholder="请选择field数据类型"> <el-select v-model="dialogMiddle.fieldSearchType" placeholder="请选择Field查询条件">
<el-option <el-option
v-for="item in typeSearchOptions" v-for="item in typeSearchOptions"
:key="item.value" :key="item.value"
...@@ -55,6 +68,7 @@ ...@@ -55,6 +68,7 @@
</div> </div>
</template> </template>
<script> <script>
import {getDict} from '@/utils/dictionary'
export default { export default {
name:"FieldDialog", name:"FieldDialog",
props:{ props:{
...@@ -67,6 +81,7 @@ export default { ...@@ -67,6 +81,7 @@ export default {
}, },
data(){ data(){
return{ return{
dbfdOptions:[],
visible:false, visible:false,
typeSearchOptions:[ typeSearchOptions:[
{ {
...@@ -122,6 +137,17 @@ export default { ...@@ -122,6 +137,17 @@ export default {
} }
}, },
methods: {
async getDbfdOptions(){
if(this.dialogMiddle.fieldType){
const res = await getDict(this.dialogMiddle.fieldType)
this.dbfdOptions = res
}
}
},
created() {
this.getDbfdOptions()
},
} }
</script> </script>
<style lang="scss"> <style lang="scss">
......
<template> <template>
<div> <div>
<!-- 从数据库直接获取字段 -->
<el-form ref="getTableForm" :inline="true" :model="dbform" label-width="120px">
<el-form-item label="数据库名" prop="structName">
<el-select @change="getTable" v-model="dbform.dbName" filterable placeholder="请选择数据库">
<el-option
v-for="item in dbOptions"
:key="item.database"
:label="item.database"
:value="item.database"
></el-option>
</el-select>
</el-form-item>
<el-form-item label="表名" prop="structName">
<el-select
v-model="dbform.tableName"
:disabled="!dbform.dbName"
filterable
placeholder="请选择表"
>
<el-option
v-for="item in tableOptions"
:key="item.tableName"
:label="item.tableName"
:value="item.tableName"
></el-option>
</el-select>
</el-form-item>
<el-form-item>
<el-button @click="getColume" type="primary">使用此表创建</el-button>
</el-form-item>
<el-form-item>
<span style="color:red">可以在此处选择数据库表直接根据表结构创建</span>
</el-form-item>
</el-form>
<el-divider></el-divider>
<!-- 初始版本自动化代码工具 --> <!-- 初始版本自动化代码工具 -->
<el-form ref="autoCodeForm" :rules="rules" :model="form" label-width="120px" :inline="true"> <el-form ref="autoCodeForm" :rules="rules" :model="form" label-width="120px" :inline="true">
<el-form-item label="Struct名称" prop="structName"> <el-form-item label="Struct名称" prop="structName">
...@@ -23,27 +59,35 @@ ...@@ -23,27 +59,35 @@
<el-button @click="editAndAddField()" type="primary">新增Field</el-button> <el-button @click="editAndAddField()" type="primary">新增Field</el-button>
</div> </div>
<el-table :data="form.fields" border stripe> <el-table :data="form.fields" border stripe>
<el-table-column type="index" label="序列" width="100"> <el-table-column type="index" label="序列" width="100"></el-table-column>
</el-table-column> <el-table-column prop="fieldName" label="Field名"></el-table-column>
<el-table-column prop="fieldName" label="Field名"> <el-table-column prop="fieldDesc" label="中文名"></el-table-column>
</el-table-column> <el-table-column prop="fieldJson" label="FieldJson"></el-table-column>
<el-table-column prop="fieldDesc" label="中文名"> <el-table-column prop="fieldType" label="Field数据类型" width="130"></el-table-column>
</el-table-column> <el-table-column prop="dbFieldType" label="数据库字段类型" width="130"></el-table-column>
<el-table-column prop="fieldJson" label="FieldJson"> <el-table-column prop="columnName" label="数据库字段" width="130"></el-table-column>
</el-table-column> <el-table-column prop="comment" label="数据库字段描述" width="130"></el-table-column>
<el-table-column prop="fieldType" label="Field数据类型" width="130"> <el-table-column prop="fieldSearchType" label="搜索条件" width="130"></el-table-column>
</el-table-column>
<el-table-column prop="columnName" label="数据库字段" width="130">
</el-table-column>
<el-table-column prop="comment" label="数据库字段描述" width="130">
</el-table-column>
<el-table-column prop="fieldSearchType" label="搜索条件" width="130">
</el-table-column>
<el-table-column label="操作" width="300"> <el-table-column label="操作" width="300">
<template slot-scope="scope"> <template slot-scope="scope">
<el-button size="mini" type="primary" icon="el-icon-edit" @click="editAndAddField(scope.row)">编辑</el-button> <el-button
<el-button size="mini" type="text" :disabled="scope.$index == 0" @click="moveUpField(scope.$index)">上移</el-button> size="mini"
<el-button size="mini" type="text" :disabled="(scope.$index + 1) == form.fields.length" @click="moveDownField(scope.$index)">下移</el-button> type="primary"
icon="el-icon-edit"
@click="editAndAddField(scope.row)"
>编辑</el-button>
<el-button
size="mini"
type="text"
:disabled="scope.$index == 0"
@click="moveUpField(scope.$index)"
>上移</el-button>
<el-button
size="mini"
type="text"
:disabled="(scope.$index + 1) == form.fields.length"
@click="moveDownField(scope.$index)"
>下移</el-button>
<el-popover placement="top" v-model="scope.row.visible"> <el-popover placement="top" v-model="scope.row.visible">
<p>确定删除吗?</p> <p>确定删除吗?</p>
<div style="text-align: right; margin: 0"> <div style="text-align: right; margin: 0">
...@@ -71,146 +115,200 @@ ...@@ -71,146 +115,200 @@
</template> </template>
<script> <script>
const fieldTemplate = { const fieldTemplate = {
fieldName: '', fieldName: "",
fieldDesc: '', fieldDesc: "",
fieldType: '', fieldType: "",
fieldJson: '', dbFieldType: "",
columnName: '', fieldJson: "",
comment:'', columnName: "",
fieldSearchType:'' comment: "",
} fieldSearchType: ""
};
import FieldDialog from "@/view/systemTools/autoCode/component/fieldDialog.vue";
import { toUpperCase } from "@/utils/stringFun.js";
import { createTemp, getDB, getTable,getColume } from "@/api/autoCode.js";
import {getDict} from '@/utils/dictionary'
import FieldDialog from '@/view/systemTools/autoCode/component/fieldDialog.vue'
import { toUpperCase } from '@/utils/stringFun.js'
import { createTemp } from '@/api/autoCode.js'
export default { export default {
name: 'autoCode', name: "autoCode",
data() { data() {
return { return {
addFlag: '', dbform: {
dbName: "",
tableName: ""
},
dbOptions: [],
tableOptions: [],
addFlag: "",
fdMap: {},
form: { form: {
structName: '', structName: "",
packageName: '', packageName: "",
abbreviation: '', abbreviation: "",
description:'', description: "",
autoCreateApiToSql: false, autoCreateApiToSql: false,
fields: [], fields: []
}, },
rules: { rules: {
structName: [{ required: true, message: '请输入结构体名称', trigger: 'blur' }], structName: [
abbreviation: [{ required: true, message: '请输入结构体简称', trigger: 'blur' }], { required: true, message: "请输入结构体名称", trigger: "blur" }
description: [{ required: true, message: '请输入结构体描述', trigger: 'blur' }], ],
packageName: [{ required: true, message: '文件名称:sys_xxxx_xxxx', trigger: 'blur' }], abbreviation: [
{ required: true, message: "请输入结构体简称", trigger: "blur" }
],
description: [
{ required: true, message: "请输入结构体描述", trigger: "blur" }
],
packageName: [
{
required: true,
message: "文件名称:sys_xxxx_xxxx",
trigger: "blur"
}
]
}, },
dialogMiddle: {}, dialogMiddle: {},
bk: {}, bk: {},
dialogFlag: false, dialogFlag: false
} };
}, },
components: { components: {
FieldDialog, FieldDialog
}, },
methods: { methods: {
editAndAddField(item) { editAndAddField(item) {
this.dialogFlag = true this.dialogFlag = true;
if (item) { if (item) {
this.addFlag = 'edit' this.addFlag = "edit";
this.bk = JSON.parse(JSON.stringify(item)) this.bk = JSON.parse(JSON.stringify(item));
this.dialogMiddle = item this.dialogMiddle = item;
} else { } else {
this.addFlag = 'add' this.addFlag = "add";
this.dialogMiddle = JSON.parse(JSON.stringify(fieldTemplate)) this.dialogMiddle = JSON.parse(JSON.stringify(fieldTemplate));
} }
}, },
moveUpField(index) { moveUpField(index) {
if (index == 0) { if (index == 0) {
return return;
} }
const oldUpField = this.form.fields[index - 1] const oldUpField = this.form.fields[index - 1];
this.form.fields.splice(index - 1, 1) this.form.fields.splice(index - 1, 1);
this.form.fields.splice(index, 0, oldUpField) this.form.fields.splice(index, 0, oldUpField);
}, },
moveDownField(index) { moveDownField(index) {
const fCount = this.form.fields.length const fCount = this.form.fields.length;
if (index == fCount - 1) { if (index == fCount - 1) {
return return;
} }
const oldDownField = this.form.fields[index + 1] const oldDownField = this.form.fields[index + 1];
this.form.fields.splice(index + 1, 1) this.form.fields.splice(index + 1, 1);
this.form.fields.splice(index, 0, oldDownField) this.form.fields.splice(index, 0, oldDownField);
}, },
enterDialog() { enterDialog() {
this.$refs.fieldDialog.$refs.fieldDialogFrom.validate((valid) => { this.$refs.fieldDialog.$refs.fieldDialogFrom.validate(valid => {
if (valid) { if (valid) {
this.dialogMiddle.fieldName = toUpperCase(this.dialogMiddle.fieldName) this.dialogMiddle.fieldName = toUpperCase(
if (this.addFlag == 'add') { this.dialogMiddle.fieldName
this.form.fields.push(this.dialogMiddle) );
if (this.addFlag == "add") {
this.form.fields.push(this.dialogMiddle);
} }
this.dialogFlag = false this.dialogFlag = false;
} else { } else {
return false return false;
} }
}) });
}, },
closeDialog() { closeDialog() {
if (this.addFlag == 'edit') { if (this.addFlag == "edit") {
this.dialogMiddle = this.bk this.dialogMiddle = this.bk;
} }
this.dialogFlag = false this.dialogFlag = false;
}, },
deleteField(index) { deleteField(index) {
this.form.fields.splice(index, 1) this.form.fields.splice(index, 1);
}, },
async enterForm() { async enterForm() {
if (this.form.fields.length <= 0) { if (this.form.fields.length <= 0) {
this.$message({ this.$message({
type: 'error', type: "error",
message: '请填写至少一个field', message: "请填写至少一个field"
}) });
return false return false;
} }
if(this.form.fields.some(item=>item.fieldName == this.form.structName)){ if (
this.form.fields.some(item => item.fieldName == this.form.structName)
) {
this.$message({ this.$message({
type: 'error', type: "error",
message: '存在与结构体同名的字段', message: "存在与结构体同名的字段"
}) });
return false return false;
} }
this.$refs.autoCodeForm.validate(async (valid) => { this.$refs.autoCodeForm.validate(async valid => {
if (valid) { if (valid) {
this.form.structName = toUpperCase(this.form.structName) this.form.structName = toUpperCase(this.form.structName);
if (this.form.structName == this.form.abbreviation) { if (this.form.structName == this.form.abbreviation) {
this.$message({ this.$message({
type: 'error', type: "error",
message: 'structName和struct简称不能相同', message: "structName和struct简称不能相同"
}) });
return false return false;
} }
const data = await createTemp(this.form) const data = await createTemp(this.form);
const blob = new Blob([data]) const blob = new Blob([data]);
const fileName = 'ginvueadmin.zip' const fileName = "ginvueadmin.zip";
if ('download' in document.createElement('a')) { if ("download" in document.createElement("a")) {
// 不是IE浏览器 // 不是IE浏览器
let url = window.URL.createObjectURL(blob) let url = window.URL.createObjectURL(blob);
let link = document.createElement('a') let link = document.createElement("a");
link.style.display = 'none' link.style.display = "none";
link.href = url link.href = url;
link.setAttribute('download', fileName) link.setAttribute("download", fileName);
document.body.appendChild(link) document.body.appendChild(link);
link.click() link.click();
document.body.removeChild(link) // 下载完成移除元素 document.body.removeChild(link); // 下载完成移除元素
window.URL.revokeObjectURL(url) // 释放掉blob对象 window.URL.revokeObjectURL(url); // 释放掉blob对象
} else { } else {
// IE 10+ // IE 10+
window.navigator.msSaveBlob(blob, fileName) window.navigator.msSaveBlob(blob, fileName);
} }
} else { } else {
return false return false;
} }
}) });
},
async getDb() {
const res = await getDB();
if (res.code == 0) {
this.dbOptions = res.data.dbs;
}
}, },
async getTable() {
const res = await getTable({ dbName: this.dbform.dbName });
if (res.code == 0) {
this.tableOptions = res.data.tables;
}
},
async getColume() {
await getColume(this.dbform)
},
async setFdMap() {
const fdTpyes = ["string", "int", "bool", "float64", "time.Time"];
fdTpyes.map(async fdtype=>{
const res = await getDict(fdtype)
res.map(item=>{
this.fdMap[item.label] = fdtype
})
})
}
}, },
} created() {
this.getDb();
this.setFdMap()
}
};
</script> </script>
<style scope lang="scss"> <style scope lang="scss">
.button-box { .button-box {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册