database/sql2go/define.go
2024-08-09 17:17:20 +08:00

116 lines
3.2 KiB
Go

// Package sql2go...
//
// Description : sql2go...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2021-10-25 4:50 下午
package sql2go
// sqlTypeMap mysql数据类型 => go 数据类型映射
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 4:50 下午 2021/10/25
var sqlTypeMap = map[string]string{
"int": "int",
"integer": "int",
"tinyint": "int8",
"smallint": "int16",
"mediumint": "int32",
"bigint": "int64",
"int unsigned": "uint",
"integer unsigned": "uint",
"tinyint unsigned": "uint8",
"smallint unsigned": "uint16",
"mediumint unsigned": "uint32",
"bigint unsigned": "uint64",
"bit": "byte",
"bool": "bool",
"enum": "string",
"set": "string",
"varchar": "string",
"char": "string",
"tinytext": "string",
"mediumtext": "string",
"text": "string",
"longtext": "string",
"blob": "string",
"tinyblob": "string",
"mediumblob": "string",
"longblob": "string",
"date": "time.Time",
"datetime": "time.Time",
"timestamp": "time.Time",
"time": "time.Time",
"float": "float64",
"double": "float64",
"decimal": "float64",
"binary": "string",
"varbinary": "string",
}
const (
// DaoTpl 模版
DaoTpl = `// Package {PACKAGE} ...
//
// Description : {PACKAGE} ...
package {PACKAGE}
import (
"gorm.io/gorm"
"errors"
)
// {DATA_STRUCT_NAME} 数据库表的数据结构
{DATA_STRUCT}
// New{DATA_STRUCT_DAO} 获取DAO实例
func New{DATA_STRUCT_DAO}() *{DATA_STRUCT_DAO} {
return &{DATA_STRUCT_DAO}{
table : "{DB_TABLE_NAME}",
}
}
// {DATA_STRUCT_DAO} sql2go tool generate
type {DATA_STRUCT_DAO} struct {
table string
}
// GetDetailBy{PRIMARY_KEY} 根据主键ID获取详情
func ({DAO_RECEIVER} *{DATA_STRUCT_DAO}) GetDetailBy{PRIMARY_KEY}(dbInstance *gorm.DB, {PRIMARY_KEY} {PRIMARY_KEY_TYPE}) (*{DATA_STRUCT_NAME}, error) {
var (
err error
detail {DATA_STRUCT_NAME}
)
if err = dbInstance.Table({DAO_RECEIVER}.table).Where("{PRIMARY_KEY_FIELD} = ?", {PRIMARY_KEY}).Limit(1).First(&detail).Error; nil != err {
return nil, err
}
return &detail, nil
}
// GetList 获取数据列表
func ({DAO_RECEIVER} *{DATA_STRUCT_DAO}) GetList(dbInstance *gorm.DB, condition map[string]any, limit int, offset int) ([]{DATA_STRUCT_NAME}, error) {
if nil == condition {
condition = make(map[string]any)
}
var (
err error
list []{DATA_STRUCT_NAME}
)
if err = dbInstance.Table({DAO_RECEIVER}.table).Where(condition).Limit(limit).Offset(offset).Find(&list).Error; nil != err {
return make([]{DATA_STRUCT_NAME}, 0), err
}
return list, nil
}
// Create 创建数据
func ({DAO_RECEIVER} *{DATA_STRUCT_DAO}) Create(dbInstance *gorm.DB, data *{DATA_STRUCT_NAME}) error {
if nil == data {
return errors.New("data is nil")
}
return dbInstance.Table({DAO_RECEIVER}.table).Create(data).Error
}
`
)