1 Star 0 Fork 0

tomatomeatman/GolangRepository

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
Service.go 90.78 KB
一键复制 编辑 原始数据 按行查看 历史
tomatomeatman 提交于 2025-01-07 22:53 +08:00 . 3
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671
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
// }
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/tomatomeatman/golang-repository.git
git@gitee.com:tomatomeatman/golang-repository.git
tomatomeatman
golang-repository
GolangRepository
61e401b0d628

搜索帮助