代码拉取完成,页面将自动刷新
package app
import (
"fmt"
"net/http"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"time"
"gitee.com/tomatomeatman/golang-repository/bricks/model/dbinfo"
"gitee.com/tomatomeatman/golang-repository/bricks/model/msgentity"
"gitee.com/tomatomeatman/golang-repository/bricks/utils/function/data/integerutil"
"gitee.com/tomatomeatman/golang-repository/bricks/utils/function/data/jsonutil"
"gitee.com/tomatomeatman/golang-repository/bricks/utils/function/data/maputil"
"gitee.com/tomatomeatman/golang-repository/bricks/utils/function/data/stringutil"
"gitee.com/tomatomeatman/golang-repository/bricks/utils/function/data/u64util"
"gitee.com/tomatomeatman/golang-repository/bricks/utils/function/data/uuidutil"
"gitee.com/tomatomeatman/golang-repository/bricks/utils/function/reflectutil"
"gitee.com/tomatomeatman/golang-repository/bricks/utils/ginutil"
"gitee.com/tomatomeatman/golang-repository/bricks/utils/gorm"
Log "github.com/cihub/seelog"
uuid "github.com/satori/go.uuid"
)
var (
recordKeyJam = "" //创建sRecordKey用的干扰串
upFilePath = "" //上传文件路径
)
// we业务层接口定义,用于规范控制层结构体
type Service interface {
/**
* 取对应模块数据层实体,若子类未设置则返回DaoBaseFunc
*/
GetModuleDao() (Dao, error) //对应模块数据层实体
/**
* 验证新增数据是否存在重复 (一旦使用则覆盖通用方法)
* @param ctx gin请求对象
* @param entity 验证数据
* @return *MsgEntity 返回验证结果
*/
CheckRepeatByAdd(ctx ginutil.Context, entity dbinfo.Entity) *msgentity.MsgEntity
/**
* 验证更新数据是否存在重复 (一旦使用则覆盖通用方法)
* @param ctx gin请求对象
* @param entity 待验证数据
* @return *MsgEntity 返回验证结果
*/
CheckRepeatByEdit(ctx ginutil.Context, entity dbinfo.Entity) *msgentity.MsgEntity
/**
* 新增
* entity 检查用数据结构
* data 数据
*/
Add(ctx ginutil.Context, entity dbinfo.Entity, data map[string]interface{}) *msgentity.MsgEntity
/**
* 新增普通数据
* entity 检查用数据结构
* data 数据
*/
AddCommon(ctx ginutil.Context, entity dbinfo.Entity, data map[string]interface{}) *msgentity.MsgEntity
/**
* 新增树节点
* entity 检查用数据结构
* data 数据
*/
AddNode(ctx ginutil.Context, entity dbinfo.Entity, data map[string]interface{}) *msgentity.MsgEntity
// 批量新增
Adds(ctx ginutil.Context, entitys []dbinfo.Entity, list []map[string]interface{}) *msgentity.MsgEntity
// 批量新增
AddList(ctx ginutil.Context, entitys []dbinfo.Entity) *msgentity.MsgEntity
/**
* 修改状态
* @param entity 实体类
* @param id 编号
* @param iState 状态值
* @param iVersion 记录版本号
* @param sMemo 备注
* @param unidirectional 是否单向 设置为单向则新值必须大于旧值才能执行
* @return msgentity.MsgEntity 返回执行情况
*/
ChangeState(ctx ginutil.Context, entity dbinfo.Entity, id interface{}, iState int, iVersion int, sMemo string, unidirectional bool) *msgentity.MsgEntity
/**
* 修改步骤值(如果设置为单向则新值必须大于旧值)
* @param id 编号
* @param iSetp 步骤值
* @param iVersion 记录版本号
* @param sMemo 备注
* @param unidirectional 是否单向 设置为单向则新值必须大于旧值才能执行
* @param entity 实体类
* @return msgentity.MsgEntity 返回执行情况
*/
ChangeSetp(ctx ginutil.Context, entity dbinfo.Entity, id interface{}, iSetp int, iVersion int, sMemo string, unidirectional bool) *msgentity.MsgEntity
/**
* 删除
* @param entity 对象类型
* @param id 记录编号值
* @param iVersion 记录版本号
* @return msgentity.MsgEntity
*/
Del(ctx ginutil.Context, entity dbinfo.Entity, id interface{}, iVersion int) *msgentity.MsgEntity
/**
* 删除
* @param entity 对象类型
* @param where 执行条件
* @return msgentity.MsgEntity
*/
DelByMap(ctx ginutil.Context, entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo) *msgentity.MsgEntity
/**
* 按实体保留map中的数据
* entity 参考的结构体
* data 数据
*/
HoldByEntity(entity dbinfo.Entity, data map[string]interface{}) map[string]interface{}
/**
* 修改
* @param entity 对象类型
* @param id 记录编号值
* @param iVersion 记录版本号
* @param data 待更新的字段和值
* @return msgentity.MsgEntity
*/
Edit(ctx ginutil.Context, entity dbinfo.Entity, id interface{}, iVersion int, data map[string]interface{}) *msgentity.MsgEntity
/**
* 批量修改
* @param entity 对象类型
* @param datas 待更新的字段和值集合
* @return msgentity.MsgEntity
*/
Edits(ctx ginutil.Context, entity dbinfo.Entity, datas []map[string]interface{}) *msgentity.MsgEntity
/**
* 根据主键查询数据
* id 主键
* entity 检查用数据结构
*/
FindById(ctx ginutil.Context, entity dbinfo.Entity, id interface{}) *msgentity.MsgEntity
// 查询所有数据
FindAll(ctx ginutil.Context, entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo) *msgentity.MsgEntity
// 查询指定时间内数据
FindByDate(ctx ginutil.Context, entity dbinfo.Entity, sDateSt string, sDateEd string) *msgentity.MsgEntity
// 查询指定行数据
FindByRow(ctx ginutil.Context, entity dbinfo.Entity, id interface{}) *msgentity.MsgEntity
// 查询分页数据
FindByPage(ctx ginutil.Context, entity dbinfo.Entity, findByPageParam dbinfo.FindByPageParam) *msgentity.MsgEntity
/**
* 补充数据库实体类的数据--新增
* @param entity
* @param selfId 自提供的编号,防止从序列中获取
* @param idValuePrefix Id前缀
* @return
*/
SupplyDbEntityAttrByAdd(ctx ginutil.Context, entity dbinfo.Entity, selfId string, idValuePrefix string) *msgentity.MsgEntity
/**
* 补充数据库实体类的数据--修改
* @param ctx
* @param data 待修改的数据
* @param entity 参照结构体
* @return
*/
SupplyDbEntityAttrByEdit(ctx ginutil.Context, data map[string]interface{}, entity dbinfo.Entity) *msgentity.MsgEntity
/**
* 验证新增数据是否存在重复
*
*/
ValidEntityRepeatByAdd(ctx ginutil.Context, entity dbinfo.Entity) *msgentity.MsgEntity
/**
* 验证更新数据是否存在重复
*
*/
ValidEntityRepeatByEdit(ctx ginutil.Context, entity dbinfo.Entity, id interface{}, data map[string]interface{}) *msgentity.MsgEntity
/**
* 通用树型结构表添加数据时重复检查方法
* entity
*/
CommonCheckRepeatByAddAndTree(ctx ginutil.Context, entity dbinfo.Entity) *msgentity.MsgEntity
/**
* 通用树型结构表添加数据时重复检查方法
* entity
*/
CommonCheckRepeatByEditAndTree(ctx ginutil.Context, entity dbinfo.Entity, id interface{}, sName interface{}) *msgentity.MsgEntity
/**
* 通用添加数据时重复检查方法
* entity
*/
CommonCheckRepeatByAdd(ctx ginutil.Context, entity dbinfo.Entity) *msgentity.MsgEntity
/**
* 通用更新数据时重复检查方法
* entity
*/
CommonCheckRepeatByEdit(ctx ginutil.Context, entity dbinfo.Entity, id interface{}, data map[string]interface{}) *msgentity.MsgEntity
/**
* 读取树形结构数据
* @param entity
* @param sGroupColumn
* @param sGroupName
* @return
*/
FindByTree(ctx ginutil.Context, entity dbinfo.Entity, sGroupColumn, sGroupName string) *msgentity.MsgEntity
/**
* List转树形结构
* @param source Map或切片结构
* @param rootName
* @param idFieldName
* @param pIdFieldName
* @param childFieldName
* @return
*/
CreateTree(source interface{}, rootName, idFieldName, pIdFieldName, childFieldName string) *msgentity.MsgEntity
/**
* List转树形结构
* @param source 切片结构
* @param rootName
* @param idFieldName
* @param pIdFieldName
* @param childFieldName
* @return
*/
createTreeByList(source []interface{},
rootName, idFieldName, pIdFieldName, childFieldName string) *msgentity.MsgEntity
/**
* List转树形结构
* @param source Map结构
* @param rootName
* @param idFieldName
* @param pIdFieldName
* @param childFieldName
* @return
*/
createTreeByMap(source []map[string]interface{},
rootName, idFieldName, pIdFieldName, childFieldName string) *msgentity.MsgEntity
/**
* 根据字段名取指定记录编号的数据库表中对应字段的值
* @param entity 实体类
* @param id
* @param fieldNames 待取数据的字段名称集合
* @return msgentity.MsgEntity 返回内容data中存放的是Map
*/
GetValueByFieldName(ctx ginutil.Context, entity dbinfo.Entity, id interface{}, fieldNames []string) *msgentity.MsgEntity
/**
* 根据字段名取指定记录编号的数据库表中对应字段的值
* @param entity 实体类
* @param id
* @param fieldName 待取数据的字段名称集合
* @return msgentity.MsgEntity 返回内容data中存放的是Map
*/
GetValueByField(ctx ginutil.Context, entity dbinfo.Entity, id interface{}, fieldName string) *msgentity.MsgEntity
/**
* 根据字段名取指定条件的数据库表中对应字段的值
* @param entity 实体类
* @param whereInfo 条件
* @param fieldName 待取数据的字段名称集合
* @param currentUser 当前用户
* @return msgentity.MsgEntity 返回内容data中存放的是Map
*/
GetValueByWhere(ctx ginutil.Context, entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, fieldName string) *msgentity.MsgEntity
/**
* 取记录对应的版本号
* @param entity 实体类
* @param idName 编号
* @return
*/
GetiVersion(ctx ginutil.Context, entity dbinfo.Entity, id interface{}) *msgentity.MsgEntity
/**
* 取记录对应的状态值
* @param entity 实体类
* @param idName 编号
* @return
*/
GetiState(ctx ginutil.Context, entity dbinfo.Entity, id interface{}) *msgentity.MsgEntity
/**
* 根据关键值取对象集合
* @Param entity 实体类
* @Param where 存放查询条件
* @return msgentity.MsgEntity
*/
FindByKey(ctx ginutil.Context, entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo) *msgentity.MsgEntity
/**
* 根据关键值取对象集合中的第一个
* @Param entity 实体类
* @Param where 存放查询条件
* @param fields 指定要查询的字段集合
* @return msgentity.MsgEntity
*/
FindOneByKey(ctx ginutil.Context, entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, fields ...string) *msgentity.MsgEntity
/**
* 根据关键值取对象集合中的符合条件的第一条记录的指定字段
* @Param entity 实体类
* @Param where 存放查询条件
* @param fieldName 指定要查询的字段
* @return msgentity.MsgEntity
*/
FindValueByKey(ctx ginutil.Context, entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, fieldName string) *msgentity.MsgEntity
/**
* 根据指定字段进行分组查询
* @Param entity 实体类
* @Param where 存放查询条件
* @param fieldMap 指定要查询的字段集合(原字段, 别名)
* @return msgentity.MsgEntity
*/
FindByFields(ctx ginutil.Context, entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, fieldMap map[string]string) *msgentity.MsgEntity
/**
* 根据关键值查数量
* @Param entity 实体类
* @Param where 存放查询条件
* @return msgentity.MsgEntity
*/
FindCountByKey(ctx ginutil.Context, entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo) *msgentity.MsgEntity
/**
* 根据字段名取分组数据
* @param entity 实体类
* @param sCreator 指定用户
* @param fields 字段名与别名对象
* @return
*/
GroupByField(ctx ginutil.Context, entity dbinfo.Entity, sCreator string, fields map[string]string) *msgentity.MsgEntity
/**
* 根据字段名取分组数据及分组后数量
* @param entity 实体类
* @param sCreator 指定用户
* @param fields 字段名与别名对象
* @return
*/
GroupByFieldAndCount(ctx ginutil.Context, entity dbinfo.Entity, sCreator string, fields map[string]string) *msgentity.MsgEntity
/**
* 取表中指定字段的最大值
* @param entity 实体类
* @param sCreator 指定用户
* @param field 字段名
* @param where 查询条件字符串
* @return msgentity.MsgEntity
*/
MaxByField(ctx ginutil.Context, entity dbinfo.Entity, sCreator string, field string, whereInfo []dbinfo.WhereInfo) *msgentity.MsgEntity
/**
* 取表中指定字段的最小值
* @param entity 实体类
* @param sCreator 指定用户
* @param field 字段名
* @param where 查询条件
* @return msgentity.MsgEntity
*/
MinByField(ctx ginutil.Context, entity dbinfo.Entity, sCreator string, field string, whereInfo []dbinfo.WhereInfo) *msgentity.MsgEntity
/**
* 检查关键值记录是否存在(返回1:存在;0:不存在)
* @param entity 实体类
* @Param id
* @return msgentity.MsgEntity
*/
HasById(ctx ginutil.Context, entity dbinfo.Entity, id interface{}) *msgentity.MsgEntity
/**
* 检查关键值记录是否存在(返回1:存在;0:不存在)
* @param entity 实体类
* @Param keyName 字段名
* @Param keyValue 字段值
* @return msgentity.MsgEntity
*/
HasByKey(ctx ginutil.Context, entity dbinfo.Entity, keyName string, keyValue interface{}) *msgentity.MsgEntity
/**
* 清理指定用户的缓存
* @param cacheName 缓存名
* @Param sUser 用户名
* @return msgentity.MsgEntity
*/
ClearCache(ctx ginutil.Context, cacheName string, sUser string) *msgentity.MsgEntity
/**
* 查询组结构数据
* @param ctx Http请求对象
* @param entity 实体类
* @param sGroupColumn 分组名(树节点)所在字段名
* @param sGroupName 分组名(树节点)
* @return
*/
FindByGroup(ctx ginutil.Context, entity dbinfo.Entity, sGroupColumn, sGroupName string) *msgentity.MsgEntity
/**
* 添加数据到指定组下
* 警告:对象必须符合树形结构要求,如:sId、sPid
* @param ctx Http请求对象
* @param sGroupName 分组字段名称(树节点)
* @param sGroupValue 分组字段值(树节点)
* @param entity 实体对象
* @return
*/
AddToGroup(ctx ginutil.Context, entity dbinfo.Entity, sGroupName, sGroupValue string) *msgentity.MsgEntity
/**
* 执行SQL脚本获取单行单列数据
* 注意:库名必须用${}进行包装,此脚本应只存在一条记录且为单列
* @param sql 待执行的SQL脚本
* @return msgentity.MsgEntity
*/
DoSql(sql string) *msgentity.MsgEntity
/**
* 执行SQL脚本获取单行单列数据
* 注意:库名必须用${}进行包装,此脚本应只存在一条记录且为单列
* @param sql 待执行的SQL脚本
* @return msgentity.MsgEntity
*/
ExecSql(sql string) *msgentity.MsgEntity
/**
* 执行SQL脚本获取单行单列数据
* 注意:库名必须用${}进行包装,此脚本应只存在一条记录且为单列
* @param sql 待执行的SQL脚本
* @return msgentity.MsgEntity
*/
GetValue(sql string) *msgentity.MsgEntity
/**
* 执行SQL脚本获取一行数据(多列)
* 注意:库名必须用${}进行包装,此脚本应只存在一条记录
* @param sql 待执行的SQL脚本
* @return msgentity.MsgEntity
*/
GetRow(sql string) *msgentity.MsgEntity
/**
* 执行SQL脚本获取多行数据(多列)
* 注意:库名必须用${}进行包装,此脚本可返回多条记录
* @param sql SQL脚本
* @return msgentity.MsgEntity
*/
GetRows(sql string) *msgentity.MsgEntity
/**
* 根据关键值翻转值(限布尔值类型,1转2,2转1)
* 警告:此方法只支持布尔值类型,且只支持翻转1和2
* @Param ctx http请求对象
* @Param entity 实体类
* @Param whereInfo 存放查询条件
* @Param reversalColumn 翻转的字段名
* @return msgentity.MsgEntity
*/
ReversalByKey(ctx ginutil.Context, entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, reversalColumn string) *msgentity.MsgEntity
/**
* 根据条件仅查询指定字段名数据
* @param entity 实体类
* @param whereInfo
* @param fieldNames 待取数据的字段名称集合
* @return msgentity.MsgEntity 返回内容data中存放的是Map
*/
FindField(ctx ginutil.Context, entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, fieldNames []string) *msgentity.MsgEntity
/**
* 上传文件
* @param ctx http请求对象
* @param modelName 模块名称
* @return msgentity.MsgEntity
*/
UpFile(ctx ginutil.Context, modelName string) *msgentity.MsgEntity
/**
* 获取图片
* @param ctx http请求对象
* @param modelName 模块名称
* @param filename 文件名
*/
LookImg(ctx ginutil.Context, modelName, filename string)
/**
* 设置父对象
* @param owner 父对象
*/
SetOwner(owner Service)
}
type CommonService = ServiceBaseFunc
// 基类
type ServiceBaseFunc struct {
owner Service //指定上级
}
// ---------------- 业务层默认接口实现 ----------------//
/**
* 设置父对象
* @param owner
*/
func (service *ServiceBaseFunc) SetOwner(owner Service) {
service.owner = owner
}
/**
* 取对应模块数据层实体
*/
func (service *ServiceBaseFunc) GetModuleDao() (Dao, error) {
moduleValue := reflect.ValueOf(service).Elem().FieldByName("ModuleDao")
if moduleValue.Kind() != reflect.Ptr || moduleValue.Type().Elem().Kind() != reflect.Struct {
return &DaoBaseFunc{}, nil //未设置模块数据层实体
}
// 获取 Entity 的反射值
daoElem := moduleValue.Elem()
dao := daoElem.Interface().(Dao)
return dao, nil
}
/**
* 验证新增数据是否存在重复 (一旦使用则覆盖通用方法)
* @param ctx gin请求对象
* @param entity 验证数据
* @return *MsgEntity 返回验证结果
*/
func (service *ServiceBaseFunc) CheckRepeatByAdd(ctx ginutil.Context, entity dbinfo.Entity) *msgentity.MsgEntity {
return msgentity.Success(nil, "验证通过(默认验证通过)")
}
/**
* 验证更新数据是否存在重复 (一旦使用则覆盖通用方法)
* @param ctx gin请求对象
* @param entity 待验证数据
* @return *MsgEntity 返回验证结果
*/
func (service *ServiceBaseFunc) CheckRepeatByEdit(ctx ginutil.Context, entity dbinfo.Entity) *msgentity.MsgEntity {
return msgentity.Success(nil, "验证通过(默认验证通过)")
}
/**
* 新增
* entity 检查用数据结构
* data 数据
*/
func (service ServiceBaseFunc) Add(ctx ginutil.Context, entity dbinfo.Entity, data map[string]interface{}) *msgentity.MsgEntity {
if dbinfo.EntityHasPid(entity) {
return service.AddNode(ctx, entity, data)
}
return service.AddCommon(ctx, entity, data)
}
/**
* 新增普通数据
* entity 检查用数据结构
* data 数据
*/
func (service ServiceBaseFunc) AddCommon(ctx ginutil.Context, entity dbinfo.Entity, data map[string]interface{}) *msgentity.MsgEntity {
stringutil.TrimAttribute(data) //清除对象各个属性的值的前后空格
//maputil.RemoveData(data, []string{"uId", "sId", "iId", "sCreator", "sModifieder", "dCreateDate", "dModifiedDate"}) //清理不能由前端定义的字段
maputil.RemoveData(data, []string{dbinfo.TableMajorKeyString, dbinfo.TableMajorKeyAutoInt, dbinfo.TableMajorKeyUuId, dbinfo.TableCreatorName, dbinfo.TableCreateDateName, dbinfo.TableModifiederName, dbinfo.TableModifiedDateName, dbinfo.TableVersionName}) //清理不能由前端定义的字段
//iCode, err := dbinfo.ValidAttr(data, entity, []string{"uId", "sId", "iId", "sCreator", "sModifieder", "dCreateDate", "dModifiedDate"}) //对对象中添加了dbinfo.DataInfo注解的不为nil的属性检查限制
iCode, err := dbinfo.ValidAttr(data, entity, []string{dbinfo.TableMajorKeyString, dbinfo.TableMajorKeyAutoInt, dbinfo.TableMajorKeyUuId, dbinfo.TableCreatorName, dbinfo.TableCreateDateName, dbinfo.TableModifiederName, dbinfo.TableModifiedDateName}) //对对象中添加了dbinfo.DataInfo注解的不为nil的属性检查限制
if err != nil {
return msgentity.Err(iCode+7000, err)
}
commons, iCode, err := dbinfo.ToEntity(data, entity)
if err != nil {
return msgentity.Err(iCode+7010, err)
}
dbinfo.SetDefault(commons, false) //对对象中添加了dataInfo注解的属性添加默认值
me := service.SupplyDbEntityAttrByAdd(ctx, commons, "", "")
if !me.Gsuccess {
return me.IncCode(7030)
}
iCode, err = dbinfo.ValidAttrByAdd(commons, []string{}) //对对象中添加了dbinfo.DataInfo注解的属性检查限制
if err != nil {
return msgentity.Err(iCode+7020, err)
}
me = service.ValidEntityRepeatByAdd(ctx, commons) //验证新增数据是否存在重复
if !me.Gsuccess {
return me.IncCode(7030)
}
return CommonDao.AddCommon(commons)
}
/**
* 新增树节点
* entity 检查用数据结构
* data 数据
*/
func (service ServiceBaseFunc) AddNode(ctx ginutil.Context, entity dbinfo.Entity, data map[string]interface{}) *msgentity.MsgEntity {
stringutil.TrimAttribute(data) //清除对象各个属性的值的前后空格
//maputil.RemoveData(data, []string{"uId", "sId", "iId", "sCreator", "sModifieder", "dCreateDate", "dModifiedDate"}) //清理不能由前端定义的字段
maputil.RemoveData(data, []string{dbinfo.TableMajorKeyString, dbinfo.TableMajorKeyAutoInt, dbinfo.TableMajorKeyUuId, dbinfo.TableCreatorName, dbinfo.TableCreateDateName, dbinfo.TableModifiederName, dbinfo.TableModifiedDateName, dbinfo.TableVersionName}) //清理不能由前端定义的字段
//iCode, err := dbinfo.ValidAttr(data, entity, []string{"uId", "sId", "iId", "sCreator", "sModifieder", "dCreateDate", "dModifiedDate"}) //对对象中添加了dbinfo.DataInfo注解的不为nil的属性检查限制
iCode, err := dbinfo.ValidAttr(data, entity, []string{dbinfo.TableMajorKeyString, dbinfo.TableMajorKeyAutoInt, dbinfo.TableMajorKeyUuId, dbinfo.TableCreatorName, dbinfo.TableCreateDateName, dbinfo.TableModifiederName, dbinfo.TableModifiedDateName}) //对对象中添加了dbinfo.DataInfo注解的不为nil的属性检查限制
if err != nil {
return msgentity.Err(iCode+7020, err)
}
commons, iCode, err := dbinfo.ToEntity(data, entity)
if err != nil {
return msgentity.Err(iCode+7010, err)
}
dbinfo.SetDefault(commons, false) //对对象中添加了dataInfo注解的属性添加默认值
me := service.SupplyDbEntityAttrByAdd(ctx, commons, "", "")
if !me.Gsuccess {
return me.IncCode(7030)
}
iCode, err = dbinfo.ValidAttrByAdd(commons, []string{}) //对对象中添加了dbinfo.DataInfo注解的属性检查限制
if err != nil {
return msgentity.Err(iCode+7020, err)
}
me = service.ValidEntityRepeatByAdd(ctx, commons) //验证新增数据是否存在重复
if !me.Gsuccess {
return me.IncCode(7030)
}
return CommonDao.AddNode(commons)
}
// 批量新增
func (service ServiceBaseFunc) Adds(ctx ginutil.Context, entitys []dbinfo.Entity, list []map[string]interface{}) *msgentity.MsgEntity {
if len(list) < 1 {
return msgentity.Err(8001, "没有需要保存的数据")
}
entitysNew := []dbinfo.Entity{}
for k, vData := range list {
stringutil.TrimAttribute(vData) //清除对象各个属性的值的前后空格
entity := entitys[k]
maputil.RemoveData(vData, []string{dbinfo.TableMajorKeyString, dbinfo.TableMajorKeyAutoInt, dbinfo.TableMajorKeyUuId, dbinfo.TableCreatorName, dbinfo.TableCreateDateName, dbinfo.TableModifiederName, dbinfo.TableModifiedDateName, dbinfo.TableVersionName}) //清理不能由前端定义的字段
iCode, err := dbinfo.ValidAttr(vData, entity, []string{dbinfo.TableMajorKeyString, dbinfo.TableMajorKeyAutoInt, dbinfo.TableMajorKeyUuId, dbinfo.TableCreatorName, dbinfo.TableCreateDateName, dbinfo.TableModifiederName, dbinfo.TableModifiedDateName}) //对对象中添加了dbinfo.DataInfo注解的不为nil的属性检查限制
if err != nil {
return msgentity.Err(iCode+7000, err)
}
commons, iCode, err := dbinfo.ToEntity(vData, entity)
if err != nil {
return msgentity.Err(iCode+7010, err)
}
dbinfo.SetDefault(commons, false) //对对象中添加了dataInfo注解的属性添加默认值
me := service.SupplyDbEntityAttrByAdd(ctx, commons, "", "")
if !me.Gsuccess {
return me.IncCode(7030)
}
iCode, err = dbinfo.ValidAttrByAdd(commons, []string{}) //对对象中添加了dbinfo.DataInfo注解的属性检查限制
if err != nil {
return msgentity.Err(iCode+7020, err)
}
me = service.ValidEntityRepeatByAdd(ctx, commons) //验证新增数据是否存在重复
if !me.Gsuccess {
return me.IncCode(7030)
}
entitysNew = append(entitysNew, commons)
}
return CommonDao.Adds(entitysNew)
}
// 批量新增
func (service ServiceBaseFunc) AddList(ctx ginutil.Context, entitys []dbinfo.Entity) *msgentity.MsgEntity {
if len(entitys) < 1 {
return msgentity.Err(8001, "没有需要保存的数据")
}
for _, entity := range entitys {
dbinfo.SetDefault(entity, false) //对对象中添加了dataInfo注解的属性添加默认值
me := service.SupplyDbEntityAttrByAdd(ctx, entity, "", "")
if !me.Gsuccess {
return me.IncCode(7030)
}
}
return CommonDao.Adds(entitys)
}
/**
* 修改状态
* @param entity 实体类
* @param id 编号
* @param iState 状态值
* @param iVersion 记录版本号
* @param sMemo 备注
* @param unidirectional 是否单向 设置为单向则新值必须大于旧值才能执行
* @return msgentity.MsgEntity 返回执行情况
*/
func (service ServiceBaseFunc) ChangeState(ctx ginutil.Context, entity dbinfo.Entity, id interface{}, iState int, iVersion int, sMemo string, unidirectional bool) *msgentity.MsgEntity {
if fmt.Sprintf("%v", id) == "" {
return msgentity.Err(8001, "记录编号参数为空!")
}
return CommonDao.ChangeState(entity, id, iState, iVersion, sMemo, unidirectional)
}
/**
* 修改步骤值(如果设置为单向则新值必须大于旧值)
* @param id 编号
* @param iSetp 步骤值
* @param iVersion 记录版本号
* @param sMemo 备注
* @param unidirectional 是否单向 设置为单向则新值必须大于旧值才能执行
* @param entity 实体类
* @return msgentity.MsgEntity 返回执行情况
*/
func (service ServiceBaseFunc) ChangeSetp(ctx ginutil.Context, entity dbinfo.Entity, id interface{}, iSetp int, iVersion int, sMemo string, unidirectional bool) *msgentity.MsgEntity {
if fmt.Sprintf("%v", id) == "" {
return msgentity.Err(8001, "记录编号参数为空!")
}
return CommonDao.ChangeSetp(entity, id, iSetp, iVersion, sMemo, unidirectional)
}
/**
* 删除
* @param entity 对象类型
* @param id 记录编号值
* @param iVersion 记录版本号
* @return msgentity.MsgEntity
*/
func (service ServiceBaseFunc) Del(ctx ginutil.Context, entity dbinfo.Entity, id interface{}, iVersion int) *msgentity.MsgEntity {
if id == nil {
return msgentity.Err(8001, "记录编号为空")
}
if dbinfo.EntityHasVersion(entity) && (iVersion < 1) && (iVersion != integerutil.MaxInt()) {
return msgentity.Err(8002, "记录版本号不正确")
}
onlyCreator := !EnableTag(dbinfo.SimpleTableName(entity), 7) //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
physics := !EnableTag(dbinfo.SimpleTableName(entity), 1) //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
if !physics && dbinfo.EntityHasDelSign(entity) { //有逻辑删除字段标识才能进行逻辑删除
return CommonDao.DelSign(entity, id, iVersion, CurrentLoginUserId(ctx.Request), onlyCreator) //标识删除
}
return CommonDao.Del(entity, id, iVersion, CurrentLoginUserId(ctx.Request), onlyCreator)
}
/**
* 删除
* @param entity 对象类型
* @param where 执行条件
* @return msgentity.MsgEntity
*/
func (service ServiceBaseFunc) DelByMap(ctx ginutil.Context, entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo) *msgentity.MsgEntity {
if entity == nil {
return msgentity.Err(8001, "结构体参数为nil")
}
onlyCreator := !EnableTag(dbinfo.SimpleTableName(entity), 7) //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
physics := !EnableTag(dbinfo.SimpleTableName(entity), 1) //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
if !physics && dbinfo.EntityHasDelSign(entity) { //有逻辑删除字段标识才能进行逻辑删除
return CommonDao.DelSignByMap(entity, whereInfo, CurrentLoginUserId(ctx.Request), onlyCreator) //标识删除
}
return CommonDao.DelByMap(entity, whereInfo, CurrentLoginUserId(ctx.Request), onlyCreator)
}
/**
* 按实体保留map中的数据
* entity 参考的结构体
* data 数据
*/
func (service ServiceBaseFunc) HoldByEntity(entity dbinfo.Entity, data map[string]interface{}) map[string]interface{} {
columns := entity.BaseColumnNames()
result := map[string]interface{}{}
for key, value := range data {
if strings.Contains(columns, key) {
continue
}
result[key] = value
}
return result
}
// func (service ServiceBaseFunc) getBaseEntity(entity dbinfo.Entity) interface{} {
// var rte reflect.Type
// var rve reflect.Value
// typeOf := reflect.TypeOf(entity) //通过反射获取type定义
// if typeOf.Kind() == reflect.Ptr { //是否指针类型
// rve = reflect.ValueOf(entity).Elem()
// rte = rve.Type() // 取得struct变量的指针
// } else if "reflect.Value" == typeOf.String() {
// rve = entity.(reflect.Value)
// rte = rve.Type()
// } else {
// rve = reflect.ValueOf(entity)
// rte = reflect.ValueOf(entity).Type()
// }
// for k := 0; k < rte.NumField(); k++ {
// field := rte.Field(k)
// if field.Anonymous && strings.HasSuffix(field.Name, "Base") {
// return rve.Field(k) //找到
// }
// }
// return entity //没找到
// }
/**
* 修改
* @param entity 对象类型
* @param id 记录编号值
* @param iVersion 记录版本号
* @param data 待更新的字段和值
* @return msgentity.MsgEntity
*/
func (service ServiceBaseFunc) Edit(ctx ginutil.Context, entity dbinfo.Entity, id interface{}, iVersion int, data map[string]interface{}) *msgentity.MsgEntity {
if fmt.Sprintf("%v", id) == "" {
return msgentity.Err(7001, "记录编号参数为空!")
}
baseEntity := entity.BaseEntity() //取基础数据库实体
data = reflectutil.HoldByEntity(baseEntity, data, "", "G") //按实体保留map中的数据
// maputil.RemoveData(data, []string{"uId", "sId", "iId", "sPath", "sCreator", "sModifieder", "dCreateDate", "dModifiedDate", "iVersion",
// "u_id", "s_id", "i_id", "s_path", "s_creator", "s_modifieder", "d_create_date", "d_modified_date", "i_version"}) //清理不能由前端定义的字段
maputil.RemoveData(data, []string{dbinfo.TableMajorKeyString, dbinfo.TableMajorKeyAutoInt, dbinfo.TableMajorKeyUuId, dbinfo.TablePathKey, dbinfo.TableCreatorName, dbinfo.TableCreateDateName, dbinfo.TableModifiederName, dbinfo.TableModifiedDateName}) //清理不能由前端定义的字段
if len(data) < 1 {
return msgentity.Err(7002, "更新操作提供的参数为空!")
}
if dbinfo.EntityHasVersion(entity) && (1 > iVersion) {
return msgentity.Err(7003, "记录版本号参数必须大于0!")
}
var oldData map[string]interface{}
if dbinfo.EntityHasRecordKey(entity) { //如果存在RecordKey标识,则必须进行记录校验
me := CommonDao.FindById(entity, id, "", false)
if me == nil {
return msgentity.Err(7004, "记录不存在!")
}
oldData = me.Gdata.(map[string]interface{})
nowKey := dbinfo.CreateRecordKeyByMap(entity, oldData)
if nowKey != oldData["RecordKey"] {
return msgentity.Err(7005, "记录校验失败!")
}
}
stringutil.TrimAttribute(data) //清除对象各个属性的值的前后空格
// iCode, err := dbinfo.ValidAttr(data, baseEntity, []string{"uId", "sId", "iId", "sCreator", "sModifieder", "dCreateDate", "dModifiedDate", //对对象中添加了dbinfo.DataInfo注解的不为nil的属性检查限制
// "u_id", "s_id", "i_id", "s_path", "s_creator", "s_modifieder", "d_create_date", "d_modified_date", "i_version"}) //对对象中添加了dbinfo.DataInfo注解的不为nil的属性检查限制
iCode, err := dbinfo.ValidAttr(data, baseEntity, []string{dbinfo.TableMajorKeyString, dbinfo.TableMajorKeyAutoInt, dbinfo.TableMajorKeyUuId, dbinfo.TablePathKey, dbinfo.TableCreateDateName, dbinfo.TableModifiedDateName}) //对对象中添加了dbinfo.DataInfo注解的不为nil的属性检查限制
if err != nil {
return msgentity.Err(iCode + 7020)
}
me := service.ValidEntityRepeatByEdit(ctx, entity, id, data) //验证更新数据是否存在重复
if !me.Gsuccess {
return me.IncCode(7030)
}
//进行前端不可传递数据处理,如:修改者、修改时间等信息清理并赋值
service.SupplyDbEntityAttrByEdit(ctx, data, entity)
if dbinfo.EntityHasRecordKey(entity) { //如果存在RecordKey标识,则必须重新对数据的检验字段进行生成
for key, val := range data { //覆盖旧数据:警告oldData后面不能再用
oldData[key] = val
}
data[dbinfo.TableRecordKeyName] = dbinfo.CreateRecordKeyByMap(entity, oldData) //更新RecordKey
}
onlyCreator := !EnableTag(dbinfo.SimpleTableName(entity), 6) //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
return CommonDao.Edit(entity, id, iVersion, data, CurrentLoginUserId(ctx.Request), onlyCreator)
}
/**
* 批量修改
* @param entity 对象类型
* @param datas 待更新的字段和值集合
* @return msgentity.MsgEntity
*/
func (service ServiceBaseFunc) Edits(ctx ginutil.Context, entity dbinfo.Entity, datas []map[string]interface{}) *msgentity.MsgEntity {
if len(datas) < 1 {
return msgentity.Err(7001, "待更新集合参数为空!")
}
baseEntity := entity.BaseEntity() //取基础数据库实体
tableInfo := dbinfo.GetTableInfo(entity)
onlyCreator := !EnableTag(dbinfo.SimpleTableName(entity), 6) //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
removeArray := []string{dbinfo.TableMajorKeyString, dbinfo.TableMajorKeyAutoInt, dbinfo.TableMajorKeyUuId, dbinfo.TablePathKey, dbinfo.TableCreatorName, dbinfo.TableCreateDateName, dbinfo.TableModifiederName, dbinfo.TableModifiedDateName}
validArray := []string{dbinfo.TableMajorKeyString, dbinfo.TableMajorKeyAutoInt, dbinfo.TableMajorKeyUuId, dbinfo.TablePathKey, dbinfo.TableCreateDateName, dbinfo.TableModifiedDateName}
result := 0
for _, data := range datas {
id := data[tableInfo.GsKeyName]
iVersion := -1
temp, ok := data[dbinfo.TableVersionName]
if ok {
iVersion = temp.(int)
}
data = reflectutil.HoldByEntity(baseEntity, data, "", "G") //按实体保留map中的数据
// maputil.RemoveData(data, []string{"uId", "sId", "iId", "sPath", "sCreator", "sModifieder", "dCreateDate", "dModifiedDate", "iVersion",
// "u_id", "s_id", "i_id", "s_path", "s_creator", "s_modifieder", "d_create_date", "d_modified_date", "i_version"}) //清理不能由前端定义的字段
maputil.RemoveData(data, removeArray) //清理不能由前端定义的字段
if len(data) < 1 {
return msgentity.Err(7002, "更新操作提供的参数为空!")
}
if dbinfo.EntityHasVersion(entity) && (1 > iVersion) {
return msgentity.Err(7003, "记录版本号参数必须大于0!")
}
var oldData map[string]interface{}
if dbinfo.EntityHasRecordKey(entity) { //如果存在RecordKey标识,则必须进行记录校验
me := CommonDao.FindById(entity, id, "", false)
if me == nil {
return msgentity.Err(7004, "记录不存在!")
}
oldData = me.Gdata.(map[string]interface{})
nowKey := dbinfo.CreateRecordKeyByMap(entity, oldData)
if nowKey != oldData["RecordKey"] {
return msgentity.Err(7005, "记录校验失败!")
}
}
stringutil.TrimAttribute(data) //清除对象各个属性的值的前后空格
// iCode, err := dbinfo.ValidAttr(data, baseEntity, []string{"uId", "sId", "iId", "sCreator", "sModifieder", "dCreateDate", "dModifiedDate", //对对象中添加了dbinfo.DataInfo注解的不为nil的属性检查限制
// "u_id", "s_id", "i_id", "s_path", "s_creator", "s_modifieder", "d_create_date", "d_modified_date", "i_version"}) //对对象中添加了dbinfo.DataInfo注解的不为nil的属性检查限制
iCode, err := dbinfo.ValidAttr(data, baseEntity, validArray) //对对象中添加了dbinfo.DataInfo注解的不为nil的属性检查限制
if err != nil {
return msgentity.Err(iCode + 7020)
}
me := service.ValidEntityRepeatByEdit(ctx, entity, id, data) //验证更新数据是否存在重复
if !me.Gsuccess {
return me.IncCode(7030)
}
//进行前端不可传递数据处理,如:修改者、修改时间等信息清理并赋值
service.SupplyDbEntityAttrByEdit(ctx, data, entity)
if dbinfo.EntityHasRecordKey(entity) { //如果存在RecordKey标识,则必须重新对数据的检验字段进行生成
for key, val := range data { //覆盖旧数据:警告oldData后面不能再用
oldData[key] = val
}
data[dbinfo.TableRecordKeyName] = dbinfo.CreateRecordKeyByMap(entity, oldData) //更新RecordKey
}
me = CommonDao.Edit(entity, id, iVersion, data, CurrentLoginUserId(ctx.Request), onlyCreator)
if me.Gsuccess {
result++
}
}
return msgentity.Success(result, "请求结束")
}
/**
* 根据主键查询数据
* id 主键
* entity 检查用数据结构
*/
func (service ServiceBaseFunc) FindById(ctx ginutil.Context, entity dbinfo.Entity, id interface{}) *msgentity.MsgEntity {
if id == nil {
return msgentity.Err(1001, "记录编号为空")
}
onlyCreator := !EnableTag(dbinfo.SimpleTableName(entity), 5) //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
return CommonDao.FindById(entity, id, CurrentLoginUserId(ctx.Request), onlyCreator)
}
// 查询所有数据
func (service ServiceBaseFunc) FindAll(ctx ginutil.Context, entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo) *msgentity.MsgEntity {
onlyCreator := !EnableTag(dbinfo.SimpleTableName(entity), 5) //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
return CommonDao.FindAll(entity, whereInfo, CurrentLoginUserId(ctx.Request), onlyCreator)
}
// 查询指定时间内数据
func (service ServiceBaseFunc) FindByDate(ctx ginutil.Context, entity dbinfo.Entity, sDateSt string, sDateEd string) *msgentity.MsgEntity {
onlyCreator := !EnableTag(dbinfo.SimpleTableName(entity), 5) //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
return CommonDao.FindByDate(entity, sDateSt, sDateEd, CurrentLoginUserId(ctx.Request), onlyCreator)
}
// 查询指定行数据
func (service ServiceBaseFunc) FindByRow(ctx ginutil.Context, entity dbinfo.Entity, id interface{}) *msgentity.MsgEntity {
if id == nil {
return msgentity.Err(1001, "记录编号为空")
}
sId := fmt.Sprintf("%v", id)
if sId == "" {
return msgentity.Err(1002, "记录编号为空")
}
onlyCreator := !EnableTag(dbinfo.SimpleTableName(entity), 5) //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
return CommonDao.FindByRow(entity, id, CurrentLoginUserId(ctx.Request), onlyCreator)
}
// 查询分页数据
func (service ServiceBaseFunc) FindByPage(ctx ginutil.Context, entity dbinfo.Entity, findByPageParam dbinfo.FindByPageParam) *msgentity.MsgEntity {
onlyCreator := !EnableTag(dbinfo.SimpleTableName(entity), 5) //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
return CommonDao.FindByPage(entity, findByPageParam, CurrentLoginUserId(ctx.Request), onlyCreator)
}
/**
* 补充数据库实体类的数据--新增
* @param entity
* @param selfId 自提供的编号,防止从序列中获取
* @param idValuePrefix Id前缀
* @return
*/
func (service ServiceBaseFunc) SupplyDbEntityAttrByAdd(ctx ginutil.Context, entity dbinfo.Entity, selfId string, idValuePrefix string) *msgentity.MsgEntity {
if entity == nil {
return msgentity.Err(1001, "待存储的数据实体不能为nil")
}
dbinfo.SetDefault(entity, false) //对对象中添加了dataInfo注解的属性添加默认值
sLoginUserId := CurrentLoginUserId(ctx.Request) //取当前登录用户编号
date := time.Now()
dbinfo.SetVal(entity, dbinfo.TableCreatorName, sLoginUserId) // 设置当前操作用户
dbinfo.SetVal(entity, dbinfo.TableModifiederName, sLoginUserId) // 设置当前操作用户
dbinfo.SetVal(entity, dbinfo.TableCreateDateName, date) // 设置新增时间
dbinfo.SetVal(entity, dbinfo.TableModifiedDateName, date) // 设置修改时间
dbinfo.SetVal(entity, dbinfo.TableIndexName, 1) // 设置排序值
dbinfo.SetVal(entity, dbinfo.TableStateName, 1) // 设置状态值
dbinfo.SetVal(entity, dbinfo.TableVersionName, 1) // 设置版本号
vNew := selfId
idName := dbinfo.EntityKeyName(entity)
if selfId != "" { //有自定义id值
dbinfo.SetVal(entity, idName, strings.ToUpper(vNew))
} else if (dbinfo.TableMajorKeyUuId == idName) && (strings.HasPrefix(idName, "u")) { //默认命名模式下,按UUID设置值
if dbinfo.EntityKeyLength(entity) == 32 {
vNew = strings.Replace(uuid.NewV4().String(), "-", "", -1) //取uuid
dbinfo.SetVal(entity, dbinfo.TableMajorKeyUuId, strings.ToUpper(vNew))
} else if dbinfo.EntityKeyLength(entity) == 22 {
dbinfo.SetVal(entity, dbinfo.TableMajorKeyUuId, u64util.Get(idValuePrefix))
} else {
dbinfo.SetVal(entity, dbinfo.TableMajorKeyUuId, u64util.Get(idValuePrefix))
}
} else if (dbinfo.TableMajorKeyString == idName) && (strings.HasPrefix(idName, "s")) { //默认命名模式下,如果不是自增长,并且没有自定义id值,才能进行从序列中取新id的方法
if dbinfo.EntityHasPath(entity) { //对象中存在sPath,则id只需要4位
pidValue := dbinfo.GetVal(entity, dbinfo.TablePidKey)
pid := fmt.Sprintf("%v", pidValue)
if nil != pidValue {
pid = dbinfo.TableTreeRootValue
}
me := CommonDao.NewChildId(entity, pid)
if !me.Gsuccess {
return me
}
vNew = me.Gdata.(string)
dbinfo.SetVal(entity, dbinfo.TableMajorKeyString, vNew)
} else if idValuePrefix == "" {
vNew = GetNewId(dbinfo.EntityKeyLength(entity), dbinfo.SimpleTableName(entity))
dbinfo.SetVal(entity, dbinfo.TableMajorKeyString, vNew)
} else {
iLength := dbinfo.EntityKeyLength(entity) - len(idValuePrefix)
vNew = idValuePrefix + GetNewId(iLength, dbinfo.SimpleTableName(entity))
dbinfo.SetVal(entity, dbinfo.TableMajorKeyString, vNew)
}
} else if !dbinfo.EntityAutoKey(entity) { //不是自增长主键则属于字符串类型,用于无法通过字段名区分是否uuid还是序列的情况
if dbinfo.EntityKeyLength(entity) == 32 {
vNew = strings.Replace(uuid.NewV4().String(), "-", "", -1) //取uuid
dbinfo.SetVal(entity, dbinfo.TableMajorKeyUuId, strings.ToUpper(vNew))
} else if dbinfo.EntityKeyLength(entity) == 22 {
dbinfo.SetVal(entity, dbinfo.TableMajorKeyUuId, u64util.Get(idValuePrefix))
} else if dbinfo.EntityHasPath(entity) { //对象中存在sPath,则id只需要4位
pidValue := dbinfo.GetVal(entity, dbinfo.TablePidKey)
pid := fmt.Sprintf("%v", pidValue)
if nil != pidValue {
pid = dbinfo.TableTreeRootValue
}
me := CommonDao.NewChildId(entity, pid)
if !me.Gsuccess {
return me
}
vNew = me.Gdata.(string)
dbinfo.SetVal(entity, dbinfo.TableMajorKeyString, vNew)
} else if idValuePrefix == "" {
vNew = GetNewId(dbinfo.EntityKeyLength(entity), dbinfo.SimpleTableName(entity))
dbinfo.SetVal(entity, dbinfo.TableMajorKeyString, vNew)
} else {
iLength := dbinfo.EntityKeyLength(entity) - len(idValuePrefix)
vNew = idValuePrefix + GetNewId(iLength, dbinfo.SimpleTableName(entity))
dbinfo.SetVal(entity, dbinfo.TableMajorKeyString, vNew)
}
}
//--如果有sPid字段则进行部分处理--//
if dbinfo.EntityHasPid(entity) {
sPid := dbinfo.GetVal(entity, dbinfo.TablePidKey)
if (sPid == nil) || (sPid.(string) == "") { //如果sPid为空,则默认赋值'00'
dbinfo.SetVal(entity, dbinfo.TablePidKey, dbinfo.TableTreeRootValue)
}
}
//--如果有sPath字段则进行部分处理--//
if dbinfo.EntityHasPath(entity) {
sPid := dbinfo.GetVal(entity, dbinfo.TablePidKey)
sPath := dbinfo.GetVal(entity, dbinfo.TablePathKey)
if ((sPath == nil) || (sPid.(string) == "") || (sPath.(string) == "/00/")) && (dbinfo.TableTreeRootValue == sPid.(string)) { //如果sPid为空,则默认赋值'00'
dbinfo.SetVal(entity, dbinfo.TablePathKey, "/00/"+vNew+"/")
} else {
sPath := CommonDao.GetPath(sPid.(string), dbinfo.EntityDbName(entity), dbinfo.SimpleTableName(entity))
dbinfo.SetVal(entity, dbinfo.TablePathKey, sPath+vNew+"/")
}
}
//--如果有sRecordKey字段则进行部分处理--//
if dbinfo.EntityHasRecordKey(entity) {
if recordKeyJam == "" {
recordKeyJam = ReadConfigKey("App", "RecordKeyJam", "12345678").(string)
}
key := reflectutil.DoMethod(entity, "CreateRecordKey", reflect.ValueOf(recordKeyJam))
if len(key) > 0 {
dbinfo.SetVal(entity, dbinfo.TableRecordKeyName, key[0])
}
}
return msgentity.Success(1999, "补充数据完毕!")
}
/**
* 补充数据库实体类的数据--修改
* @param ctx
* @param data 待修改的数据
* @param entity 参照结构体
* @return
*/
func (service ServiceBaseFunc) SupplyDbEntityAttrByEdit(ctx ginutil.Context, data map[string]interface{}, entity dbinfo.Entity) *msgentity.MsgEntity {
if data == nil || len(data) < 1 {
return msgentity.Err(1001, "待修改的数据不能为nil")
}
sLoginUserId := CurrentLoginUserId(ctx.Request) //取当前登录用户编号
if dbinfo.EntityHasCreator(entity) {
delete(data, dbinfo.TableCreatorName) // 清理,限制不允许修改创建人
}
if dbinfo.EntityHasCreateDate(entity) {
delete(data, dbinfo.TableCreateDateName) // 清理,限制不允许修改设置新增时间
}
if dbinfo.EntityHasDelSign(entity) {
delete(data, dbinfo.TableDelSignName) // 清理,限制不允许修改删除标识
}
if dbinfo.EntityHasModifieder(entity) {
data[dbinfo.TableModifiederName] = sLoginUserId // 设置当前操作用户
}
if dbinfo.EntityHasModifiedDate(entity) {
data[dbinfo.TableModifiedDateName] = time.Now() // 设置修改时间
}
if dbinfo.EntityHasVersion(entity) {
data[dbinfo.TableVersionName] = data[dbinfo.TableVersionName].(int) + 1 // 设置版本号
}
//--如果有sRecordKey字段则进行部分处理,为提高效率,在edit中处理--//
return msgentity.Success(1999, "补充数据完毕!")
}
/**
* 验证新增数据是否存在重复
*
*/
func (service ServiceBaseFunc) ValidEntityRepeatByAdd(ctx ginutil.Context, entity dbinfo.Entity) *msgentity.MsgEntity {
customService := serviceMap[dbinfo.SimpleTableName(entity)]
//-- 树形结构 --//
if dbinfo.EntityHasPid(entity) {
if customService == nil { //如果没有自定义业务层
return service.CommonCheckRepeatByAddAndTree(ctx, entity) //通用树型结构表添加数据时重复检查方法
}
method := reflectutil.GetMethod(customService, "CheckRepeatByAddAndTree")
if !method.IsValid() { //如果自定义业务层定义了自检方法
return service.CommonCheckRepeatByAddAndTree(ctx, entity) //通用树型结构表添加数据时重复检查方法
}
result := reflectutil.DoMethod(customService, "CheckRepeatByAddAndTree", entity)
me := result[0].Interface()
return me.(*msgentity.MsgEntity)
}
//--不是树形数据则使用普通方法检查--//
if customService == nil { //如果没有自定义业务层
return service.CommonCheckRepeatByAdd(ctx, entity) //通用添加数据时重复检查方法
}
method := reflectutil.GetMethod(customService, "CheckRepeatByAdd")
if !method.IsValid() { //如果自定义业务层定义了自检方法
return service.CommonCheckRepeatByAdd(ctx, entity) //通用添加数据时重复检查方法
}
result := reflectutil.DoMethod(customService, "CheckRepeatByAdd", entity)
me := result[0].Interface()
return me.(*msgentity.MsgEntity)
}
/**
* 验证更新数据是否存在重复
*
*/
func (service ServiceBaseFunc) ValidEntityRepeatByEdit(ctx ginutil.Context, entity dbinfo.Entity, id interface{}, data map[string]interface{}) *msgentity.MsgEntity {
customService := serviceMap[dbinfo.SimpleTableName(entity)]
//-- 树形结构 --//
if dbinfo.EntityHasPid(entity) {
if customService == nil { //如果没有自定义业务层
return service.CommonCheckRepeatByEditAndTree(ctx, entity, id, data["sName"]) //通用树型结构表添加数据时重复检查方法
}
method := reflectutil.GetMethod(customService, "CheckRepeatByEditAndTree")
if !method.IsValid() { //如果自定义业务层定义了自检方法
return service.CommonCheckRepeatByEditAndTree(ctx, entity, id, data["sName"]) //通用树型结构表添加数据时重复检查方法
}
result := reflectutil.DoMethod(customService, "CheckRepeatByEditAndTree", id, data["sName"])
me := result[0].Interface()
return me.(*msgentity.MsgEntity)
}
//--不是树形数据则使用普通方法检查--//
if customService == nil { //如果没有自定义业务层
return service.CommonCheckRepeatByEdit(ctx, entity, id, data) //通用添加数据时重复检查方法
}
method := reflectutil.GetMethod(customService, "CheckRepeatByEdit")
if !method.IsValid() { //如果自定义业务层定义了自检方法
return service.CommonCheckRepeatByEdit(ctx, entity, id, data) //通用添加数据时重复检查方法
}
result := reflectutil.DoMethod(customService, "CheckRepeatByEdit", data, id)
me := result[0].Interface()
return me.(*msgentity.MsgEntity)
}
/**
* 通用树型结构表添加数据时重复检查方法
* entity
*/
func (service ServiceBaseFunc) CommonCheckRepeatByAddAndTree(ctx ginutil.Context, entity dbinfo.Entity) *msgentity.MsgEntity {
vName := dbinfo.GetVal(entity, dbinfo.TableTreeNodeName)
if nil == vName {
return msgentity.Err(1001, "节点名称为空")
}
sName := vName.(string)
var sPid string
vPid := dbinfo.GetVal(entity, dbinfo.TablePidKey)
if nil != vPid {
sPid = vPid.(string)
} else {
sPid = dbinfo.TableTreeRootValue
}
if sPid == "" {
sPid = dbinfo.TableTreeRootValue
}
where := make(map[string]interface{})
//同一层节点下,展现名不能相同//
var build strings.Builder
build.WriteString("SELECT SUM(iCount) AS iCount FROM (")
if dbinfo.EntityHasSign(entity) {
build.WriteString(" select SIGN(COUNT(1) * 10) as iCount from ${sDbTableName}")
build.WriteString(" where ")
build.WriteString(dbinfo.TablesSign)
build.WriteString(" = @sSign")
build.WriteString(dbinfo.TablesSign)
build.WriteString(" UNION ALL ")
where[dbinfo.TablesSign] = dbinfo.GetVal(entity, dbinfo.TablesSign)
}
build.WriteString(" select SIGN(COUNT(1)) as iCount from ${sDbTableName}")
build.WriteString(" where ${dbinfo.TablePidKey} = @sPid and ${dbinfo.TableTreeNodeName} = @sName")
build.WriteString(") TMP")
txt := build.String()
txt = strings.Replace(txt, "${sDbTableName}", entity.TableName(), -1)
txt = strings.Replace(txt, "${sTableName}", dbinfo.SimpleTableName(entity), -1)
txt = strings.Replace(txt, "${dbinfo.TablePidKey}", dbinfo.TablePidKey, -1)
txt = strings.Replace(txt, "${dbinfo.TableTreeNodeName}", dbinfo.TableTreeNodeName, -1)
where[dbinfo.TablePidKey] = sPid
where[dbinfo.TableTreeNodeName] = sName
var iCount int
dbResult := gorm.Raw(txt, where).Find(&iCount)
if dbResult.Error != nil {
Log.Error("查询发生异常:", dbResult.Error)
return msgentity.Err(1002, "查询数据发生异常:", dbResult.Error)
}
if iCount != 0 {
return msgentity.Err(1003, "节点重复")
}
return msgentity.Success(1999, "节点未重复")
}
/**
* 通用树型结构表添加数据时重复检查方法
* entity
*/
func (service ServiceBaseFunc) CommonCheckRepeatByEditAndTree(ctx ginutil.Context, entity dbinfo.Entity, id interface{}, sName interface{}) *msgentity.MsgEntity {
if (sName == nil) || (sName == "") || (sName == "<nil>") {
return msgentity.Err(1001, "节点名称为空")
}
where := make(map[string]interface{})
//同一层节点下,展现名不能相同//
var build strings.Builder
build.WriteString("SELECT SUM(iCount) AS iCount FROM (")
if dbinfo.EntityHasSign(entity) {
build.WriteString(" select SIGN(COUNT(1) * 10) as iCount from ${sDbTableName}")
build.WriteString(" where ")
build.WriteString(dbinfo.TablesSign)
build.WriteString(" = @")
build.WriteString(dbinfo.TablesSign)
build.WriteString(" and ${sId} <> @sId")
build.WriteString(" UNION ALL ")
where[dbinfo.TablesSign] = dbinfo.GetVal(entity, dbinfo.TablesSign)
}
build.WriteString(" select SIGN(COUNT(1)) as iCount from ${sDbTableName}")
build.WriteString(" where ${sId} <> @sId")
build.WriteString(" and ${dbinfo.TablePidKey} = (select a.${dbinfo.TablePidKey} from ${sDbTableName} a where a.${sId} = @sId)")
build.WriteString(" and ${dbinfo.TableTreeNodeName} = #{sName}")
build.WriteString(") TMP")
txt := build.String()
txt = strings.Replace(txt, "${sDbTableName}", entity.TableName(), -1)
txt = strings.Replace(txt, "${sTableName}", dbinfo.SimpleTableName(entity), -1)
txt = strings.Replace(txt, "${sId}", dbinfo.EntityKeyName(entity), -1)
txt = strings.Replace(txt, "${dbinfo.TablePidKey}", dbinfo.TablePidKey, -1)
txt = strings.Replace(txt, "${dbinfo.TableTreeNodeName}", dbinfo.TableTreeNodeName, -1)
txt = strings.Replace(txt, "#{sName}", "@sName", -1)
where["sId"] = id
where["sName"] = sName
var iCount int
dbResult := gorm.Raw(txt, where).Find(&iCount)
if dbResult.Error != nil {
Log.Error("查询发生异常:", dbResult.Error)
return msgentity.Err(1002, "查询数据发生异常:", dbResult.Error)
}
if iCount != 0 {
return msgentity.Err(1003, "节点重复")
}
return msgentity.Success(1999, "节点未重复")
}
/**
* 通用添加数据时重复检查方法
* entity
*/
func (service ServiceBaseFunc) CommonCheckRepeatByAdd(ctx ginutil.Context, entity dbinfo.Entity) *msgentity.MsgEntity {
vCheckRepeatCombination := checkRepeatCombinationMap[dbinfo.SimpleTableName(entity)]
vCheckRepeatAlone := checkRepeatAloneMap[dbinfo.SimpleTableName(entity)]
k := 0
//检查待新增内容是否存在重复数据(多字段组合重复即重复)集合
if (vCheckRepeatCombination != nil) && (len(vCheckRepeatCombination) > 0) {
checkRepeatCombination := vCheckRepeatCombination
var build strings.Builder
build.WriteString("SELECT COUNT(1) AS iCount FROM ${sDbTableName} WHERE 1=1")
var temp strings.Builder
temp.WriteString("[")
where := make(map[string]interface{})
for _, value := range checkRepeatCombination {
build.WriteString(" AND ")
build.WriteString(value)
build.WriteString(" = @")
build.WriteString(value)
where[value] = reflectutil.GetFieldValue(entity, "G"+value)
dataInfo := entity.GetDataInfo(value)
temp.WriteString("、'")
temp.WriteString(dataInfo.GsComment)
temp.WriteString("'")
}
txt := strings.Replace(build.String(), "1=1 AND ", "", -1)
txt = strings.Replace(txt, "${sDbTableName}", entity.TableName(), -1)
txt = strings.Replace(txt, "${sTableName}", dbinfo.SimpleTableName(entity), -1)
iCount := 0
dbResult := gorm.Raw(txt, where).Find(&iCount)
if dbResult.Error != nil {
Log.Error("验证数据是否重复发生异常:", dbResult.Error)
return msgentity.Err(1001, "验证数据是否重复发生异常:", dbResult.Error)
}
if iCount != 0 {
temp.WriteString("]组合发现数据重复")
return msgentity.Err(1002, strings.Replace(temp.String(), "、", "", 1))
}
k++
}
//检查待新增内容是否存在重复数据(单独字段重复即重复)集合
if (vCheckRepeatAlone != nil) && (len(vCheckRepeatAlone) > 0) {
checkRepeatAlone := vCheckRepeatAlone
var build strings.Builder
build.WriteString("SELECT SUM(iCount) FROM (")
where := make(map[string]interface{})
for key, value := range checkRepeatAlone {
build.WriteString(" union all select (SIGN(COUNT(1)) * ")
build.WriteString(strconv.Itoa(value))
build.WriteString(") as iCount ")
build.WriteString(" from ${sDbTableName} ")
build.WriteString(" where ")
build.WriteString(key)
build.WriteString("= @")
build.WriteString(key)
where[key] = reflectutil.GetFieldValue(entity, "G"+key)
}
build.WriteString(") TMP")
txt := strings.Replace(build.String(), " union all ", " ", 1)
txt = strings.Replace(txt, "${sDbTableName}", entity.TableName(), -1)
txt = strings.Replace(txt, "${sTableName}", dbinfo.SimpleTableName(entity), -1)
iCount := 0
dbResult := gorm.Raw(txt, where).Find(&iCount)
if dbResult.Error != nil {
Log.Error("验证数据是否重复发生异常:", dbResult.Error)
return msgentity.Err(1003, "验证数据是否重复发生异常:", dbResult.Error)
}
if iCount != 0 {
var temp strings.Builder
str := fmt.Sprintf("%0*d", len(checkRepeatAlone), iCount)
array := []rune(str) //得到字符数组
ml := len(checkRepeatAlone)
for key, value := range checkRepeatAlone {
i := len(strconv.Itoa(value))
if array[ml-i] == 48 { // ASCII对应: '0' => 48, '1' => 49
continue
}
dataInfo := entity.GetDataInfo(key)
temp.WriteString("、'")
temp.WriteString(dataInfo.GsComment)
temp.WriteString("'")
}
temp.WriteString("存在重复")
return msgentity.Err(1004, strings.Replace(temp.String(), "、", "", 1))
}
k++
}
if k == 0 {
return msgentity.Success("没有设定验证函数,通过")
}
return msgentity.Success("经验证,通过")
}
/**
* 通用更新数据时重复检查方法
* entity
*/
func (service ServiceBaseFunc) CommonCheckRepeatByEdit(ctx ginutil.Context, entity dbinfo.Entity, id interface{}, data map[string]interface{}) *msgentity.MsgEntity {
vCheckRepeatCombination := checkRepeatCombinationMap[dbinfo.SimpleTableName(entity)]
vCheckRepeatAlone := checkRepeatAloneMap[dbinfo.SimpleTableName(entity)]
k := 0
//检查待修改内容是否存在重复数据(多字段组合重复即重复)集合
if (vCheckRepeatCombination != nil) && (len(vCheckRepeatCombination) > 0) {
checkRepeatCombination := vCheckRepeatCombination
var build strings.Builder
build.WriteString("SELECT COUNT(1) AS iCount FROM ${sDbTableName} WHERE 1=1")
var temp strings.Builder
temp.WriteString("[")
where := make(map[string]interface{})
where[dbinfo.EntityKeyName(entity)] = id
build.WriteString(" AND ")
build.WriteString(dbinfo.EntityKeyName(entity))
build.WriteString(" != @")
build.WriteString(dbinfo.EntityKeyName(entity))
for _, value := range checkRepeatCombination {
build.WriteString(" AND ")
build.WriteString(value)
build.WriteString(" = @")
build.WriteString(value)
where[value] = data[value] // reflectutil.GetFieldValue(entity, "G"+value)
dataInfo := entity.GetDataInfo(value)
temp.WriteString("、'")
temp.WriteString(dataInfo.GsComment)
temp.WriteString("'")
}
txt := strings.Replace(build.String(), "1=1 AND ", "", -1)
txt = strings.Replace(txt, "${sDbTableName}", entity.TableName(), -1)
txt = strings.Replace(txt, "${sTableName}", dbinfo.SimpleTableName(entity), -1)
iCount := 0
dbResult := gorm.Raw(txt, where).Find(&iCount)
if dbResult.Error != nil {
Log.Error("验证数据是否重复发生异常:", dbResult.Error)
return msgentity.Err(1001, "验证数据是否重复发生异常:", dbResult.Error)
}
if iCount != 0 {
temp.WriteString("]组合发现数据重复")
return msgentity.Err(1002, strings.Replace(temp.String(), "、", "", 1))
}
k++
}
//检查待修改内容是否存在重复数据(单独字段重复即重复)集合
if (vCheckRepeatAlone != nil) && (len(vCheckRepeatAlone) > 0) {
checkRepeatAlone := vCheckRepeatAlone
var build strings.Builder
build.WriteString("SELECT SUM(iCount) FROM (")
where := make(map[string]interface{})
where[dbinfo.EntityKeyName(entity)] = id
for key, value := range checkRepeatAlone {
build.WriteString(" union all select (SIGN(COUNT(1)) * ")
build.WriteString(strconv.Itoa(value))
build.WriteString(") as iCount ")
build.WriteString(" from ${sDbTableName} ")
build.WriteString(" where ")
build.WriteString(key)
build.WriteString("= @")
build.WriteString(key)
build.WriteString(" and ")
build.WriteString(dbinfo.EntityKeyName(entity))
build.WriteString(" != @")
build.WriteString(dbinfo.EntityKeyName(entity))
where[key] = data[key] // reflectutil.GetFieldValue(entity, "G"+key)
}
build.WriteString(") TMP")
txt := strings.Replace(build.String(), " union all ", " ", 1)
txt = strings.Replace(txt, "${sDbTableName}", entity.TableName(), -1)
txt = strings.Replace(txt, "${sTableName}", dbinfo.SimpleTableName(entity), -1)
iCount := 0
dbResult := gorm.Raw(txt, where).Find(&iCount)
if dbResult.Error != nil {
Log.Error("验证数据是否重复发生异常:", dbResult.Error)
return msgentity.Err(1003, "验证数据是否重复发生异常:", dbResult.Error)
}
if iCount != 0 {
var temp strings.Builder
str := fmt.Sprintf("%0*d", len(checkRepeatAlone), iCount)
array := []rune(str) //得到字符数组
ml := len(checkRepeatAlone)
for key, value := range checkRepeatAlone {
i := len(strconv.Itoa(value))
if array[ml-i] == 48 { // ASCII对应: '0' => 48, '1' => 49
continue
}
dataInfo := entity.GetDataInfo(key)
temp.WriteString("、'")
temp.WriteString(dataInfo.GsComment)
temp.WriteString("'")
}
temp.WriteString("存在重复")
return msgentity.Err(1004, strings.Replace(temp.String(), "、", "", 1))
}
k++
}
if k == 0 {
return msgentity.Success("没有设定验证函数,通过")
}
return msgentity.Success("经验证,通过")
}
/**
* 读取树形结构数据
* @param entity
* @param sGroupColumn
* @param sGroupName
* @return
*/
func (service ServiceBaseFunc) FindByTree(ctx ginutil.Context, entity dbinfo.Entity, sGroupColumn, sGroupName string) *msgentity.MsgEntity {
if !dbinfo.EntityHasPid(entity) {
return msgentity.Err(1001, "指定分组字段不存在!")
}
//-- 从文件读取 --//
var filePath string
if sGroupName == "" {
filePath = "./temp/cache/" + dbinfo.SimpleTableName(entity) + "/tree.txt"
} else {
filePath = "./temp/cache/" + dbinfo.SimpleTableName(entity) + "/Group_" + sGroupName + ".txt"
}
me := jsonutil.FormFile(filePath, map[string]interface{}{})
if me.Gsuccess {
return msgentity.Success(me.Gdata, "在文件中找到") //返回结果
}
//-- 从数据库读取 --//
var build strings.Builder
build.WriteString("SELECT * FROM ${sDbTableName} WHERE ")
build.WriteString(dbinfo.TableMajorKeyString)
build.WriteString(" > 0")
where := []interface{}{}
if sGroupName != "" {
build.WriteString(" AND ")
build.WriteString(dbinfo.TablePathKey)
build.WriteString(" LIKE (")
build.WriteString(" select CONCAT(a.")
build.WriteString(dbinfo.TablePathKey)
build.WriteString(", '%')")
build.WriteString(" from ${sDbTableName} a")
if sGroupColumn != "" {
build.WriteString(" where a.")
build.WriteString(sGroupColumn) //指定字段作为分组标识
build.WriteString(" = ?")
} else if dbinfo.EntityHasOnlyign(entity) { //启用唯一标识作为关键字
build.WriteString(" where a.")
build.WriteString(dbinfo.TableOnlyignName) //启用唯一标识作为关键字
build.WriteString(" = ?") //启用唯一标识作为关键字
} else {
build.WriteString(" where a.")
build.WriteString(dbinfo.TableTreeNodeName)
build.WriteString(" = ?")
}
build.WriteString(" )")
where = append(where, sGroupName)
}
build.WriteString(" ORDER BY ")
build.WriteString(dbinfo.TablePathKey)
txt := strings.Replace(build.String(), "${sDbTableName}", entity.TableName(), -1)
txt = strings.Replace(txt, "${sTableName}", dbinfo.SimpleTableName(entity), -1)
rows, err := gorm.Raw(txt, where).Rows()
if nil != err {
Log.Error("查询发生异常:", err)
return msgentity.Err(1002, "查询发生异常:", err)
}
defer rows.Close()
res := gorm.ScanRows2mapI(rows)
if res == nil {
return msgentity.Err(1003, "查询后数据转换发生异常")
}
if len(res) < 1 {
return msgentity.Err(1004, "数据为空")
}
sRootValue := dbinfo.TableTreeRootValue
if sGroupName != "" {
sRootValue = res[0][dbinfo.TableMajorKeyString].(string) //分组查询情况下必须要一个根节点(因为已经path排序)
}
me = service.CreateTree(res, sRootValue, dbinfo.TableMajorKeyString, dbinfo.TablePidKey, "childs")
if !me.Gsuccess {
return me
}
if len((me.Gdata).([]interface{})) < 1 {
return msgentity.Err(1005, "数据转换后构造树型数据为空")
}
jsonutil.ToFile(me.Gdata, filePath) //保存到文件
return msgentity.Success(me.Gdata, "查询成功")
}
/**
* List转树形结构
* @param source Map或切片结构
* @param rootName
* @param idFieldName
* @param pIdFieldName
* @param childFieldName
* @return
*/
func (service ServiceBaseFunc) CreateTree(source interface{},
rootName, idFieldName, pIdFieldName, childFieldName string) *msgentity.MsgEntity {
if nil == source {
return msgentity.Err(5001, "没有数据无法进行树结构创建!")
}
if strings.TrimSpace(idFieldName) == "" {
return msgentity.Err(5002, "对象字段中的编号属性名称必须提供!")
}
if strings.TrimSpace(pIdFieldName) == "" {
return msgentity.Err(5003, "对象字段中的上级编号属性名称必须提供!")
}
if strings.TrimSpace(childFieldName) == "" {
return msgentity.Err(5004, "对象字段中的子节点集合属性名称必须提供!")
}
sourceTypeName := reflect.TypeOf(source).String()
if strings.HasPrefix(sourceTypeName, "[]map[string]interface") {
return service.createTreeByMap(source.([]map[string]interface{}), rootName, idFieldName, pIdFieldName, childFieldName)
}
return service.createTreeByList(source.([]interface{}), rootName, idFieldName, pIdFieldName, childFieldName)
}
/**
* List转树形结构
* @param source 切片结构
* @param rootName
* @param idFieldName
* @param pIdFieldName
* @param childFieldName
* @return
*/
func (service ServiceBaseFunc) createTreeByList(source []interface{},
rootName, idFieldName, pIdFieldName, childFieldName string) *msgentity.MsgEntity {
if nil == source || (len(source) < 1) {
return msgentity.Err(5001, "没有数据无法进行树结构创建!")
}
result := []interface{}{}
rt := reflect.TypeOf(source[0])
sourceTypeName := rt.String()
isMap := strings.HasPrefix(sourceTypeName, "map[string]interface") //如果数据类型是Map则取值不能用反射方式
if strings.TrimSpace(rootName) == "" {
rootName = dbinfo.TableTreeRootValue //未指定就默认为'00'做根节点
}
//-- 将所有数据进行预分组存储,同时筛选出根节点 --//
groupMap := map[string][]interface{}{} //待进行挂接的子分组
allMap := map[string]interface{}{}
for _, object := range source {
sGroupName := ""
if !isMap {
sGroupName = reflectutil.GetFieldValue(object, pIdFieldName).(string)
} else {
sGroupName = (object.(map[string]interface{}))[pIdFieldName].(string)
}
if strings.TrimSpace(sGroupName) == "" {
sGroupName = rootName //如果父节点信息为空,则默认为根节点
}
sGroupName = strings.TrimSpace(sGroupName) //所在组名
sid := ""
if isMap {
sid = (object.(map[string]interface{}))[idFieldName].(string)
} else {
sid = (reflectutil.GetFieldValue(object, idFieldName)).(string)
}
allMap[sid] = object
if rootName == sGroupName {
result = append(result, object) //加入根节点列表
continue
}
childs, ok := groupMap[sGroupName]
if !ok {
childs = []interface{}{}
groupMap[sGroupName] = childs
}
childs = append(childs, object)
groupMap[sGroupName] = childs
}
//--将所有分组寻找父节点--//
for key, value := range groupMap {
obj := allMap[key]
if nil == obj {
continue
}
sTypeName := reflect.TypeOf(obj).String()
if strings.HasPrefix(sTypeName, "map[string]interface") {
(obj.(map[string]interface{}))[childFieldName] = value
continue
}
reflectutil.SetFieldValue(obj, childFieldName, value) // 设置子节点集合
}
return msgentity.Success(result, "构造成功!")
}
/**
* List转树形结构
* @param source Map结构
* @param rootName
* @param idFieldName
* @param pIdFieldName
* @param childFieldName
* @return
*/
func (service ServiceBaseFunc) createTreeByMap(source []map[string]interface{},
rootName, idFieldName, pIdFieldName, childFieldName string) *msgentity.MsgEntity {
if nil == source || (len(source) < 1) {
return msgentity.Err(5001, "没有数据无法进行树结构创建!")
}
result := []interface{}{}
rt := reflect.TypeOf(source[0])
sourceTypeName := rt.String()
isMap := strings.HasPrefix(sourceTypeName, "map[string]interface") //如果数据类型是Map则取值不能用反射方式
if strings.TrimSpace(rootName) == "" {
rootName = dbinfo.TableTreeRootValue //未指定就默认为'00'做根节点
}
//-- 将所有数据进行预分组存储,同时筛选出根节点 --//
groupMap := map[string][]interface{}{} //待进行挂接的子分组
allMap := map[string]interface{}{}
for _, object := range source {
sGroupName := ""
if !isMap {
sGroupName = reflectutil.GetFieldValue(object, pIdFieldName).(string)
} else {
sGroupName = object[pIdFieldName].(string)
}
if strings.TrimSpace(sGroupName) == "" {
sGroupName = rootName //如果父节点信息为空,则默认为根节点
}
sGroupName = strings.TrimSpace(sGroupName) //所在组名
sid := ""
if isMap {
sid = object[idFieldName].(string)
} else {
sid = (reflectutil.GetFieldValue(object, idFieldName)).(string)
}
allMap[sid] = object
if rootName == sGroupName {
result = append(result, object) //加入根节点列表
continue
}
childs, ok := groupMap[sGroupName]
if !ok {
childs = []interface{}{}
groupMap[sGroupName] = childs
}
childs = append(childs, object)
groupMap[sGroupName] = childs
}
//--将所有分组寻找父节点--//
for key, value := range groupMap {
obj := allMap[key]
if nil == obj {
continue
}
sTypeName := reflect.TypeOf(obj).String()
if strings.HasPrefix(sTypeName, "map[string]interface") {
(obj.(map[string]interface{}))[childFieldName] = value
continue
}
reflectutil.SetFieldValue(obj, childFieldName, value) // 设置子节点集合
}
return msgentity.Success(result, "构造成功!")
}
/**
* 根据字段名取指定记录编号的数据库表中对应字段的值
* @param entity 实体类
* @param id
* @param fieldNames 待取数据的字段名称集合
* @return msgentity.MsgEntity 返回内容data中存放的是Map
*/
func (service ServiceBaseFunc) GetValueByFieldName(ctx ginutil.Context, entity dbinfo.Entity, id interface{}, fieldNames []string) *msgentity.MsgEntity {
currentUser := ""
onlyCreator := !EnableTag(dbinfo.SimpleTableName(entity), 5)
if onlyCreator { //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
currentUser = CurrentLoginUserId(ctx.Request)
}
return CommonDao.GetValueByFieldName(entity, id, fieldNames, currentUser, onlyCreator)
}
/**
* 根据字段名取指定记录编号的数据库表中对应字段的值
* @param entity 实体类
* @param id
* @param fieldName 待取数据的字段名称集合
* @return msgentity.MsgEntity 返回内容data中存放的是Map
*/
func (service ServiceBaseFunc) GetValueByField(ctx ginutil.Context, entity dbinfo.Entity, id interface{}, fieldName string) *msgentity.MsgEntity {
currentUser := ""
onlyCreator := !EnableTag(dbinfo.SimpleTableName(entity), 5)
if onlyCreator { //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
currentUser = CurrentLoginUserId(ctx.Request)
}
return CommonDao.GetValueByField(entity, id, fieldName, currentUser, onlyCreator)
}
/**
* 根据字段名取指定记录编号的数据库表中对应字段的值
* @param entity 实体类
* @param whereInfo 条件
* @param fieldName 待取数据的字段名称集合
* @param currentUser 当前用户
* @return msgentity.MsgEntity 返回内容data中存放的是Map
*/
func (service ServiceBaseFunc) GetValueByWhere(ctx ginutil.Context, entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, fieldName string) *msgentity.MsgEntity {
currentUser := ""
onlyCreator := !EnableTag(dbinfo.SimpleTableName(entity), 5)
if onlyCreator { //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
currentUser = CurrentLoginUserId(ctx.Request)
}
return CommonDao.GetValueByWhere(entity, whereInfo, fieldName, currentUser, onlyCreator)
}
/**
* 取记录对应的版本号
* @param entity 实体类
* @param idName 编号
* @return
*/
func (service ServiceBaseFunc) GetiVersion(ctx ginutil.Context, entity dbinfo.Entity, id interface{}) *msgentity.MsgEntity {
if fmt.Sprintf("%v", id) == "" {
return msgentity.Err(8001, "记录编号参数为空!")
}
return CommonDao.GetiVersion(entity, id)
}
/**
* 取记录对应的状态值
* @param entity 实体类
* @param idName 编号
* @return
*/
func (service ServiceBaseFunc) GetiState(ctx ginutil.Context, entity dbinfo.Entity, id interface{}) *msgentity.MsgEntity {
if fmt.Sprintf("%v", id) == "" {
return msgentity.Err(8001, "记录编号参数为空!")
}
return CommonDao.GetiState(entity, id)
}
/**
* 根据关键值取对象集合
* @Param entity 实体类
* @Param where 存放查询条件
* @return msgentity.MsgEntity
*/
func (service ServiceBaseFunc) FindByKey(ctx ginutil.Context, entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo) *msgentity.MsgEntity {
whereInfo = service.holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件
if len(whereInfo) < 1 {
return msgentity.Err(8001, "没有对应的查询条件!")
}
onlyCreator := !EnableTag(dbinfo.SimpleTableName(entity), 5) //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
return CommonDao.FindByKey(entity, whereInfo, CurrentLoginUserId(ctx.Request), onlyCreator)
}
/**
* 根据关键值取对象集合中的第一个
* @Param entity 实体类
* @Param where 存放查询条件
* @param fields 指定要查询的字段集合
* @return msgentity.MsgEntity
*/
func (service ServiceBaseFunc) FindOneByKey(ctx ginutil.Context, entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, fields ...string) *msgentity.MsgEntity {
whereInfo = service.holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件
if len(whereInfo) < 1 {
return msgentity.Err(8001, "没有对应的查询条件!")
}
onlyCreator := !EnableTag(dbinfo.SimpleTableName(entity), 5) //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
return CommonDao.FindOneByKey(entity, whereInfo, CurrentLoginUserId(ctx.Request), onlyCreator, fields...)
}
/**
* 根据关键值取对象集合中的符合条件的第一条记录的指定字段
* @Param entity 实体类
* @Param where 存放查询条件
* @param fieldName 指定要查询的字段
* @return msgentity.MsgEntity
*/
func (service ServiceBaseFunc) FindValueByKey(ctx ginutil.Context, entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, fieldName string) *msgentity.MsgEntity {
whereInfo = service.holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件
if len(whereInfo) < 1 {
return msgentity.Err(8001, "没有对应的查询条件!")
}
fieldName = strings.TrimSpace(fieldName)
if fieldName == "" {
return msgentity.Err(8002, "没有待查字段!")
}
if !dbinfo.HasColumnName(entity, fieldName) {
return msgentity.Err(8003, "指定字段不存在!")
}
onlyCreator := !EnableTag(dbinfo.SimpleTableName(entity), 5) //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
return CommonDao.FindValueByKey(entity, whereInfo, fieldName, CurrentLoginUserId(ctx.Request), onlyCreator)
}
/**
* 根据指定字段进行分组查询
* @Param entity 实体类
* @Param where 存放查询条件
* @param fieldMap 指定要查询的字段集合(原字段, 别名)
* @return msgentity.MsgEntity
*/
func (service ServiceBaseFunc) FindByFields(ctx ginutil.Context, entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, fieldMap map[string]string) *msgentity.MsgEntity {
whereInfo = service.holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件
if len(whereInfo) < 1 {
return msgentity.Err(8001, "没有对应的查询条件!")
}
if nil == fieldMap || len(fieldMap) < 1 {
return msgentity.Err(8002, "没有待查字段!")
}
onlyCreator := !EnableTag(dbinfo.SimpleTableName(entity), 5) //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
return CommonDao.FindByFields(entity, whereInfo, fieldMap, CurrentLoginUserId(ctx.Request), onlyCreator)
}
/**
* 根据关键值查数量
* @Param entity 实体类
* @Param where 存放查询条件
* @return msgentity.MsgEntity
*/
func (service ServiceBaseFunc) FindCountByKey(ctx ginutil.Context, entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo) *msgentity.MsgEntity {
whereInfo = service.holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件
if len(whereInfo) < 1 {
return msgentity.Err(7001, "没有对应的查询条件!")
}
onlyCreator := !EnableTag(dbinfo.SimpleTableName(entity), 5) //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
return CommonDao.FindCountByKey(entity, whereInfo, CurrentLoginUserId(ctx.Request), onlyCreator)
}
// /**
// * 以事务方式执行Mapper下的多个方法
// * 注意:Mapper必须存在才能执行
// * @param mapper iBatis实体
// * @Param funcInfo 接口信息集合(以3对为一组) <函数名, 函数参数类型集合, 函数参数集合, 函数名, 函数参数类型集合, 函数参数集合....>
// * @return msgentity.MsgEntity 返回对象数组(各函数执行结果)
// */
// func (service ServiceBaseFunc) transactionMapping(Object mapper, Object...funcInfo) *msgentity.MsgEntity {
// return msgentity.Success(res, "查询成功")
// }
/**
* 根据字段名取分组数据
* @param entity 实体类
* @param sCreator 指定用户
* @param fields 字段名与别名对象
* @return
*/
func (service ServiceBaseFunc) GroupByField(ctx ginutil.Context, entity dbinfo.Entity, sCreator string, fields map[string]string) *msgentity.MsgEntity {
if len(fields) < 1 {
return msgentity.Err(8001, "没有对应的待查字段!")
}
onlyCreator := !EnableTag(dbinfo.SimpleTableName(entity), 5) //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
return CommonDao.GroupByField(entity, sCreator, fields, CurrentLoginUserId(ctx.Request), onlyCreator)
}
/**
* 根据字段名取分组数据及分组后数量
* @param entity 实体类
* @param sCreator 指定用户
* @param fields 字段名与别名对象
* @return
*/
func (service ServiceBaseFunc) GroupByFieldAndCount(ctx ginutil.Context, entity dbinfo.Entity, sCreator string, fields map[string]string) *msgentity.MsgEntity {
if len(fields) < 1 {
return msgentity.Err(8001, "没有对应的待查字段!")
}
onlyCreator := !EnableTag(dbinfo.SimpleTableName(entity), 5) //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
return CommonDao.GroupByFieldAndCount(entity, sCreator, fields, CurrentLoginUserId(ctx.Request), onlyCreator)
}
/**
* 取表中指定字段的最大值
* @param entity 实体类
* @param sCreator 指定用户
* @param field 字段名
* @param where 查询条件字符串
* @return msgentity.MsgEntity
*/
func (service ServiceBaseFunc) MaxByField(ctx ginutil.Context, entity dbinfo.Entity, sCreator string, field string, whereInfo []dbinfo.WhereInfo) *msgentity.MsgEntity {
field = strings.TrimSpace(field)
if field == "" {
return msgentity.Err(7001, "没有待查字段!")
}
if len(whereInfo) < 1 {
return msgentity.Err(7002, "没有对应的查询条件!")
}
if !dbinfo.HasColumnName(entity, field) {
return msgentity.Err(7003, "指定字段不存在!")
}
onlyCreator := !EnableTag(dbinfo.SimpleTableName(entity), 5) //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
return CommonDao.MaxByField(entity, sCreator, field, whereInfo, CurrentLoginUserId(ctx.Request), onlyCreator)
}
/**
* 取表中指定字段的最小值
* @param entity 实体类
* @param sCreator 指定用户
* @param field 字段名
* @param where 查询条件
* @return msgentity.MsgEntity
*/
func (service ServiceBaseFunc) MinByField(ctx ginutil.Context, entity dbinfo.Entity, sCreator string, field string, whereInfo []dbinfo.WhereInfo) *msgentity.MsgEntity {
field = strings.TrimSpace(field)
if field == "" {
return msgentity.Err(7001, "没有待查字段!")
}
if len(whereInfo) < 1 {
return msgentity.Err(7002, "没有对应的查询条件!")
}
if !dbinfo.HasColumnName(entity, field) {
return msgentity.Err(7003, "指定字段不存在!")
}
onlyCreator := EnableTag(dbinfo.SimpleTableName(entity), 5) //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
return CommonDao.MinByField(entity, sCreator, field, whereInfo, CurrentLoginUserId(ctx.Request), onlyCreator)
}
/**
* 检查关键值记录是否存在(返回1:存在;0:不存在)
* @param entity 实体类
* @Param id
* @return msgentity.MsgEntity
*/
func (service ServiceBaseFunc) HasById(ctx ginutil.Context, entity dbinfo.Entity, id interface{}) *msgentity.MsgEntity {
if fmt.Sprintf("%v", id) == "" {
return msgentity.Err(8001, "记录编号参数为空!")
}
return CommonDao.HasById(entity, id)
}
/**
* 检查关键值记录是否存在(返回1:存在;0:不存在)
* @param entity 实体类
* @Param keyName 字段名
* @Param keyValue 字段值
* @return msgentity.MsgEntity
*/
func (service ServiceBaseFunc) HasByKey(ctx ginutil.Context, entity dbinfo.Entity, keyName string, keyValue interface{}) *msgentity.MsgEntity {
keyName = strings.TrimSpace(keyName)
if keyName == "" {
return msgentity.Err(7001, "字段名参数为空!")
}
if (keyValue == nil) || (fmt.Sprintf("%v", keyValue) == "") || (fmt.Sprintf("%v", keyValue) == "<nil>") {
return msgentity.Err(7002, "字段值参数为空!")
}
if !dbinfo.HasColumnName(entity, keyName) {
return msgentity.Err(7003, "指定字段不存在!")
}
dataInfo := entity.GetDataInfo(keyName)
if dataInfo == nil {
return msgentity.Err(7004, "字段备注信息缺失")
}
switch dataInfo.GsDbFileType {
case "int":
temp, err := strconv.Atoi(keyValue.(string))
if err != nil {
return msgentity.Err(7005, "字段值参数为不符合规范!")
}
keyValue = temp
case "bigint":
temp, err := strconv.ParseInt(keyValue.(string), 10, 64)
if err != nil {
return msgentity.Err(7006, "字段值参数为不符合规范!")
}
keyValue = temp
}
return CommonDao.HasByKey(entity, keyName, keyValue)
}
/**
* 清理指定用户的缓存
* @param cacheName 缓存名
* @Param sUser 用户名
* @return msgentity.MsgEntity
*/
func (service ServiceBaseFunc) ClearCache(ctx ginutil.Context, cacheName, sUser string) *msgentity.MsgEntity {
cacheName = strings.TrimSpace(cacheName)
if cacheName == "" {
return msgentity.Err(7001, "指定'缓存库名称'参数为空!")
}
sUser = strings.TrimSpace(sUser)
if sUser == "" {
cacheName = cacheName + sUser
}
Log.Error("清理缓存库:" + cacheName)
// if globalvariable.Del(cacheName) {//这种方式不合适,需要换
// return msgentity.Success(7999, "清理成功!")
// }
return msgentity.Err(7002, "清理失败!")
}
/**
* 查询组结构数据
* @param r Http请求对象
* @param entity 实体类
* @param sGroupColumn 分组名(树节点)所在字段名
* @param sGroupName 分组名(树节点)
* @return
*/
func (service ServiceBaseFunc) FindByGroup(ctx ginutil.Context, entity dbinfo.Entity, sGroupColumn, sGroupName string) *msgentity.MsgEntity {
return service.FindByTree(ctx, entity, sGroupColumn, sGroupName)
}
/**
* 添加数据到指定组下
* 警告:对象必须符合树形结构要求,如:sId、sPid
* @param r Http请求对象
* @param sGroupName 分组字段名称(树节点)
* @param sGroupValue 分组字段值(树节点)
* @param entity 实体对象
* @return
*/
func (service ServiceBaseFunc) AddToGroup(ctx ginutil.Context, entity dbinfo.Entity, sGroupName, sGroupValue string) *msgentity.MsgEntity {
if sGroupName == "" {
return msgentity.Err(8001, "节点参数不能为空!")
}
if entity == nil {
return msgentity.Err(8002, "实体对象不能为空!")
}
if !dbinfo.EntityHasPid(entity) {
return msgentity.Err(8003, "指定分组字段不存在!")
}
if dbinfo.TableMajorKeyString != dbinfo.EntityKeyName(entity) {
return msgentity.Err(8004, "实体类型没有sId字段,不符合格式要求!")
}
if !dbinfo.EntityHasPid(entity) {
return msgentity.Err(8005, "实体类型没有sPid字段,不符合格式要求!")
}
//-- 查组所在记录编号 --//
var build strings.Builder
build.WriteString("SELECT ")
build.WriteString(dbinfo.TableMajorKeyString)
build.WriteString(" FROM ")
build.WriteString(entity.TableName())
build.WriteString(" WHERE ")
build.WriteString(sGroupName)
build.WriteString("=? LIMIT 0, 1")
sPId := ""
dbResult := gorm.Raw(build.String(), sGroupValue).Find(&sPId)
if dbResult.Error != nil {
Log.Error("查询发生异常:", dbResult.Error)
return msgentity.Err(8006, "查询发生异常:", dbResult.Error)
}
if sPId == "" {
return msgentity.Err(8007, "指定组不存在,不能用此方法添加!")
}
reflectutil.SetFieldValue(entity, dbinfo.TablePidKey, sPId) // 父编号就是查出来的数据
dbinfo.SetDefault(entity, false) //对对象中添加了dataInfo注解的属性添加默认值
me := service.SupplyDbEntityAttrByAdd(ctx, entity, "", "")
if !me.Gsuccess {
return me.IncCode(7030)
}
iCode, err := dbinfo.ValidAttrByAdd(entity, []string{}) //对对象中添加了dbinfo.DataInfo注解的属性检查限制
if err != nil {
return msgentity.Err(iCode+7020, err.Error())
}
me = service.ValidEntityRepeatByAdd(ctx, entity) //验证新增数据是否存在重复
if !me.Gsuccess {
return me.IncCode(7030)
}
return CommonDao.AddCommon(entity)
}
/**
* 执行SQL脚本获取单行单列数据
* 注意:库名必须用${}进行包装,此脚本应只存在一条记录且为单列
* @param sql 待执行的SQL脚本
* @return msgentity.MsgEntity
*/
func (service ServiceBaseFunc) DoSql(sql string) *msgentity.MsgEntity {
return CommonDao.DoSql(sql)
}
/**
* 执行SQL脚本获取单行单列数据
* 注意:库名必须用${}进行包装,此脚本应只存在一条记录且为单列
* @param sql 待执行的SQL脚本
* @return msgentity.MsgEntity
*/
func (service ServiceBaseFunc) ExecSql(sql string) *msgentity.MsgEntity {
return CommonDao.ExecSql(sql)
}
/**
* 执行SQL脚本获取单行单列数据
* 注意:库名必须用${}进行包装,此脚本应只存在一条记录且为单列
* @param sql 待执行的SQL脚本
* @return msgentity.MsgEntity
*/
func (service ServiceBaseFunc) GetValue(sql string) *msgentity.MsgEntity {
return CommonDao.GetValue(sql)
}
/**
* 执行SQL脚本获取一行数据(多列)
* 注意:库名必须用${}进行包装,此脚本应只存在一条记录
* @param sql 待执行的SQL脚本
* @return msgentity.MsgEntity
*/
func (service ServiceBaseFunc) GetRow(sql string) *msgentity.MsgEntity {
return CommonDao.GetRow(sql)
}
/**
* 执行SQL脚本获取多行数据(多列)
* 注意:库名必须用${}进行包装,此脚本可返回多条记录
* @param sql SQL脚本
* @return msgentity.MsgEntity
*/
func (service ServiceBaseFunc) GetRows(sql string) *msgentity.MsgEntity {
return CommonDao.GetRows(sql)
}
/**
* 根据关键值翻转值(限布尔值类型,1转2,2转1)
* 警告:此方法只支持布尔值类型,且只支持翻转1和2
* @Param ctx http请求对象
* @Param entity 实体类
* @Param whereInfo 存放查询条件
* @Param reversalColumn 翻转的字段名
* @return msgentity.MsgEntity
*/
func (service ServiceBaseFunc) ReversalByKey(ctx ginutil.Context, entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, reversalColumn string) *msgentity.MsgEntity {
currentUser := CurrentLoginUserId(ctx.Request)
onlyCreator := !EnableTag(dbinfo.SimpleTableName(entity), 6) //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
return CommonDao.ReversalByKey(entity, whereInfo, reversalColumn, currentUser, onlyCreator)
}
/**
* 根据条件仅查询指定字段名数据
* @param entity 实体类
* @param whereInfo
* @param fieldNames 待取数据的字段名称集合
* @return msgentity.MsgEntity 返回内容data中存放的是Map
*/
func (service ServiceBaseFunc) FindField(ctx ginutil.Context, entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, fieldNames []string) *msgentity.MsgEntity {
currentUser := ""
onlyCreator := !EnableTag(dbinfo.SimpleTableName(entity), 5) //7个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆、物理删除
if onlyCreator {
currentUser = CurrentLoginUserId(ctx.Request)
}
return CommonDao.FindField(entity, whereInfo, fieldNames, currentUser, onlyCreator)
}
/**
* 上传文件
* @param ctx http请求对象
* @param modelName 模块名称
* @return msgentity.MsgEntity
*/
func (service ServiceBaseFunc) UpFile(ctx ginutil.Context, modelName string) *msgentity.MsgEntity {
if upFilePath == "" {
upFilePath = ReadConfigKey("App", "UpFilePath", "./data/app/").(string)
if !strings.HasSuffix(upFilePath, "/") {
upFilePath = upFilePath + "/"
}
}
// 指定上传目录
targetDir := upFilePath + modelName
// 确保目录存在
if err := os.MkdirAll(targetDir, 0755); err != nil {
return msgentity.Err(8001, "无法创建目录!")
}
// 单个文件上传示例
file, err := ctx.FormFile("file")
if err != nil {
return msgentity.Err(8002, "'file'参数缺失!")
}
// 读取文件
src, err := file.Open()
if err != nil {
return msgentity.Err(8003, "无法打开上传的文件!")
}
defer src.Close()
sFilename := uuidutil.Get()
// 保存文件到指定目录
dst, err := os.Create(filepath.Join(targetDir, sFilename))
if err != nil {
return msgentity.Err(8004, "无法保存文件!")
}
defer dst.Close()
_, err = dst.ReadFrom(src)
if err != nil {
return msgentity.Err(8005, "保存文件内容失败!")
}
return msgentity.Success(sFilename, "上传成功!")
}
/**
* 获取图片
* @param ctx http请求对象
* @param modelName 模块名称
* @param filename 文件名
*/
func (service ServiceBaseFunc) LookImg(ctx ginutil.Context, modelName, filename string) {
if (filename == "") || (filename == "null") {
modelName = "imgs"
filename = "空图片.png"
}
if upFilePath == "" {
upFilePath = ReadConfigKey("App", "UpFilePath", "./data/app/").(string)
if !strings.HasSuffix(upFilePath, "/") {
upFilePath = upFilePath + "/"
}
}
filePath := upFilePath + modelName + "/" + filename // 假设文件存储在 ./texts 目录下
// 读取图片文件
content, err := os.ReadFile(filePath)
if err != nil {
ctx.AbortWithStatus(http.StatusInternalServerError)
return
}
// 获取文件的MIME类型
mimeType := http.DetectContentType(content[:512])
// 使用 c.Data() 发送图片二进制数据
ctx.Data(http.StatusOK, mimeType, content)
}
/**
* 按实体保留切片中的数据
* object 待检查对象
* whereInfo 数据
*/
func (ServiceBaseFunc) holdByEntityToWhereInfo(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo) []dbinfo.WhereInfo {
columns := "," + entity.BaseColumnNames() + ","
result := []dbinfo.WhereInfo{}
for _, val := range whereInfo {
if !strings.Contains(columns, ","+val.Name+",") {
continue
}
result = append(result, val)
}
return result
}
// /**
// * 按实体保留切片中的数据
// * object 待检查对象
// * data 数据
// * fieldPrefix 字段前缀(可不传)
// */
// func (ServiceBaseFunc) holdByEntityToArray(entity dbinfo.Entity, data []string) []string {
// columns := "," + entity.BaseColumnNames() + ","
// result := []string{}
// for _, val := range data {
// if !strings.Contains(columns, ","+val+",") {
// continue
// }
// result = append(result, val)
// }
// return result
// }
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。