1 Star 1 Fork 1

xiaoyutab / xgotool

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
init_server.go 3.12 KB
一键复制 编辑 原始数据 按行查看 历史
xiaoyutab 提交于 2024-02-01 13:14 . 添加数据字典生成脚本
package xconsole
import (
"errors"
"strings"
"gitee.com/xiaoyutab/xgotool/xnum"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
// 表注释
type Table struct {
Name string `gorm:"column:Name"` // 表名
Comment string `gorm:"column:Comment"` // 表注释
Fields []Field `gorm:"-"` // 表字段
}
// 表字段
type Field struct {
Field string `gorm:"column:Field"`
Type string `gorm:"column:Type"`
Null string `gorm:"column:Null"`
Key string `gorm:"column:Key"`
Default string `gorm:"column:Default"`
Extra string `gorm:"column:Extra"`
Privileges string `gorm:"column:Privileges"`
Comment string `gorm:"column:Comment"`
}
type gorm_config struct {
DNS string // 数据库DNS连接字符串
DBS string // 生成框架中的数据库连接
DB *gorm.DB // 数据库连接
DBName string // 数据库名称
Table string // 查询的表名称
TableInfo *Table // 数据表注释信息
Error error // 错误存储
Field []Field // 表字段列表
DeletedField string // 删除的字段标识【空-物理删除 时间类型-时间删除 数值类型-1删除,不允许为字符串类型】
DeletedWhere string // 删除字段的类型,允许值为:int、datetime、date、time
}
func gorm_error(err error) *gorm_config {
return &gorm_config{
Error: err,
}
}
// 连接数据库操作
//
// dns 数据库连接
func connect(dns string) *gorm_config {
if len(strings.Split(dns, "/")) != 2 {
return gorm_error(errors.New("DNS结构错误"))
}
databases := strings.Split(strings.Split(dns, "/")[1], "?")[0]
// 连接数据库
db, err := gorm.Open(mysql.Open(dns))
if err != nil {
return gorm_error(err)
}
return &gorm_config{
DBName: databases,
DB: db,
}
}
// 设置表名称
//
// name 数据表名称
func (c *gorm_config) setTable(name string) *gorm_config {
if c.Error != nil {
return c
}
// 获取表结构信息
var tables Table
err := c.DB.Raw("SELECT TABLE_NAME AS `Name`,TABLE_COMMENT AS `Comment` FROM information_schema.TABLES WHERE table_schema='" +
c.DBName + "' AND TABLE_NAME = '" +
name + "';").Find(&tables).Error
if err != nil {
c.Error = err
return c
}
c.Table = name
c.TableInfo = &tables
// 获取字段结构信息
fields := []Field{}
err = c.DB.Raw("SHOW FULL COLUMNS FROM " + c.Table + ";").Find(&fields).Error
if err != nil {
c.Error = err
return c
}
c.Field = fields
return c
}
// 设置DBS连接字符串
//
// name 连接字符串
func (c *gorm_config) setDBS(name string) *gorm_config {
c.DBS = name
return c
}
// 设置删除的字段类型
//
// name 删除的字段标识
func (c *gorm_config) setDeletedField(name string) *gorm_config {
c.DeletedField = name
for i := 0; i < len(c.Field); i++ {
if c.Field[i].Field == name {
if xnum.InArray(c.Field[i].Type, []string{"datetime", "timestamp"}) {
// 时间格式
c.DeletedWhere = "datetime"
} else if c.Field[i].Type == "date" {
c.DeletedWhere = "date"
} else if c.Field[i].Type == "time" {
c.DeletedWhere = "time"
} else {
c.DeletedField = "int"
}
}
}
return c
}
Go
1
https://gitee.com/xiaoyutab/xgotool.git
git@gitee.com:xiaoyutab/xgotool.git
xiaoyutab
xgotool
xgotool
v0.3.13

搜索帮助