作者 唐旭辉

更新部门职位管理

... ... @@ -11,7 +11,7 @@ AdminPort = 8088
#---自定义配置 开始----
##数据库连接
# sqlconn ="${MYSQL_CONN||root:root@tcp(127.0.0.1:3306)/opportunity_dev?charset=utf8}"
sqlconn ="${MYSQL_CONN||root:sutianxia2015@tcp(115.29.205.99:3306)/opportunity?charset=utf8}"
sqlconn ="${MYSQL_CONN||root:sutianxia2015@tcp(115.29.205.99:3306)/opportunity?charset=utf8&loc=Asia%2FShanghai}"
##redis相关配置
redis_add_port = "127.0.0.1:6379"
redis_auth = ""
... ...
... ... @@ -10,7 +10,7 @@ AdminPort = 8088
#---自定义配置 开始----
#数据库连接
sqlconn = "root:root@tcp(127.0.0.1:3306)/ability_display?charset=utf8"
sqlconn = "root:root@tcp(127.0.0.1:3306)/ability_display?charset=utf8&loc=Asia%2FShanghai"
#redis相关配置
redis_add_port = "127.0.0.1:6379"
redis_auth = ""
... ...
... ... @@ -8,7 +8,7 @@ httpport = 8080
#---自定义配置 开始----
#数据库连接
sqlconn = "${MYSQL_CONN||root:sutianxia2015@tcp(115.29.205.99:3306)/opportunity?charset=utf8}"
sqlconn = "${MYSQL_CONN||root:sutianxia2015@tcp(115.29.205.99:3306)/opportunity?charset=utf8&loc=Asia%2FShanghai}"
#redis相关配置
redis_add_port = "127.0.0.1:6379"
redis_auth = ""
... ...
package controllers
import (
"encoding/json"
"oppmg/common/log"
"oppmg/protocol"
servecompany "oppmg/services/company"
)
type CompanyController struct {
BaseController
}
//URLMapping 实现ControllerInterface中的URLMapping
func (c *CompanyController) URLMapping() {
//c.Mapping("AccessToken", c.AccessToken)
}
// DepartmentAdd 添加部门
// @router /department [post]
func (c *CompanyController) DepartmentAdd() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
var param protocol.RequestDepartmentAdd
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
log.Error("json 解析失败 err:%s", err)
msg = protocol.BadRequestParam("1")
return
}
if param.CompanyID <= 0 {
log.Error("param.CompanyID <= 0")
msg = protocol.BadRequestParam("1")
return
}
//err := protocol.NewErrWithMessage("101", nil)
err := servecompany.DepartmentAdd(param)
msg = protocol.NewReturnResponse(nil, err)
return
}
// DepartmentUpdate 更新部门
// @router /department [put]
func (c *CompanyController) DepartmentUpdate() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
var param protocol.RequestDepartmentEdit
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
log.Error("json 解析失败 err:%s", err)
msg = protocol.BadRequestParam("1")
return
}
if param.ID <= 0 {
log.Error(" param.ID <= 0 ")
msg = protocol.BadRequestParam("1")
return
}
err := servecompany.DepartmentEdit(param)
msg = protocol.NewReturnResponse(nil, err)
return
}
// DepartmentUpdate 删除部门
// @router /department [delete]
func (c *CompanyController) DepartmentDelete() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
var param protocol.RequestDepartmentDelete
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
log.Error("json 解析失败 err:%s", err)
msg = protocol.BadRequestParam("1")
return
}
if param.ID <= 0 {
log.Error(" param.ID <= 0 ")
msg = protocol.BadRequestParam("1")
return
}
err := servecompany.DepartmentDelete(param)
msg = protocol.NewReturnResponse(nil, err)
return
}
... ...
... ... @@ -16,6 +16,7 @@ func main() {
common.ResetCommonConfig()
log.Debug("加载配置%s", config.MConfig.ConfigName)
orm.RegisterDataBase("default", "mysql", config.MConfig.SqlConn)
// orm.Debug = true
if beego.BConfig.RunMode == "dev" {
beego.BConfig.WebConfig.DirectoryIndex = true
beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
... ...
... ... @@ -40,9 +40,10 @@ func (t *Department) GetManagesIds() []int64 {
return r
}
func (t *Department) ParseManagesIds(v []int64) string {
func (t *Department) SetManages(v []int64) {
bt, _ := json.Marshal(v)
return string(bt)
t.Manages = string(bt)
return
}
func (t *Department) SetRelation(parent *Department) error {
... ... @@ -59,8 +60,14 @@ func (t *Department) SetRelation(parent *Department) error {
// AddDepartment insert a new Department into database and returns
// last inserted Id on success.
func AddDepartment(m *Department) (id int64, err error) {
o := orm.NewOrm()
func AddDepartment(m *Department, om ...orm.Ormer) (id int64, err error) {
var o orm.Ormer
if len(om) > 0 {
o = om[0]
} else {
o = orm.NewOrm()
}
m.DeleteAt = time.Unix(0, 0)
id, err = o.Insert(m)
return
}
... ... @@ -89,6 +96,7 @@ func UpdateDepartmentById(m *Department, col []string, om ...orm.Ormer) (err err
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
m.UpdateAt = time.Now()
if num, err = o.Update(m, col...); err == nil {
fmt.Println("Number of records updated in database:", num)
}
... ... @@ -96,21 +104,6 @@ func UpdateDepartmentById(m *Department, col []string, om ...orm.Ormer) (err err
return
}
// DeleteDepartment deletes Department by Id and returns error if
// the record to be deleted doesn't exist
func DeleteDepartment(id int64) (err error) {
o := orm.NewOrm()
v := Department{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&Department{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
func GetDepartmentSubsetByRelation(relation string, om ...orm.Ormer) ([]Department, error) {
dataSql := `SELECT company_id,parent_id,name,create_at,relation,member,managers
FROM department
... ... @@ -132,3 +125,15 @@ func GetDepartmentSubsetByRelation(relation string, om ...orm.Ormer) ([]Departme
}
return result, nil
}
func GetDepartmentByCompanyId(companyId int64) ([]Department, error) {
var (
result []Department
err error
)
o := orm.NewOrm()
_, err = o.QueryTable(&Department{}).
Filter("company_id", companyId).
All(&result)
return result, err
}
... ...
package models
import (
"errors"
"fmt"
"time"
"github.com/astaxie/beego/orm"
)
type Position struct {
Id int64 `orm:"column(id);auto" description:"职位表id"`
CompanyId int64 `orm:"column(company_id)" description:"表company.id 公司编号"`
Name string `orm:"column(name);size(100)" description:"职位名称"`
ParentId int64 `orm:"column(parent_id)" description:"父级id"`
Relation string `orm:"column(relation);size(1000)" description:"父子级关系树"`
CreateAt time.Time `orm:"column(create_at);type(timestamp)" description:"创建时间"`
UpdateAt time.Time `orm:"column(update_at);type(timestamp)" description:"更新时间"`
EnableStatus string `orm:"column(enable_status);size(255)" description:"有效状态 1:有效 0:无效"`
}
func (t *Position) TableName() string {
return "position"
}
func init() {
orm.RegisterModel(new(Position))
}
func (t *Position) SetRelation(parent *Position) error {
if t.Id == 0 {
return errors.New("Id==0")
}
if parent == nil {
t.Relation = fmt.Sprintf("%d", t.Id)
} else {
t.Relation = fmt.Sprintf("%s/%d", parent.Relation, t.Id)
}
return nil
}
func (t *Position) ValidatePid() error {
roledata, err := GetPositionById(t.ParentId)
if err != nil {
return err
}
if roledata.CompanyId != t.CompanyId {
return errors.New("validate companyId err")
}
return nil
}
// AddPosition insert a new Position into database and returns
// last inserted Id on success.
func AddPosition(m *Position, om ...orm.Ormer) (id int64, err error) {
var o orm.Ormer
if len(om) > 0 {
o = om[0]
} else {
o = orm.NewOrm()
}
m.CreateAt = time.Now()
m.UpdateAt = time.Now()
id, err = o.Insert(m)
return
}
// GetPositionById retrieves Position by Id. Returns error if
// Id doesn't exist
func GetPositionById(id int64) (v *Position, err error) {
o := orm.NewOrm()
v = &Position{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// UpdatePositionById updates Department by Id and returns error if
// the record to be updated doesn't exist
func UpdatePositionById(m *Position, col []string, om ...orm.Ormer) (err error) {
var o orm.Ormer
if len(om) > 0 {
o = om[0]
} else {
o = orm.NewOrm()
}
v := Position{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
m.UpdateAt = time.Now()
if num, err = o.Update(m, col...); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
... ...
... ... @@ -33,7 +33,7 @@ const (
)
func (t *Role) ValidateTypes() bool {
switch i {
switch t.Types {
case ROLETYPES_GROUP:
return true
case ROLETYPES_ROLE:
... ...
... ... @@ -4,8 +4,8 @@ package protocol
type RequestDepartmentAdd struct {
CompanyID int64 `json:"company_id"` //公司
Name string `json:"name"` //部门名字
ParantID int64 `json:"parant_id"` //父级部门Id
Managers []int64 `json:"admin_id"` //主管userid
ParentID int64 `json:"parent_id"` //父级部门Id
Managers []int64 `json:"manages"` //主管userid
}
//ResponseDepartmentInfo ...
... ... @@ -40,3 +40,16 @@ type RequestDepartmentDelete struct {
type ResponseDepartmentList struct {
List []ResponseDepartmentInfo
}
//RequestPositionAdd 添加职位
type RequestPositionAdd struct {
CompanyID int64 `json:"company_id"`
Name string `json:"name"`
ParentID int64 `json:"parent_id"`
}
//RequestPositionEdit 编辑职位
type RequestPositionEdit struct {
ID int `json:"id"`
RequestPositionAdd
}
... ...
... ... @@ -88,14 +88,14 @@ func (e ErrWithMessage) ParseToMessage() *ResponseMessage {
func SearchErr(code string) ErrorCode {
return errmessge.Search(code)
}
func NewReturnResponse(data interface{}, eRR error) *ResponseMessage {
var msg *ResponseMessage
func NewReturnResponse(data interface{}, eRR error) (msg *ResponseMessage) {
// var msg *ResponseMessage
if eRR == nil {
msg = NewMesage("0")
msg = NewMesage("00000")
msg.Data = data
return msg
}
// fmt.Println("日志:" + eRR.Error())
if x, ok := eRR.(CustomErrParse); ok {
return x.ParseToMessage()
}
... ...
... ... @@ -10,7 +10,12 @@ import (
func init() {
nsV1 := beego.NewNamespace("v1",
beego.NSBefore(middleware.AuthToken),
beego.NSBefore(middleware.LogRequestData, middleware.AuthToken),
beego.NSNamespace("/company",
beego.NSRouter("/department", &controllers.CompanyController{}, "post:DepartmentAdd"),
beego.NSRouter("/department", &controllers.CompanyController{}, "put:DepartmentUpdate"),
beego.NSRouter("/department", &controllers.CompanyController{}, "delete:DepartmentDelete"),
),
)
nsAuth := beego.NewNamespace("/auth",
... ...
... ... @@ -17,10 +17,10 @@ func DepartmentAdd(param protocol.RequestDepartmentAdd) error {
parentDepart *models.Department
err error
)
if param.ParantID > 0 {
parentDepart, err = models.GetDepartmentById(param.ParantID)
if param.ParentID > 0 {
parentDepart, err = models.GetDepartmentById(param.ParentID)
if err != nil {
e := fmt.Errorf("GetDepartmentById(%d) err:%s", param.ParantID, err)
e := fmt.Errorf("GetDepartmentById(%d) err:%s", param.ParentID, err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
... ... @@ -42,16 +42,35 @@ func DepartmentAdd(param protocol.RequestDepartmentAdd) error {
CompanyId: param.CompanyID,
Name: param.Name,
CreateAt: time.Now(),
ParentId: param.ParantID,
UpdateAt: time.Now(),
ParentId: param.ParentID,
Member: 0,
}
departmentAdd.SetRelation(parentDepart)
_, err = models.AddDepartment(departmentAdd)
departmentAdd.SetManages(param.Managers)
o := orm.NewOrm()
o.Begin()
_, err = models.AddDepartment(departmentAdd, o)
if err != nil {
o.Rollback()
e := fmt.Errorf("AddDepartment err:%s", err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
err = departmentAdd.SetRelation(parentDepart)
if err != nil {
o.Rollback()
e := fmt.Errorf("SetRelation err:%s", err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
err = models.UpdateDepartmentById(departmentAdd, []string{"Relation"}, o)
if err != nil {
o.Rollback()
e := fmt.Errorf("UpdateDepartmentById err:%s", err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
o.Commit()
return nil
}
... ... @@ -87,27 +106,27 @@ func DepartmentEdit(param protocol.RequestDepartmentEdit) error {
return protocol.NewErrWithMessage("1", e)
}
}
departUpdate.SetManages(param.Managers)
departUpdate.Name = param.Name
departUpdate.UpdateAt = time.Now()
err = models.UpdateDepartmentById(departUpdate, []string{"Manages", "Name", "UpdateAt"})
if err != nil {
e := fmt.Errorf("UpdateDepartmentById err:%s", err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
//处理部门上级发生变化的情况
var (
newparent *models.Department
)
if departUpdate.ParentId != param.ParantID {
newparent, err = models.GetDepartmentById(param.ParantID)
if departUpdate.ParentId != param.ParentID {
newparent, err = models.GetDepartmentById(param.ParentID)
if err != nil {
e := fmt.Errorf("GetDepartmentById(%d) err:%s", param.ParantID, err)
e := fmt.Errorf("GetDepartmentById(%d) err:%s", param.ParentID, err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
}
departUpdate.Manages = departUpdate.ParseManagesIds(param.Managers)
departUpdate.Name = param.Name
departUpdate.UpdateAt = time.Now()
err = models.UpdateDepartmentById(departUpdate, []string{"Manages", "Name", "UpdateAt"})
if err != nil {
e := fmt.Errorf("UpdateDepartmentById err:%s", err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
//更新部门关系数据
err = departmentRelationUpdate(departUpdate, newparent)
if err != nil {
... ... @@ -119,32 +138,44 @@ func DepartmentEdit(param protocol.RequestDepartmentEdit) error {
}
//DepartmentParentChange 处理部门上级发生变化的情况
func departmentRelationUpdate(old *models.Department, newparent *models.Department) error {
func departmentRelationUpdate(departUpdate *models.Department, newparent *models.Department) error {
if newparent == nil {
return nil
}
const (
//获取某个部门的下级部门 select ... for update
dataSql0 string = `SELECT id,relation FROM department WHERE relation LIKE ? AND delete_at = 0 FOR UPDATE`
//更新关系树
dataSql2 string = `update department set relation=? where id=?`
//更新departUpdate的parent_id
dataSql3 string = `update department set parent_id=? where id =?`
)
var (
departSubset []models.Department //子级部门
err error
oldrelation string = old.Relation
relationLike string = oldrelation + "%"
newRelation string = fmt.Sprintf("%s/%d", newparent.Relation, old.Id)
oldRelation string = departUpdate.Relation
relationLike string = oldRelation + "%"
newRelation string = fmt.Sprintf("%s/%d", newparent.Relation, departUpdate.Id)
)
o := orm.NewOrm()
o.Begin()
err = utils.ExcuteQueryAllWithOrmer(o, &departSubset, dataSql0, relationLike)
//修改部门的parent_id
err = utils.ExecuteSQLWithOrmer(o, dataSql3, newparent.Id, departUpdate.Id)
if err != nil {
o.Rollback()
e := fmt.Errorf("EXECUTE SQL err:%s", err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
//获取部门及子级部门的relation和id
err = utils.ExecuteQueryAllWithOrmer(o, &departSubset, dataSql0, relationLike)
if err != nil {
o.Rollback()
e := fmt.Errorf("EXECUTE SQL err:%s", err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
//修改部门及子级部门的relation
for i := range departSubset {
if departSubset[i].Id == newparent.Id {
//确认新的父级id是否合法
... ... @@ -154,9 +185,9 @@ func departmentRelationUpdate(old *models.Department, newparent *models.Departme
return protocol.NewErrWithMessage("1", e)
}
//重建关系树
s := strings.TrimPrefix(departSubset[i].Relation, oldrelation)
s := strings.TrimPrefix(departSubset[i].Relation, oldRelation)
departSubset[i].Relation = strings.TrimSpace(fmt.Sprintf("%s%s", newRelation, s))
err := utils.ExcuteSQLWithOrmer(o, dataSql2, departSubset[i].Relation, departSubset[i].Id)
err = utils.ExecuteSQLWithOrmer(o, dataSql2, departSubset[i].Relation, departSubset[i].Id)
if err != nil {
o.Rollback()
e := fmt.Errorf("EXECUTE SQL err:%s", err)
... ... @@ -164,15 +195,68 @@ func departmentRelationUpdate(old *models.Department, newparent *models.Departme
return protocol.NewErrWithMessage("1", e)
}
}
o.Commit()
return nil
}
func DepartmentDelete(parm protocol.RequestDepartmentDelete) error {
//DepartmentDelete 部门删除,删除整个分枝
func DepartmentDelete(param protocol.RequestDepartmentDelete) error {
var (
departDelete *models.Department
err error
)
departDelete, err = models.GetDepartmentById(param.ID)
if err != nil {
e := fmt.Errorf("GetDepartmentById err:%s", err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
if departDelete.CompanyId != param.CompanyID {
e := fmt.Errorf("departDelete.CompanyId != param.CompanyID")
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
const (
//获取部门子集 锁数据 select ... for update,
dataSql0 string = `SELECT id,relation,member FROM department WHERE relation LIKE ? AND delete_at = 0 FOR UPDATE`
dataSql2 string = `update department set delete_at=? where relation LIKE ?`
)
var (
departSubset []models.Department
relationLike string = departDelete.Relation + "%"
nowTime string = time.Now().String()
)
o := orm.NewOrm()
o.Begin()
err = utils.ExecuteQueryAllWithOrmer(o, &departSubset, dataSql0, relationLike)
if err != nil {
o.Rollback()
e := fmt.Errorf("")
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
for _, v := range departSubset {
if v.Member > 0 {
o.Rollback()
e := fmt.Errorf("Member > 0 ")
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
}
err = utils.ExecuteSQLWithOrmer(o, dataSql2, nowTime, relationLike)
if err != nil {
o.Rollback()
e := fmt.Errorf("EXECUTE SQL err:%s", err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
o.Commit()
return nil
}
func DepartmentListAll() (protocol.ResponseDepartmentList, error) {
func DepartmentListAll(companyId int64) (protocol.ResponseDepartmentList, error) {
r := protocol.ResponseDepartmentList{}
return r, nil
}
... ...
package company
import (
"fmt"
"oppmg/common/log"
"oppmg/models"
"oppmg/protocol"
"time"
"github.com/astaxie/beego/orm"
)
//PositionAdd 添加职位
func PositionAdd(param protocol.RequestDepartmentAdd) error {
var (
parentPosition *models.Position
err error
)
if param.ParentID > 0 {
parentPosition, err = models.GetPositionById(param.ParentID)
if err != nil {
e := fmt.Errorf("GetDepartmentById(%d) err:%s", param.ParentID, err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
if parentPosition.CompanyId != param.CompanyID {
e := fmt.Errorf("parentDepart.CompanyId != param.CompanyID")
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
}
positionAdd := &models.Position{
CompanyId: param.CompanyID,
Name: param.Name,
CreateAt: time.Now(),
UpdateAt: time.Now(),
ParentId: param.ParentID,
}
o := orm.NewOrm()
o.Begin()
_, err = models.AddPosition(positionAdd, o)
if err != nil {
o.Rollback()
e := fmt.Errorf("AddPosition err:%s", err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
err = positionAdd.SetRelation(parentPosition)
if err != nil {
o.Rollback()
e := fmt.Errorf("SetRelation err:%s", err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
err = models.UpdatePositionById(positionAdd, []string{"Relation"}, o)
if err != nil {
o.Rollback()
e := fmt.Errorf("UpdatePositionById err:%s", err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
o.Commit()
return nil
}
... ...
... ... @@ -128,6 +128,10 @@ func RoleGetByPage(param protocol.RequestRoleList) (*protocol.ResponseRoleList,
return r, nil
}
func GetRoleGroup() error {
}
func RoleHasPermission() error {
return nil
}
... ...
... ... @@ -4,59 +4,65 @@ import (
"fmt"
"oppmg/common/log"
"oppmg/protocol"
"strings"
"github.com/astaxie/beego/orm"
)
//PrintLogSql 打印sql语句
func PrintLogSql(sql string, param ...interface{}) {
format := `SQL EXCUTE:[%s]-%s`
log.Debug(format, sql, fmt.Sprint(param...))
format := `SQL EXCEUTE:[%s]-%s`
parmformat := `[%v]`
var p strings.Builder
for i := range param {
p.WriteString(fmt.Sprintf(parmformat, param[i]))
}
log.Debug(format, sql, p.String())
}
//ExcuteQueryOne 执行原生sql查询单条记录;结果用结构体接收
func ExcuteQueryOne(result interface{}, sqlstr string, param ...interface{}) error {
//ExecuteQueryOne 执行原生sql查询单条记录;结果用结构体接收
func ExecuteQueryOne(result interface{}, sqlstr string, param ...interface{}) error {
PrintLogSql(sqlstr, param...)
var err error
o := orm.NewOrm()
err = ExcuteQueryOneWithOrmer(o, result, sqlstr, param)
err = ExecuteQueryOneWithOrmer(o, result, sqlstr, param)
return err
}
//ExcuteQueryOneWithOrmer 执行原生sql查询单条
func ExcuteQueryOneWithOrmer(o orm.Ormer, result interface{}, sqlstr string, param ...interface{}) error {
//ExecuteQueryOneWithOrmer 执行原生sql查询单条
func ExecuteQueryOneWithOrmer(o orm.Ormer, result interface{}, sqlstr string, param ...interface{}) error {
PrintLogSql(sqlstr, param...)
var err error
err = o.Raw(sqlstr, param).QueryRow(result)
if err != nil {
return fmt.Errorf("SQL EXCUTE err:%s", err)
return fmt.Errorf("SQL Execute err:%s", err)
}
return nil
}
//ExcuteQuerySql 执行原生sql查询多条记录
func ExcuteQueryAll(result interface{}, sqlstr string, param ...interface{}) error {
//ExecuteQuerySql 执行原生sql查询多条记录
func ExecuteQueryAll(result interface{}, sqlstr string, param ...interface{}) error {
PrintLogSql(sqlstr, param...)
var err error
o := orm.NewOrm()
err = ExcuteQueryOneWithOrmer(o, result, sqlstr, param)
err = ExecuteQueryOneWithOrmer(o, result, sqlstr, param)
return err
}
//ExcuteQueryOneWithOrmer 执行原生sql查询多条记录
func ExcuteQueryAllWithOrmer(o orm.Ormer, result interface{}, sqlstr string, param ...interface{}) error {
//ExecuteQueryOneWithOrmer 执行原生sql查询多条记录
func ExecuteQueryAllWithOrmer(o orm.Ormer, result interface{}, sqlstr string, param ...interface{}) error {
PrintLogSql(sqlstr, param...)
var (
err error
)
_, err = o.Raw(sqlstr, param).QueryRows(result)
if err != nil {
return fmt.Errorf("SQL EXCUTE err:%s", err)
return fmt.Errorf("SQL Execute err:%s", err)
}
return nil
}
func ExcuteSQLWithOrmer(o orm.Ormer, sqlstr string, param ...interface{}) error {
func ExecuteSQLWithOrmer(o orm.Ormer, sqlstr string, param ...interface{}) error {
PrintLogSql(sqlstr, param...)
var (
err error
... ... @@ -105,7 +111,7 @@ func (q *QueryDataByPage) Query(result interface{}) (pageinfo protocol.ResponseP
total int
)
o := orm.NewOrm()
err = ExcuteQueryOneWithOrmer(o, &total, q.CountSql, q.Param...)
err = ExecuteQueryOneWithOrmer(o, &total, q.CountSql, q.Param...)
if err != nil {
return
}
... ... @@ -113,7 +119,7 @@ func (q *QueryDataByPage) Query(result interface{}) (pageinfo protocol.ResponseP
return protocol.ResponsePageInfo{CurrentPage: q.offset, TotalPage: total}, nil
}
q.DataSql = fmt.Sprintf("%s limit %d,%d", q.DataSql, pagebegin, q.num)
err = ExcuteQueryAllWithOrmer(o, result, q.DataSql, q.Param...)
err = ExecuteQueryAllWithOrmer(o, result, q.DataSql, q.Param...)
if err != nil {
return
}
... ...