1 Star 0 Fork 0

CaptialSTeam/ubdframe

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
dataexec_mysql.go 6.62 KB
一键复制 编辑 原始数据 按行查看 历史
Souki 提交于 2025-12-08 17:01 +08:00 . !7modify support
package dataexec
import (
"fmt"
"gitee.com/captials-team/ubdframe/src/domain/configstc"
"gitee.com/captials-team/ubdframe/src/infrastructure/clients/mysql"
"gitee.com/captials-team/ubdframe/src/pkg/atapi/config"
"gitee.com/captials-team/ubdframe/src/pkg/atapi/ifs"
"gorm.io/gorm"
"strings"
"time"
)
type MysqlDbExec struct {
db *gorm.DB
name string
tbName string
}
func (exec *MysqlDbExec) DoSearch(conditions map[string]interface{}, fields []string, page, size int) ([]map[string]interface{}, int64, error) {
//fmt.Printf("search params: %+v ,%+v ,%d ,%d\n", params, fields, page, size)
//fields = append(fields, "id", "created_at", "updated_at")
if conditions == nil {
conditions = map[string]interface{}{}
}
fields = append(fields, "id")
where := []string{
"deleted_uid=0",
}
whereArgs := []interface{}{}
for k := range conditions {
v := conditions[k]
where = append(where, k)
whereArgs = append(whereArgs, v)
}
orderBy := []string{
"id desc",
}
var list []map[string]interface{}
newScan := func() ([]interface{}, []interface{}) {
arr := make([]interface{}, len(fields))
arr1 := make([]interface{}, len(fields))
for i := range fields {
arr1[i] = &arr[i]
}
return arr, arr1
}
toRetRow := func(arr []interface{}) map[string]interface{} {
m := map[string]interface{}{}
for i := range arr {
v := arr[i]
var value interface{}
switch v.(type) {
case string:
value = v.(string)
case []byte:
value = string(v.([]byte))
case int64:
value = v.(int64)
default:
value = v
}
m[fields[i]] = value
}
return m
}
whereStr := ""
if len(where) > 0 {
whereStr = "WHERE " + strings.Join(where, " AND ")
}
var total int64
countSql := fmt.Sprintf("SELECT COUNT(*) FROM %s %s LIMIT 1", exec.tbName, whereStr)
ret := exec.db.Raw(countSql, whereArgs...).Scan(&total)
if ret.Error != nil {
return nil, 0, ret.Error
}
if len(fields) <= 0 {
fields = append(fields, "*")
}
orderByStr := strings.Join(orderBy, ",")
if orderByStr != "" {
orderByStr = "ORDER BY " + orderByStr
}
whereArgs = append(whereArgs, size)
whereArgs = append(whereArgs, size*(page-1))
dataSql := fmt.Sprintf("SELECT %s FROM %s %s %s LIMIT ? OFFSET ?", strings.Join(fields, ","), exec.tbName, whereStr, orderByStr)
rows, err := exec.db.Raw(dataSql, whereArgs...).Rows()
if err != nil {
return nil, 0, err
}
for rows.Next() {
arr, scans := newScan()
err := rows.Scan(scans...)
if err != nil {
return list, 0, err
}
list = append(list, toRetRow(arr))
}
return list, total, err
}
func (exec *MysqlDbExec) DoQuery(conditions map[string]interface{}, fields []string) (map[string]interface{}, error) {
//fmt.Printf("query params: %s, %+v, %+v\n", exec.tbName, conditions, fields)
fields = append(fields, "id")
where := []string{
"deleted_uid=0",
}
whereArgs := []interface{}{}
for k, v := range conditions {
where = append(where, fmt.Sprintf("%s=?", k))
whereArgs = append(whereArgs, v)
}
var fieldArr = []string{}
var scanArr = []interface{}{}
m := map[string]interface{}{}
arr := make([]interface{}, len(fields))
for i, v := range fields {
m[v] = &arr[i]
fieldArr = append(fieldArr, fmt.Sprintf("`%s`", v))
scanArr = append(scanArr, &arr[i])
}
whereStr := ""
orderByStr := ""
if len(where) > 0 {
whereStr = "WHERE " + strings.Join(where, " AND ")
}
fieldStr := strings.Join(fieldArr, ",")
selectSql := fmt.Sprintf("SELECT %s FROM %s %s %s LIMIT 1",
fieldStr, exec.tbName, whereStr, orderByStr)
ret := exec.db.Raw(selectSql, whereArgs...).Scan(&m)
if ret.Error != nil {
return nil, ret.Error
}
return m, nil
}
func (exec *MysqlDbExec) DoCreate(params map[string]interface{}) (int64, error) {
var values = map[string]interface{}{}
for k, v := range params {
values[k] = v
}
ret := exec.db.Table(exec.tbName).Create(values)
if ret.Error != nil {
return 0, ret.Error
}
//logs.Out.Info("Values= %+v", values["@id"])
//主键id值
id, exist := values["@id"]
if exist {
return id.(int64), nil
}
return ret.RowsAffected, nil
}
func (exec *MysqlDbExec) DoUpdate(id int64, params map[string]interface{}) (int64, error) {
//fmt.Printf("update params: %d, %+v\n", id, params)
where := []string{
"id=?",
"deleted_uid=0",
}
whereArgs := []interface{}{
id,
}
params["updated_at"] = time.Now().UnixMilli()
var fieldArr = []string{}
var valueArr = []interface{}{}
for k, v := range params {
fieldArr = append(fieldArr, fmt.Sprintf("`%s`=?", k))
valueArr = append(valueArr, v)
}
fieldStr := strings.Join(fieldArr, ",")
whereStr := ""
if len(where) > 0 {
whereStr = "WHERE " + strings.Join(where, " AND ")
}
if len(whereArgs) > 0 {
for _, v := range whereArgs {
valueArr = append(valueArr, v)
}
}
updateSql := fmt.Sprintf("UPDATE %s SET %s %s", exec.tbName, fieldStr, whereStr)
ret := exec.db.Exec(updateSql, valueArr...)
if ret.Error != nil {
return 0, ret.Error
}
return ret.RowsAffected, nil
}
func (exec *MysqlDbExec) DoDelete(id int64) (int64, error) {
return exec.DoUpdate(id, map[string]interface{}{
"deleted_uid": 1,
"deleted_at": time.Now().UnixMilli(),
})
}
func (exec *MysqlDbExec) Copy() ifs.IAutoApiDataExec {
return &MysqlDbExec{
db: exec.db,
}
}
func (exec *MysqlDbExec) InitDB(name string, c config.AutoApiDataDefined) error {
return exec.initV1(name, c)
}
func (exec *MysqlDbExec) initV1(name string, config config.AutoApiDataDefined) error {
exec.name = name
exec.tbName = exec.genTableName(config)
//log.Printf("data init: %s, %+v",exec.name,exec.tbName)
//自动初始化表
if config.AutoTable {
ret := exec.db.Exec(exec.tableSql(config))
return ret.Error
}
return nil
}
func (exec *MysqlDbExec) TableName() string {
return exec.tbName
}
func (exec *MysqlDbExec) genTableName(config config.AutoApiDataDefined) string {
name := config.DataName
if name == "" {
name = exec.name
}
return "atapi_" + name
}
func (exec *MysqlDbExec) tableSql(config config.AutoApiDataDefined) string {
tableName := exec.tbName
tableComment := ""
fields := []string{}
for _, f := range config.Fields {
fields = append(fields,
f.CreateSql(),
)
}
sql := `
CREATE TABLE IF NOT EXISTS %s
(
id int unsigned auto_increment,
created_at datetime default current_timestamp null comment 'create time',
updated_at datetime default null comment 'update time',
deleted_at datetime default null comment 'delete time',
deleted_uid int unsigned default 0,
%s,
PRIMARY KEY (id)
)
COMMENT '%s';
`
return fmt.Sprintf(sql, tableName,
strings.Join(fields, ",\n"),
tableComment)
}
func NewMysqlDbExec(c configstc.DBConfig) (*MysqlDbExec, error) {
db := mysql.NewGormDB(c)
return &MysqlDbExec{
db: db,
}, nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/captials-team/ubdframe.git
git@gitee.com:captials-team/ubdframe.git
captials-team
ubdframe
ubdframe
v1.0.4

搜索帮助