作者 yangfu

机会初始化

要显示太多修改。

为保证性能只显示 46 of 46+ 个文件。

# Binaries for programs and plugins
*.exe
*.dll
*.so
*.dylib
*.vscode
# Test binary, build with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
*.log
*debug
*wasm
*.idea
*.tmp
*.sum
opp
/vendor
... ...
FROM golang:1.13 as builder
ENV GOPROXY https://goproxy.cn
ENV GO111MODULE on
RUN git clone http://gitlab.fjmaimaimai.com/mmm-go/gocomm.git /app/gocomm
WORKDIR /app/ability
COPY go.mod .
COPY go.sum .
RUN go mod download
COPY . .
RUN GOOS=linux CGO_ENABLED=0 go build -ldflags="-s -w" -installsuffix cgo -o ability main.go
#FROM scratch
FROM alpine:latest
RUN apk add --no-cache tzdata \
&& ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
&& echo "Asia/Shanghai" > /etc/timezone \
&& rm -rf /var/cache/apk/* /tmp/* /var/tmp/* $HOME/.cache ## 清除缓存
WORKDIR /root/
COPY --from=builder /app/ability .
#RUN ls -l
EXPOSE 8080
CMD ["./ability"]
\ No newline at end of file
... ...
## 目录
- [项目说明](#项目说明)
- [代码声明](#代码声明)
- [命名规范](#命名规范)
- [项目约定](#项目约定)
- [注意事项](#注意事项)
### 项目说明
opp (opportunity) : 机会app服务端项目; 企业员工可以主动的把机会展示出来,另外有员工能把展示的机会抓 住、变现,从而形成自主的供需循环。使企业的运转正向向前进
### 代码声明
#### 命名规范
1.包名
```
*
package名和目录保持一致,需避免和标准库冲突
小写
*
package comm
```
2.命名
```
package pkg
*1.错误*
/*
定义在包的首部,所有错误都定义在一起,
并且以Err开头
*/
var ErrFooBar = fmt.Errorf("pkg: ...")
*2.变量*
/*
采用驼峰命名
*/
var fooBar int
*3.常量*
/*
大写+下划线
*/
var(
FOO = 1
BAR = 2
FOO_BAR = 3
)
*4.结构*
/*
采用驼峰命名法
*/
type FooBar struct{
foo int
Bar string
}
*5.方法接口*
/*
采用驼峰命名法
非对外方法,首字母需为小写
*/
func foo(){}
func Foo(){}
```
3.目录结构
```
* conf //配置
* dev.conf
* prod.conf
* controller //控制器
* v1
* auth.go
* internal
* repository //存储层
* user.go
* *_mock.go
* model //模型
* protocol //协议层
* routers //路由
* service //逻辑层
* auth
* static //静态数据
* views //视图
* main.go
* Dockerfile
* README.md
* *.sh //脚本
```
#### 项目约定
1. 入参跟返回值都要定义一个协议结构 protocol.XxxRequest \*protocol.XxxResponse,方便扩展
2. 函数方法的变量都定义在函数的头几行 var( ... )
3. 服务调用尽量封装成接口,方便测试扩展 比如:ISmsServe{ Send() error }
4. 公用的基础代码库,需要做一下封装放在 [gocomm](http://gitlab.fjmaimaimai.com/mmm-go/gocomm) ,方便在其他项目中调用
5. 可以使用代码生成固定格式, [项目地址](http://gitlab.fjmaimaimai.com/mmm-go/gencode) 脚本:.\gencode.exe new -c Auth -m Login
```
package pkg
//Login
func(this *AuthController)Login(){
var msg *protocol.ResponseMessage
defer func(){
this.Resp(msg)
}()
var request *protocol.LoginRequest
if err:=json.Unmarshal(this.ByteBody,&request);err!=nil{
log.Error(err)
msg = protocol.ReturnResponse(1)
return
}
if b,m :=this.Valid(request);!b{
msg = m
return
}
msg = this.GenMessage(auth.Login(request))
}
/*Login */
type LoginRequest struct {
Xxx string`json:"xxx" valid:"Required"`
}
type LoginResponse struct {
}
func Login(request *protocol.LoginRequest)(rsp *protocol.LoginResponse,err error){
var (
)
rsp =&protocol.LoginResponse{}
return
}
```
#### 注意事项
1. 启动一个 groutine(eg:go func(){}()),需要在函数内进行 recover,不然 groutine 里面 panic,会导致外部程序一起崩溃掉;
2. 当接受者是 map, chan, func, 不要使用指针传递,因为它们本身就是引用类型
3. 当接受者类型是一个结构体并且很庞大,或者是一个大数组,建议使用指针传递来提高性能,其他场景使用值传递即可
4. 当接受者是一个结构体,并且包含了 sync.Mutex 或者类似的用于同步的成员。必须使用指针传递,避免成员拷贝
5. 当函数内部需要修改接受者,必须使用指针传递
6. 声明空的 slice 应该使用下面的格式: var t []string 不要使用 t := []string{} ,前者声明了一个 nil slice 而后者是一个长度为 0 的非 nil 的 slice。
... ...
#!/usr/bin/env bash
##部署脚本/文件路径
#deploy_shell_path="/home/tiptok/test/ability.tar"
deploy_shell_path="/home/tiptok/test/ability.zip"
go build -o ability main.go
chmod +x ability
#tar -zcvf ${deploy_shell_path} ability conf deploy.sh run.sh start.sh stop.sh
zip -r ${deploy_shell_path} ability conf deploy.sh run.sh start.sh stop.sh
... ...
appname = opportunity
httpport = 8080
runmode = dev
#没设置的话 this.Ctx.Input.RequestBody 没有值
copyrequestbody = true
#enablexsrf = true
#开启应用内文档开关
EnableDocs = true
include "dev.conf"
include "prod.conf"
... ...
[dev]
#数据库相关
data_source = "root:123456@tcp(192.168.100.102:3306)/opportunity?loc=Local"
#data_source = "root:sutianxia2015@tcp(115.29.205.99:3306)/ability_display"
#data_source = "root:root@tcp(localhost:3306)/ability_display?loc=Local"
#redis相关配置
redis_add_port = "192.168.100.102:6379"
redis_auth = "123456"
#sms相关配置
yunpian_sms_sdk_url ="https://sms.yunpian.com/v2/sms/single_send.json"
yunpian_app_key ="0bf6fb10a11a68a95dee80901eb545b5"
#存储 http://ability.fjmaimaimai.com:8080/
source_host ="http://192.168.139.131:8080/"
source_virtual_path=file/ab
source_path =/home/tiptok/www/ab
#网易云信 IM
net_im_base_url ="https://api.netease.im/nimserver"
net_im_app_secret ="a8d231f5c13a"
net_im_app_key ="9c5410602597a7fe367aeeebd8210262"
\ No newline at end of file
... ...
[prod]
#数据库相关
data_source = "root:123456@tcp(192.168.100.102:3306)/ability_display?loc=Local"
#redis相关配置
redis_add_port = "192.168.100.102:6379"
redis_auth = "123456"
#sms相关配置
yunpian_sms_sdk_url ="https://sms.yunpian.com/v2/sms/single_send.json"
yunpian_app_key ="0bf6fb10a11a68a95dee80901eb545b5"
#存储 http://ability.fjmaimaimai.com:8080/
source_host ="http://192.168.139.131:8080/"
source_virtual_path=file/ab
source_path =/home/tiptok/www/ab
#网易云信 IM
net_im_base_url ="https://api.netease.im/nimserver"
net_im_app_secret ="a8d231f5c13a"
net_im_app_key ="9c5410602597a7fe367aeeebd8210262"
\ No newline at end of file
... ...
package controllers
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"strconv"
"strings"
"opp/protocol"
s_auth "opp/services/auth"
"github.com/astaxie/beego"
"github.com/astaxie/beego/context"
"github.com/astaxie/beego/validation"
"github.com/prometheus/client_golang/prometheus"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/common"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/mybeego"
)
var (
//prometheus 监控endpoint
HTTPReqTotal *prometheus.CounterVec
auth s_auth.IAuthService = &s_auth.AuthService{}
)
type BaseController struct {
mybeego.BaseController
}
func init() {
// HistogramVec 是一组Histogram
HTTPReqTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "request_count_vec", //http_requests_total
Help: "total number of http requests made.",
}, []string{"method", "path"})
// 这里的"method"、"path"、"status" 都是label , "status"
prometheus.MustRegister(
HTTPReqTotal,
)
//if err:=prometheus.Register(HTTPReqTotal);err!=nil{
// log.Error(err)
//}
}
var DefaultController *BaseController = &BaseController{}
//Valid valid struct
func (this *BaseController) Valid(obj interface{}) (result bool, msg *protocol.ResponseMessage) {
/*校验*/
var err error
valid := validation.Validation{}
result, err = valid.Valid(obj)
if err != nil {
msg = protocol.BadRequestParam(1)
return
}
if !result {
for _, err := range valid.Errors {
log.Error(err.Key, err.Message)
}
msg = protocol.BadRequestParam(2)
return
}
return
}
func (this *BaseController) Resp(msg *protocol.ResponseMessage) {
this.Data["json"] = msg
this.ServeJSON()
}
//GenMessage genarate a response message
// func (this *BaseController) GenMessage(rsp interface{}, err error) *protocol.ResponseMessage {
// var msg *protocol.ResponseMessage
// if err == nil {
// msg = protocol.ReturnResponse(0)
// msg.Data = rsp
// return msg
// }
// //log.Error(err)
// if e, ok := err.(common.Error); ok {
// msg = protocol.ReturnResponse(e.Code)
// msg.Data = rsp
// return msg
// }
// msg = protocol.ReturnResponse(1)
// return msg
// }
//获取请求头信息
func GetRequestHeader(ctx *context.Context) *protocol.RequestHeader {
h := &protocol.RequestHeader{}
h.AccessToken = ctx.Input.Header("x-mmm-accesstoken")
h.AppProject = ctx.Input.Header("x-mmm-appproject")
h.DeviceType = ctx.Input.Header("x-mmm-devicetype")
h.Sign = ctx.Input.Header("x-mmm-sign")
h.Uuid = ctx.Input.Header("x-mmm-uuid")
h.TimeStamp = ctx.Input.Header("x-mmm-timestamp")
h.Uid, _ = strconv.ParseInt(ctx.Input.Header("uid"), 10, 64) //需要uid写入到header里面
return h
}
//过滤器
func FilterComm(ctx *context.Context) {
//if strings.HasSuffix(ctx.Request.RequestURI,"login"){
// return
//}
//统计
MetricCounter(ctx)
if beego.BConfig.RunMode != "prod" {
return
}
//1.检查签名
if !CheckSign(ctx) {
return
}
//2.检查token是否有效
if !CheckToken(ctx) {
return
}
//3.查重uuid
if !CheckUuid(ctx) {
return
}
return
}
func MetricCounter(ctx *context.Context) {
// 请求数加1
HTTPReqTotal.With(prometheus.Labels{
"method": ctx.Request.Method,
"path": ctx.Request.RequestURI,
//"status": strconv.Itoa(c.Writer.Status()),
}).Inc()
}
//检查签名
func CheckSign(ctx *context.Context) (result bool) {
var (
h *protocol.RequestHeader
sign string
signHex string
)
result = true
h = GetRequestHeader(ctx)
//1.检查签名
sign = fmt.Sprintf("v!(MmM%v%v%vMmM)i^", h.TimeStamp, h.Uuid, h.AccessToken)
sha256 := sha256.New()
sha256.Write([]byte(sign))
signHex = hex.EncodeToString(sha256.Sum(nil))
if strings.Compare(signHex, h.Sign) != 0 {
msg := protocol.BadRequestParam(113)
log.Error(fmt.Sprintf("%v req:%v resp:%v %v", ctx.Request.RequestURI, common.AssertJson(h), common.AssertJson(msg), signHex))
ctx.Output.JSON(msg, false, false)
result = false
return
}
return
}
//检查access_token
func CheckToken(ctx *context.Context) (result bool) {
var (
msg *protocol.ResponseMessage
)
result = true
defer func() {
if msg != nil {
result = false
ctx.Output.JSON(msg, false, false)
}
}()
token := ctx.Input.Header("x-mmm-accesstoken")
if rsp, err := auth.CheckToken(&protocol.CheckTokenRequest{Token: token}); err != nil || rsp.UserInfo == nil {
msg = protocol.NewReturnResponse(rsp, err)
log.Error(fmt.Sprintf("%v req:%v resp:%v", ctx.Request.RequestURI, token, common.AssertJson(msg)))
return
} else {
if rsp.UserInfo != nil {
//设置附加数据
ctx.Request.Header.Add("uid", fmt.Sprintf("%v", rsp.UserInfo.Uuid))
}
}
return
}
//检查Uuid
func CheckUuid(ctx *context.Context) (result bool) {
var (
msg *protocol.ResponseMessage
)
result = true
defer func() {
if msg != nil {
result = false
ctx.Output.JSON(msg, false, false)
}
}()
uuid := ctx.Input.Header("x-mmm-uuid")
msg = protocol.NewReturnResponse(auth.CheckUuid(&protocol.CheckUuidRequest{Uuid: uuid}))
if msg != nil {
log.Error(fmt.Sprintf("%v req:%v resp:%v", ctx.Request.RequestURI, uuid, common.AssertJson(msg)))
}
return
}
... ...
package controllers
import (
"fmt"
"log"
"reflect"
"testing"
"time"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/common"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/mybeego"
)
func Test_GenMessage(t *testing.T) {
input := []struct {
Rsp interface{}
Error error
Exceprt *mybeego.Message
}{
{Rsp: "test", Error: fmt.Errorf("test"), Exceprt: mybeego.NewMessage(1)},
{Rsp: "test-A", Error: common.NewErrorWithMsg(100, "test-A"), Exceprt: mybeego.NewErrMessage(100, "test-A")},
}
for i := range input {
o := input[i]
out := DefaultController.GenMessage(o.Rsp, o.Error)
if !reflect.DeepEqual(out, o.Exceprt) {
log.Fatal("not equal ", out, o.Exceprt)
}
}
}
func Benchmark_GenMessage(b *testing.B) {
o := struct {
Rsp interface{}
Error error
Exceprt *mybeego.Message
}{Rsp: "test", Error: fmt.Errorf("test"), Exceprt: mybeego.NewMessage(1)}
for i := 0; i < b.N; i++ {
out := DefaultController.GenMessage(o.Rsp, o.Error)
if out.Errmsg != o.Exceprt.Errmsg || out.Errno != o.Exceprt.Errno {
log.Fatal("not equal ", out, o.Exceprt)
}
}
}
func TestXXX(t *testing.T) {
t.Log(time.Now())
}
... ...
package v1
import (
"encoding/json"
"opp/controllers"
"opp/protocol"
s_auth "opp/services/auth"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
)
var (
auth s_auth.IAuthService = &s_auth.AuthService{}
)
type AuthController struct {
controllers.BaseController
}
// Login
// @router /login [post]
func (this *AuthController) Login() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.LoginRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
msg = protocol.NewReturnResponse(auth.Login(request))
}
//SmsCode
// @router /smsCode [post]
func (this *AuthController) SmsCode() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.SmsCodeRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
msg = protocol.NewReturnResponse(auth.SmsCode(request))
}
//UpdateDevice
// @router /updateDevice [post]
func (this *AuthController) UpdateDevice() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.UpdateDeviceRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
msg = protocol.NewReturnResponse(auth.UpdateDevice(request))
}
//AccessToken
// @router /accessToken [post]
func (this *AuthController) AccessToken() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.AccessTokenRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
msg = protocol.NewReturnResponse(auth.AccessToken(request))
}
//RefreshToken
// @router /refreshToken [post]
func (this *AuthController) RefreshToken() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.RefreshTokenRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
msg = protocol.NewReturnResponse(auth.RefreshToken(request))
}
... ...
package v1
import (
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/mybeego"
)
type MainController struct {
mybeego.BaseController
}
// URLMapping ...
func (this *MainController) URLMapping() {
//this.Mapping("Get", this.Get)
//this.Mapping("Hello", this.Hello)
}
func (c *MainController) Get() {
c.Data["Website"] = "beego.me"
c.Data["Email"] = "astaxie@gmail.com"
c.TplName = "index.tpl"
}
... ...
package v1
import (
"opp/controllers"
"opp/protocol"
"opp/services/upload"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
)
type UploadController struct {
controllers.BaseController
}
// Image
// @router /image [post]
func (this *UploadController) Image() {
var (
msg *protocol.ResponseMessage
err error
)
defer func() {
this.Resp(msg)
}()
var request = &protocol.FileRequest{}
//if err:=json.Unmarshal(this.ByteBody,&request);err!=nil{
// log.Error(err)
// msg = protocol.ReturnResponse(1)
// return
//}
//if b,m :=this.Valid(request);!b{
// msg = m
// return
//}
if request.Files, err = this.GetFiles("file"); err != nil {
log.Error(err)
return
}
msg = protocol.NewReturnResponse(upload.Image(request))
}
// Image
// @router /voice [post]
func (this *UploadController) Voice() {
var (
msg *protocol.ResponseMessage
err error
)
defer func() {
this.Resp(msg)
}()
var request = &protocol.FileRequest{}
//if err:=json.Unmarshal(this.ByteBody,&request);err!=nil{
// log.Error(err)
// msg = protocol.ReturnResponse(1)
// return
//}
//if b,m :=this.Valid(request);!b{
// msg = m
// return
//}
if request.Files, err = this.GetFiles("file"); err != nil {
log.Error(err)
return
}
msg = protocol.NewReturnResponse(upload.Voice(request))
}
... ...
package v1
import (
"encoding/json"
"opp/controllers"
"opp/protocol"
"opp/services/version"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
)
type VersionController struct {
controllers.BaseController
}
//GetLatestVersionInfo
func (this *VersionController) GetLatestVersionInfo() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.GetLatestVersionInfoRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
msg = protocol.NewReturnResponse(version.GetLatestVersionInfo(request))
}
... ...
package v1
import (
"opp/controllers"
)
type WebSocketController struct {
controllers.BaseController
}
... ...
#!/bin/bash
time=$(date +%Y%m%d_%H%m%s)
project_name="ability"
##部署脚本/文件路径
deploy_shell_path="/home/tiptok/test"
##部署路径
project_root_path="/home/tiptok/www"
project_path="${project_root_path}/${project_name}"
##备份路径
project_bak_path="/home/tiptok/www/bin_bak"
projcet_bak_file="${project_bak_path}/${time}_${project_name}.tar"
## 看压缩文件的格式 tar / zip
#project_gzip_file="${deploy_shell_path}/${project_name}.tar"
project_gzip_file="${deploy_shell_path}/${project_name}.zip"
conpress_type="${project_gzip_file##*.}"
echo "------begin deploy-------"
echo "ProjectName: ${project_name}"
echo "ProjectPath: ${project_path}"
echo "ProjectBakFile : ${projcet_bak_file}"
echo "ProjectGzipFile : ${project_gzip_file}"
echo "ConpressType : ${conpress_type}"
if [ ! -d ${project_bak_path} ];then
mkdir -p ${project_bak_path}
echo "mkdir ${project_bak_path}"
fi
if [ ! -d ${project_path} ];then
mkdir -p ${project_path}
echo "mkdir ${project_path}"
else
echo "backup : ${projcet_bak_file}"
cd $project_path && tar -zcf ${projcet_bak_file} * ||(echo "backup failed"; exit 1)
rm -fr "${project_path}/" *
fi
echo "------begin tar-------"
if [ ! -e ${project_path} ];then
mkdir -p ${project_path}
echo "mkdir ${project_path}"
fi
if [ -f ${project_gzip_file} ];then
if [ ${conpress_type} == "tar" ];then
tar -xzf ${project_gzip_file} -C "${project_root_path}/${project_name}"||(echo "tar -x failed"; exit 1)
elif [ ${conpress_type} == "zip" ];then
unzip -o ${project_gzip_file} -d "${project_root_path}/${project_name}"||(echo "tar -x failed"; exit 1)
fi
rm -fr ${project_gzip_file}
else
echo "project_gzip_file not exists! please upload zip file ..."
exit 0
fi
echo "------begin start-------"
cd ${project_path} && ./start.sh ${project_name}
... ...
version: '3.1' #指定docker-compose 版本
services:
redis:
image: redis #使用 镜像
container_name: gocomm_redis
command: redis-server /usr/local/etc/redis/redis.conf
ports: #
- 6379:6379
volumes:
- ./data:/data
- ./redis.conf:/usr/local/etc/redis/redis.conf
db:
#构建mysql镜像
image: mysql
container_name: gocomm-mysql # 容器名
command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci #设置utf8字符集
restart: always
environment:
MYSQL_ROOT_PASSWORD: 123456 #root管理员用户密码
MYSQL_USER: test #创建test用户
MYSQL_PASSWORD: 123456 #设置test用户的密码
ports:
- 3306:3306 #host物理直接映射端口为6606
volumes:
#mysql数据库挂载到host物理机目录/e/docker/mysql/data/db
- "/docker/mysql/data/db:/var/lib/mysql"
#容器的配置目录挂载到host物理机目录/e/docker/mysql/data/conf
- "/docker/mysql/data/conf:/etc/mysql/conf.d"
ability: #定义服务名称
build: ./ #引入了 build 的路径,它指向一个存有 Dockerfile 的目录
ports: #
- 8081:8081
environment:
RUNMODULE: "PROD"
\ No newline at end of file
... ...
module opp
go 1.12
require (
github.com/astaxie/beego v1.10.0
github.com/go-sql-driver/mysql v1.4.1
github.com/gorilla/websocket v1.4.1
github.com/prometheus/client_golang v1.1.0
github.com/smartystreets/goconvey v0.0.0-20190731233626-505e41936337 // indirect
gitlab.fjmaimaimai.com/mmm-go/gocomm v0.0.1
google.golang.org/appengine v1.6.2 // indirect
)
replace gitlab.fjmaimaimai.com/mmm-go/gocomm => ../gocomm
... ...
package repository
import "opp/models"
type IConfigRepository interface {
GetCfgClient(clintId, clientSecret string) (v *models.CfgClient, err error)
}
type ConfigRepository struct{}
func (r *ConfigRepository) GetCfgClient(clintId, clientSecret string) (v *models.CfgClient, err error) {
return models.GetCfgClient(clintId, clientSecret)
}
... ...
package repository
import "opp/models"
type ConfigMockeRepository struct{}
func (r *ConfigMockeRepository) GetCfgClient(clintId, clientSecret string) (v *models.CfgClient, err error) {
return
}
... ...
package repository
import "opp/models"
type IUserRepository interface {
GetUsersByMobile(mobile string) (v *models.Users, err error)
GetUserInfoByMobile(mobile string) (v *models.UserInfo, err error)
UpdateUserInfoById(m *models.UserInfo) (err error)
GetUserInfoByAuthCode(authCode string) (v *models.UserInfo, err error)
GetUserInfoByRefreshToken(refreshToken string) (v *models.UserInfo, err error)
}
func assertImplement() {
var _ IUserRepository = (*UserRepository)(nil)
}
type UserRepository struct{}
func (r *UserRepository) GetUsersByMobile(mobile string) (v *models.Users, err error) {
return models.GetUsersByMobile(mobile)
}
func (r *UserRepository) GetUserInfoByMobile(mobile string) (v *models.UserInfo, err error) {
return models.GetUserInfoByMobile(mobile)
}
func (r *UserRepository) UpdateUserInfoById(m *models.UserInfo) (err error) {
return models.UpdateUserInfoById(m)
}
func (r *UserRepository) GetUserInfoByAuthCode(authCode string) (v *models.UserInfo, err error) {
return models.GetUserInfoByAuthCode(authCode)
}
func (r *UserRepository) GetUserInfoByRefreshToken(refreshToken string) (v *models.UserInfo, err error) {
return models.GetUserInfoByRefreshToken(refreshToken)
}
... ...
package repository
import "opp/models"
type UserMockRepository struct{}
var userInfo = &models.UserInfo{
Auth: "897ca746f46b11e98771000c29ad8d6d",
AccessToken: "897ca746f46b11e98771000c29ad8d7d",
RefreshToken: "897ca746f46b11e98771000c29ad8d8d",
}
func (r *UserMockRepository) GetUsersByMobile(mobile string) (v *models.Users, err error) {
v = &models.Users{
Username: "18065048389",
Password: "$2y$10$YWg7jPRVLBzc3kevokMkW.boswtCvhToqC.TappIwfqwJ.cI0efvy",
}
return
}
func (r *UserMockRepository) GetUserInfoByMobile(mobile string) (v *models.UserInfo, err error) {
v = userInfo
return
}
func (r *UserMockRepository) UpdateUserInfoById(m *models.UserInfo) (err error) {
return
}
func (r *UserMockRepository) GetUserInfoByAuthCode(authCode string) (v *models.UserInfo, err error) {
v = userInfo
return
}
func (r *UserMockRepository) GetUserInfoByRefreshToken(refreshToken string) (v *models.UserInfo, err error) {
v = userInfo
return
}
... ...
package main
import (
"github.com/astaxie/beego"
_ "github.com/go-sql-driver/mysql"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/common"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/config"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/orm"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/redis"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/websocket"
"opp/controllers"
"opp/protocol"
_ "opp/routers"
"opp/services/im"
"time"
)
func init() {
time.Local = time.FixedZone("CST", 3600*8)
log.InitLog(config.Logger{
Filename: "app.log",
Level: "7",
})
//TODO:kafka配置
log.InitKafkaLogger(log.KafkaConfig{
Topic: "ability",
Addrs: []string{"127.0.0.1:9092"},
Level: 6,
})
err := redis.InitWithDb(100, beego.AppConfig.String("redis_add_port"), beego.AppConfig.String("redis_auth"), "0")
if err != nil {
log.Fatal(err, beego.AppConfig.String("redis_add_port"), beego.AppConfig.String("redis_auth"))
//panic(err)
}
orm.NewBeeormEngine(config.Mysql{
AliasName: "default",
DataSource: beego.AppConfig.String("data_source"),
MaxIdle: 100,
MaxOpen: 100,
})
//TODO:邮件服务配置
common.InitMailService(&common.MailConfig{
//Host:"smtp.qq.com",
//Port:465,
//From:"785410885@qq.com",
//Password:"ibfduqhfmgypbffe", //授权码
//IsUseSsl:true,
})
im.InitImClient(beego.AppConfig.String("net_im_base_url"), beego.AppConfig.String("net_im_app_key"), beego.AppConfig.String("net_im_app_secret"))
websocket.InitWebsocketConnmgrs(10)
}
func main() {
defer func() {
log.Info("app on stop!")
}()
beego.InsertFilter("/*", beego.BeforeRouter, controllers.FilterComm)
protocol.InitMessageCode()
log.Info("app on start!")
log.Info("Beego Run Mode:", beego.BConfig.RunMode)
beego.Run()
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/astaxie/beego/orm"
)
type Announcement struct {
Id int `orm:"column(id);pk" description:"主键ID"`
CreateTime time.Time `orm:"column(createTime);type(timestamp);auto_now_add" description:"创建时间"`
Content string `orm:"column(content);size(500)" description:"消息标题"`
CompanyId int64 `orm:"column(company_id);null"`
Day string `orm:"column(day);size(20)" description:"日期"`
}
func (t *Announcement) TableName() string {
return "announcement"
}
func init() {
orm.RegisterModel(new(Announcement))
}
// AddAnnouncement insert a new Announcement into database and returns
// last inserted Id on success.
func AddAnnouncement(m *Announcement) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetAnnouncementById retrieves Announcement by Id. Returns error if
// Id doesn't exist
func GetAnnouncementById(id int) (v *Announcement, err error) {
o := orm.NewOrm()
v = &Announcement{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllAnnouncement retrieves all Announcement matches certain condition. Returns empty list if
// no records exist
func GetAllAnnouncement(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(Announcement))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []Announcement
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdateAnnouncement updates Announcement by Id and returns error if
// the record to be updated doesn't exist
func UpdateAnnouncementById(m *Announcement) (err error) {
o := orm.NewOrm()
v := Announcement{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteAnnouncement deletes Announcement by Id and returns error if
// the record to be deleted doesn't exist
func DeleteAnnouncement(id int) (err error) {
o := orm.NewOrm()
v := Announcement{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&Announcement{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/astaxie/beego/orm"
)
type BonusPoint struct {
Id int `orm:"column(id);pk"`
CompanyId int `orm:"column(company_id)" description:"公司ID"`
Type int8 `orm:"column(type)" description:"加分类型 0发现 1分析 2解决"`
Uid int64 `orm:"column(uid)" description:"被加分人"`
Score int `orm:"column(score)" description:"加分数值"`
JoinDate time.Time `orm:"column(join_date);type(date)" description:"加入年月"`
OperatorId int64 `orm:"column(operator_id)" description:"加分人(操作者id)"`
Reason string `orm:"column(reason);size(500);null" description:"加分理由"`
CreateTime time.Time `orm:"column(createTime);type(timestamp);auto_now_add"`
UpdateTime time.Time `orm:"column(updateTime);type(timestamp);auto_now_add"`
}
func (t *BonusPoint) TableName() string {
return "bonus_point"
}
func init() {
orm.RegisterModel(new(BonusPoint))
}
// AddBonusPoint insert a new BonusPoint into database and returns
// last inserted Id on success.
func AddBonusPoint(m *BonusPoint) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetBonusPointById retrieves BonusPoint by Id. Returns error if
// Id doesn't exist
func GetBonusPointById(id int) (v *BonusPoint, err error) {
o := orm.NewOrm()
v = &BonusPoint{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllBonusPoint retrieves all BonusPoint matches certain condition. Returns empty list if
// no records exist
func GetAllBonusPoint(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(BonusPoint))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []BonusPoint
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdateBonusPoint updates BonusPoint by Id and returns error if
// the record to be updated doesn't exist
func UpdateBonusPointById(m *BonusPoint) (err error) {
o := orm.NewOrm()
v := BonusPoint{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteBonusPoint deletes BonusPoint by Id and returns error if
// the record to be deleted doesn't exist
func DeleteBonusPoint(id int) (err error) {
o := orm.NewOrm()
v := BonusPoint{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&BonusPoint{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/astaxie/beego/orm"
)
type Bulletin struct {
Id int `orm:"column(id);auto"`
Title string `orm:"column(title);size(2000);null" description:"标题"`
Content string `orm:"column(content);null" description:"内容"`
Cover string `orm:"column(cover);size(255);null" description:"封面地址"`
W int `orm:"column(w);null" description:"宽"`
H int `orm:"column(h);null" description:"高"`
Type int8 `orm:"column(type);null" description:"公告类型(0图+跳转链接、1链接)"`
Receiver string `orm:"column(receiver);null" description:"接收者"`
QuestionSwitch int8 `orm:"column(question_switch);null" description:"设置问题开关"`
CreateTime time.Time `orm:"column(createTime);type(timestamp);null" description:"创建时间"`
UpdateTime time.Time `orm:"column(updateTime);type(timestamp);null" description:"更新时间"`
AllowClose int8 `orm:"column(allowClose);null" description:"允许关闭公告(0允许,1禁止)"`
CompanyId int `orm:"column(company_id);null" description:"公司Id"`
Status uint8 `orm:"column(status)" description:"状态 0-下架 1- 上架"`
}
func (t *Bulletin) TableName() string {
return "bulletin"
}
func init() {
orm.RegisterModel(new(Bulletin))
}
// AddBulletin insert a new Bulletin into database and returns
// last inserted Id on success.
func AddBulletin(m *Bulletin) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetBulletinById retrieves Bulletin by Id. Returns error if
// Id doesn't exist
func GetBulletinById(id int) (v *Bulletin, err error) {
o := orm.NewOrm()
v = &Bulletin{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllBulletin retrieves all Bulletin matches certain condition. Returns empty list if
// no records exist
func GetAllBulletin(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(Bulletin))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []Bulletin
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdateBulletin updates Bulletin by Id and returns error if
// the record to be updated doesn't exist
func UpdateBulletinById(m *Bulletin) (err error) {
o := orm.NewOrm()
v := Bulletin{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteBulletin deletes Bulletin by Id and returns error if
// the record to be deleted doesn't exist
func DeleteBulletin(id int) (err error) {
o := orm.NewOrm()
v := Bulletin{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&Bulletin{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/astaxie/beego/orm"
)
type BulletinQuestion struct {
Id int `orm:"column(id);auto"`
BulletinId int `orm:"column(bulletin_id);null" description:"公告id"`
Type int8 `orm:"column(type);null" description:"类型:0-单选,1-多选"`
Title string `orm:"column(title);size(2000);null" description:"标题"`
Content string `orm:"column(content);size(2000);null" description:"内容"`
CreateTime time.Time `orm:"column(createTime);type(timestamp);null" description:"创建时间"`
UpdateTime time.Time `orm:"column(updateTime);type(timestamp);null" description:"更新时间"`
}
func (t *BulletinQuestion) TableName() string {
return "bulletin_question"
}
func init() {
orm.RegisterModel(new(BulletinQuestion))
}
// AddBulletinQuestion insert a new BulletinQuestion into database and returns
// last inserted Id on success.
func AddBulletinQuestion(m *BulletinQuestion) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetBulletinQuestionById retrieves BulletinQuestion by Id. Returns error if
// Id doesn't exist
func GetBulletinQuestionById(id int) (v *BulletinQuestion, err error) {
o := orm.NewOrm()
v = &BulletinQuestion{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllBulletinQuestion retrieves all BulletinQuestion matches certain condition. Returns empty list if
// no records exist
func GetAllBulletinQuestion(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(BulletinQuestion))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []BulletinQuestion
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdateBulletinQuestion updates BulletinQuestion by Id and returns error if
// the record to be updated doesn't exist
func UpdateBulletinQuestionById(m *BulletinQuestion) (err error) {
o := orm.NewOrm()
v := BulletinQuestion{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteBulletinQuestion deletes BulletinQuestion by Id and returns error if
// the record to be deleted doesn't exist
func DeleteBulletinQuestion(id int) (err error) {
o := orm.NewOrm()
v := BulletinQuestion{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&BulletinQuestion{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/astaxie/beego/orm"
)
type BulletinQuestionAnswer struct {
Id int `orm:"column(id);auto"`
Answer string `orm:"column(answer);null" description:"答案"`
BulletinId int `orm:"column(bulletin_id);null" description:"公告id"`
BulletinQuestionId int `orm:"column(bulletin_question_id);null" description:"公告问题id"`
Uid int64 `orm:"column(uid);null" description:"用户id"`
CreateTime time.Time `orm:"column(createTime);type(timestamp);null" description:"创建时间"`
UpdateTime time.Time `orm:"column(updateTime);type(timestamp);null" description:"更新时间"`
}
func (t *BulletinQuestionAnswer) TableName() string {
return "bulletin_question_answer"
}
func init() {
orm.RegisterModel(new(BulletinQuestionAnswer))
}
// AddBulletinQuestionAnswer insert a new BulletinQuestionAnswer into database and returns
// last inserted Id on success.
func AddBulletinQuestionAnswer(m *BulletinQuestionAnswer) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetBulletinQuestionAnswerById retrieves BulletinQuestionAnswer by Id. Returns error if
// Id doesn't exist
func GetBulletinQuestionAnswerById(id int) (v *BulletinQuestionAnswer, err error) {
o := orm.NewOrm()
v = &BulletinQuestionAnswer{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllBulletinQuestionAnswer retrieves all BulletinQuestionAnswer matches certain condition. Returns empty list if
// no records exist
func GetAllBulletinQuestionAnswer(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(BulletinQuestionAnswer))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []BulletinQuestionAnswer
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdateBulletinQuestionAnswer updates BulletinQuestionAnswer by Id and returns error if
// the record to be updated doesn't exist
func UpdateBulletinQuestionAnswerById(m *BulletinQuestionAnswer) (err error) {
o := orm.NewOrm()
v := BulletinQuestionAnswer{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteBulletinQuestionAnswer deletes BulletinQuestionAnswer by Id and returns error if
// the record to be deleted doesn't exist
func DeleteBulletinQuestionAnswer(id int) (err error) {
o := orm.NewOrm()
v := BulletinQuestionAnswer{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&BulletinQuestionAnswer{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/astaxie/beego/orm"
)
type CfgAppVersion struct {
Id int `orm:"column(id);auto"`
DeviceType int8 `orm:"column(device_type);null" description:"设备类型 (0 ios 1android)"`
VersionName string `orm:"column(version_name);size(255)" description:"版本名"`
VersionNo int `orm:"column(version_no)" description:"版本号"`
VersionState int8 `orm:"column(version_state)" description:"版本状态(0正常 1危险)"`
Title string `orm:"column(title);size(255)" description:"版本标题"`
Content string `orm:"column(content);size(500)" description:"更新的内容"`
DownloadPage string `orm:"column(download_page);size(255);null" description:"下载页"`
DownloadFile string `orm:"column(download_file);size(255)" description:"文件下载页"`
CreateTime time.Time `orm:"column(create_time);type(timestamp);null;auto_now"`
Enabled int8 `orm:"column(enabled);null" description:"是否有效"`
AdminId int `orm:"column(admin_id)" description:"操作人员"`
UpdateTime time.Time `orm:"column(update_time);type(timestamp);auto_now_add" description:"更新时间"`
Channel string `orm:"column(channel);size(255)" description:"当前渠道 0_AppStore、1_fir平台、2_华为、3_小米、4_魅族、5_oppo、6_vivo、7_360、8_百度、9_应用宝、10_其他(使用应用宝地址)"`
Type int8 `orm:"column(type);null" description:"0为手机 1为平板 终端类型"`
}
func (t *CfgAppVersion) TableName() string {
return "cfg_app_version"
}
func init() {
orm.RegisterModel(new(CfgAppVersion))
}
// AddCfgAppVersion insert a new CfgAppVersion into database and returns
// last inserted Id on success.
func AddCfgAppVersion(m *CfgAppVersion) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetCfgAppVersionById retrieves CfgAppVersion by Id. Returns error if
// Id doesn't exist
func GetCfgAppVersionById(id int) (v *CfgAppVersion, err error) {
o := orm.NewOrm()
v = &CfgAppVersion{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllCfgAppVersion retrieves all CfgAppVersion matches certain condition. Returns empty list if
// no records exist
func GetAllCfgAppVersion(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(CfgAppVersion))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []CfgAppVersion
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdateCfgAppVersion updates CfgAppVersion by Id and returns error if
// the record to be updated doesn't exist
func UpdateCfgAppVersionById(m *CfgAppVersion) (err error) {
o := orm.NewOrm()
v := CfgAppVersion{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteCfgAppVersion deletes CfgAppVersion by Id and returns error if
// the record to be deleted doesn't exist
func DeleteCfgAppVersion(id int) (err error) {
o := orm.NewOrm()
v := CfgAppVersion{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&CfgAppVersion{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
func GetCfgAppVersion(versionNo, channel int) (v *CfgAppVersion, err error) {
o := orm.NewOrm()
sql := `select * from cfg_app_version where version_no =? and channel =? and enabled=1`
if err = o.Raw(sql, versionNo, channel).QueryRow(&v); err == nil {
return v, nil
}
return nil, err
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/astaxie/beego/orm"
)
type CfgAttr struct {
Id int `orm:"column(id);auto" description:"主键ID"`
CompanyId int `orm:"column(company_id)" description:"公司Id"`
Name string `orm:"column(name);size(200)" description:"名称"`
Sort uint `orm:"column(sort)" description:"排序"`
CreateTime time.Time `orm:"column(createTime);type(timestamp);auto_now_add" description:"创建时间"`
Enabled int `orm:"column(enabled)"`
}
func (t *CfgAttr) TableName() string {
return "cfg_attr"
}
func init() {
orm.RegisterModel(new(CfgAttr))
}
// AddCfgAttr insert a new CfgAttr into database and returns
// last inserted Id on success.
func AddCfgAttr(m *CfgAttr) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetCfgAttrById retrieves CfgAttr by Id. Returns error if
// Id doesn't exist
func GetCfgAttrById(id int) (v *CfgAttr, err error) {
o := orm.NewOrm()
v = &CfgAttr{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllCfgAttr retrieves all CfgAttr matches certain condition. Returns empty list if
// no records exist
func GetAllCfgAttr(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(CfgAttr))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []CfgAttr
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdateCfgAttr updates CfgAttr by Id and returns error if
// the record to be updated doesn't exist
func UpdateCfgAttrById(m *CfgAttr) (err error) {
o := orm.NewOrm()
v := CfgAttr{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteCfgAttr deletes CfgAttr by Id and returns error if
// the record to be deleted doesn't exist
func DeleteCfgAttr(id int) (err error) {
o := orm.NewOrm()
v := CfgAttr{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&CfgAttr{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/astaxie/beego/orm"
)
type CfgClient struct {
Id int `orm:"column(id);auto" description:"主键ID"`
ClientId string `orm:"column(client_id);size(32)" description:"客户端ID"`
ClientSecret string `orm:"column(client_secret);size(128);null" description:"客户端密钥"`
CreateTime time.Time `orm:"column(create_time);type(timestamp);auto_now" description:"创建时间"`
Enabled int8 `orm:"column(enabled)" description:"是否有效"`
}
func (t *CfgClient) TableName() string {
return "cfg_client"
}
func init() {
orm.RegisterModel(new(CfgClient))
}
// AddCfgClient insert a new CfgClient into database and returns
// last inserted Id on success.
func AddCfgClient(m *CfgClient) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetCfgClientById retrieves CfgClient by Id. Returns error if
// Id doesn't exist
func GetCfgClientById(id int) (v *CfgClient, err error) {
o := orm.NewOrm()
v = &CfgClient{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllCfgClient retrieves all CfgClient matches certain condition. Returns empty list if
// no records exist
func GetAllCfgClient(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(CfgClient))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []CfgClient
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdateCfgClient updates CfgClient by Id and returns error if
// the record to be updated doesn't exist
func UpdateCfgClientById(m *CfgClient) (err error) {
o := orm.NewOrm()
v := CfgClient{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteCfgClient deletes CfgClient by Id and returns error if
// the record to be deleted doesn't exist
func DeleteCfgClient(id int) (err error) {
o := orm.NewOrm()
v := CfgClient{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&CfgClient{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
func GetCfgClient(clintId, clientSecret string) (v *CfgClient, err error) {
o := orm.NewOrm()
sql := "select * from cfg_client where enabled=1 and client_id=? and client_secret=?"
if err = o.Raw(sql, clintId, clientSecret).QueryRow(&v); err == nil {
return v, nil
}
return nil, err
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/astaxie/beego/orm"
)
type CfgMsg struct {
Id int `orm:"column(id);pk" description:"主键ID"`
CreateTime time.Time `orm:"column(createTime);type(timestamp);auto_now_add" description:"创建时间"`
Title string `orm:"column(title);size(100)" description:"消息标题"`
Type int `orm:"column(type)" description:"1为某某某代表解决 2为某某某提出 3为某某某申请解决"`
}
func (t *CfgMsg) TableName() string {
return "cfg_msg"
}
func init() {
orm.RegisterModel(new(CfgMsg))
}
// AddCfgMsg insert a new CfgMsg into database and returns
// last inserted Id on success.
func AddCfgMsg(m *CfgMsg) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetCfgMsgById retrieves CfgMsg by Id. Returns error if
// Id doesn't exist
func GetCfgMsgById(id int) (v *CfgMsg, err error) {
o := orm.NewOrm()
v = &CfgMsg{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllCfgMsg retrieves all CfgMsg matches certain condition. Returns empty list if
// no records exist
func GetAllCfgMsg(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(CfgMsg))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []CfgMsg
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdateCfgMsg updates CfgMsg by Id and returns error if
// the record to be updated doesn't exist
func UpdateCfgMsgById(m *CfgMsg) (err error) {
o := orm.NewOrm()
v := CfgMsg{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteCfgMsg deletes CfgMsg by Id and returns error if
// the record to be deleted doesn't exist
func DeleteCfgMsg(id int) (err error) {
o := orm.NewOrm()
v := CfgMsg{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&CfgMsg{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/astaxie/beego/orm"
)
type CfgQtype struct {
Id int `orm:"column(id);auto" description:"主键ID"`
CompanyId int `orm:"column(company_id)" description:"公司Id"`
Name string `orm:"column(name);size(200)" description:"消息标题"`
CreateTime time.Time `orm:"column(createTime);type(timestamp);auto_now_add" description:"创建时间"`
Enabled int `orm:"column(enabled)"`
}
func (t *CfgQtype) TableName() string {
return "cfg_qtype"
}
func init() {
orm.RegisterModel(new(CfgQtype))
}
// AddCfgQtype insert a new CfgQtype into database and returns
// last inserted Id on success.
func AddCfgQtype(m *CfgQtype) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetCfgQtypeById retrieves CfgQtype by Id. Returns error if
// Id doesn't exist
func GetCfgQtypeById(id int) (v *CfgQtype, err error) {
o := orm.NewOrm()
v = &CfgQtype{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllCfgQtype retrieves all CfgQtype matches certain condition. Returns empty list if
// no records exist
func GetAllCfgQtype(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(CfgQtype))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []CfgQtype
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdateCfgQtype updates CfgQtype by Id and returns error if
// the record to be updated doesn't exist
func UpdateCfgQtypeById(m *CfgQtype) (err error) {
o := orm.NewOrm()
v := CfgQtype{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteCfgQtype deletes CfgQtype by Id and returns error if
// the record to be deleted doesn't exist
func DeleteCfgQtype(id int) (err error) {
o := orm.NewOrm()
v := CfgQtype{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&CfgQtype{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/astaxie/beego/orm"
)
type Commend struct {
Id int `orm:"column(cid);pk" description:"主键ID"`
Uid int64 `orm:"column(uid)" description:"用户ID"`
Username string `orm:"column(username);size(255)" description:"用户名"`
CreateTime time.Time `orm:"column(createTime);type(timestamp);auto_now_add" description:"创建时间"`
QuestionTitle string `orm:"column(questionTitle);size(100)" description:"标题"`
QuestionId int64 `orm:"column(questionId);null"`
Way int `orm:"column(way)" description:"0提出问题、1参与解决问题"`
Company string `orm:"column(company);size(50)" description:"是否已读 0未读,1已读"`
CompanyId int `orm:"column(company_id)" description:"公司id"`
Status int8 `orm:"column(status)" description:"状态 1可见 2不可见"`
CommendationTime time.Time `orm:"column(commendation_time);type(date)" description:"表彰时间"`
}
func (t *Commend) TableName() string {
return "commend"
}
func init() {
orm.RegisterModel(new(Commend))
}
// AddCommend insert a new Commend into database and returns
// last inserted Id on success.
func AddCommend(m *Commend) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetCommendById retrieves Commend by Id. Returns error if
// Id doesn't exist
func GetCommendById(id int) (v *Commend, err error) {
o := orm.NewOrm()
v = &Commend{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllCommend retrieves all Commend matches certain condition. Returns empty list if
// no records exist
func GetAllCommend(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(Commend))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []Commend
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdateCommend updates Commend by Id and returns error if
// the record to be updated doesn't exist
func UpdateCommendById(m *Commend) (err error) {
o := orm.NewOrm()
v := Commend{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteCommend deletes Commend by Id and returns error if
// the record to be deleted doesn't exist
func DeleteCommend(id int) (err error) {
o := orm.NewOrm()
v := Commend{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&Commend{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/astaxie/beego/orm"
)
type Comment struct {
Id int `orm:"column(cid);pk"`
Uid int64 `orm:"column(uid);null"`
CreateTime time.Time `orm:"column(createTime);type(timestamp);auto_now_add"`
Content string `orm:"column(content)"`
PageView int `orm:"column(pageView);null" description:"浏览总数"`
CommentTotal int `orm:"column(commentTotal);null" description:"评论总数"`
SympathyTotal int `orm:"column(sympathyTotal)" description:"同感总数"`
Type int `orm:"column(type);null" description:"0问题、1评论、2方案"`
Id_RENAME int64 `orm:"column(id);null" description:"对应的ID"`
}
func (t *Comment) TableName() string {
return "comment"
}
func init() {
orm.RegisterModel(new(Comment))
}
// AddComment insert a new Comment into database and returns
// last inserted Id on success.
func AddComment(m *Comment) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetCommentById retrieves Comment by Id. Returns error if
// Id doesn't exist
func GetCommentById(id int) (v *Comment, err error) {
o := orm.NewOrm()
v = &Comment{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllComment retrieves all Comment matches certain condition. Returns empty list if
// no records exist
func GetAllComment(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(Comment))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []Comment
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdateComment updates Comment by Id and returns error if
// the record to be updated doesn't exist
func UpdateCommentById(m *Comment) (err error) {
o := orm.NewOrm()
v := Comment{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteComment deletes Comment by Id and returns error if
// the record to be deleted doesn't exist
func DeleteComment(id int) (err error) {
o := orm.NewOrm()
v := Comment{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&Comment{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/astaxie/beego/orm"
)
type Companies struct {
Id int `orm:"column(id);auto"`
Name string `orm:"column(name);size(255)"`
Username string `orm:"column(username);size(255)"`
Phone string `orm:"column(phone);size(255)"`
Status uint8 `orm:"column(status)" description:"状态 1启用 2禁用"`
CreateTime time.Time `orm:"column(create_time);type(timestamp);auto_now"`
}
func (t *Companies) TableName() string {
return "companies"
}
func init() {
orm.RegisterModel(new(Companies))
}
// AddCompanies insert a new Companies into database and returns
// last inserted Id on success.
func AddCompanies(m *Companies) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetCompaniesById retrieves Companies by Id. Returns error if
// Id doesn't exist
func GetCompaniesById(id int) (v *Companies, err error) {
o := orm.NewOrm()
v = &Companies{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllCompanies retrieves all Companies matches certain condition. Returns empty list if
// no records exist
func GetAllCompanies(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(Companies))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []Companies
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdateCompanies updates Companies by Id and returns error if
// the record to be updated doesn't exist
func UpdateCompaniesById(m *Companies) (err error) {
o := orm.NewOrm()
v := Companies{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteCompanies deletes Companies by Id and returns error if
// the record to be deleted doesn't exist
func DeleteCompanies(id int) (err error) {
o := orm.NewOrm()
v := Companies{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&Companies{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/astaxie/beego/orm"
)
type Departments struct {
Id int `orm:"column(id);auto"`
CompanyId int `orm:"column(company_id)"`
Name string `orm:"column(name);size(255)"`
Username string `orm:"column(username);size(255)"`
Number int `orm:"column(number)"`
CreateTime time.Time `orm:"column(create_time);type(timestamp);auto_now"`
Enabled uint8 `orm:"column(enabled)" description:"状态 1启用 0禁用"`
}
func (t *Departments) TableName() string {
return "departments"
}
func init() {
orm.RegisterModel(new(Departments))
}
// AddDepartments insert a new Departments into database and returns
// last inserted Id on success.
func AddDepartments(m *Departments) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetDepartmentsById retrieves Departments by Id. Returns error if
// Id doesn't exist
func GetDepartmentsById(id int) (v *Departments, err error) {
o := orm.NewOrm()
v = &Departments{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllDepartments retrieves all Departments matches certain condition. Returns empty list if
// no records exist
func GetAllDepartments(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(Departments))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []Departments
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdateDepartments updates Departments by Id and returns error if
// the record to be updated doesn't exist
func UpdateDepartmentsById(m *Departments) (err error) {
o := orm.NewOrm()
v := Departments{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteDepartments deletes Departments by Id and returns error if
// the record to be deleted doesn't exist
func DeleteDepartments(id int) (err error) {
o := orm.NewOrm()
v := Departments{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&Departments{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"github.com/astaxie/beego/orm"
)
type LogUuid struct {
Id int64 `orm:"column(id);auto" description:"主键ID"`
Uuid string `orm:"column(uuid);size(128)"`
}
func (t *LogUuid) TableName() string {
return "log_uuid"
}
func init() {
orm.RegisterModel(new(LogUuid))
}
// AddLogUuid insert a new LogUuid into database and returns
// last inserted Id on success.
func AddLogUuid(m *LogUuid) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetLogUuidById retrieves LogUuid by Id. Returns error if
// Id doesn't exist
func GetLogUuidById(id int64) (v *LogUuid, err error) {
o := orm.NewOrm()
v = &LogUuid{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllLogUuid retrieves all LogUuid matches certain condition. Returns empty list if
// no records exist
func GetAllLogUuid(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(LogUuid))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []LogUuid
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdateLogUuid updates LogUuid by Id and returns error if
// the record to be updated doesn't exist
func UpdateLogUuidById(m *LogUuid) (err error) {
o := orm.NewOrm()
v := LogUuid{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteLogUuid deletes LogUuid by Id and returns error if
// the record to be deleted doesn't exist
func DeleteLogUuid(id int64) (err error) {
o := orm.NewOrm()
v := LogUuid{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&LogUuid{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
func GetLogUuidByUuid(uuid string) (v *LogUuid, err error) {
o := orm.NewOrm()
sql := "select * from log_uuid where uuid=?"
if err = o.Raw(sql, uuid).QueryRow(&v); err == nil {
return v, nil
}
return nil, err
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"github.com/astaxie/beego/orm"
)
type Logic struct {
Id int `orm:"column(id);auto"`
Data string `orm:"column(data);null"`
Db string `orm:"column(db);size(50);null"`
Datatype string `orm:"column(datatype);size(50);null"`
Type string `orm:"column(type);size(100);null"`
Defaultparam string `orm:"column(defaultparam);size(200);null"`
}
func (t *Logic) TableName() string {
return "logic"
}
func init() {
orm.RegisterModel(new(Logic))
}
// AddLogic insert a new Logic into database and returns
// last inserted Id on success.
func AddLogic(m *Logic) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetLogicById retrieves Logic by Id. Returns error if
// Id doesn't exist
func GetLogicById(id int) (v *Logic, err error) {
o := orm.NewOrm()
v = &Logic{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllLogic retrieves all Logic matches certain condition. Returns empty list if
// no records exist
func GetAllLogic(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(Logic))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []Logic
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdateLogic updates Logic by Id and returns error if
// the record to be updated doesn't exist
func UpdateLogicById(m *Logic) (err error) {
o := orm.NewOrm()
v := Logic{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteLogic deletes Logic by Id and returns error if
// the record to be deleted doesn't exist
func DeleteLogic(id int) (err error) {
o := orm.NewOrm()
v := Logic{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&Logic{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"github.com/astaxie/beego/orm"
)
type Permissions struct {
Id int `orm:"column(id);auto"`
Name string `orm:"column(name);size(255)"`
Value int8 `orm:"column(value)"`
}
func (t *Permissions) TableName() string {
return "permissions"
}
func init() {
orm.RegisterModel(new(Permissions))
}
// AddPermissions insert a new Permissions into database and returns
// last inserted Id on success.
func AddPermissions(m *Permissions) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetPermissionsById retrieves Permissions by Id. Returns error if
// Id doesn't exist
func GetPermissionsById(id int) (v *Permissions, err error) {
o := orm.NewOrm()
v = &Permissions{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllPermissions retrieves all Permissions matches certain condition. Returns empty list if
// no records exist
func GetAllPermissions(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(Permissions))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []Permissions
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdatePermissions updates Permissions by Id and returns error if
// the record to be updated doesn't exist
func UpdatePermissionsById(m *Permissions) (err error) {
o := orm.NewOrm()
v := Permissions{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeletePermissions deletes Permissions by Id and returns error if
// the record to be deleted doesn't exist
func DeletePermissions(id int) (err error) {
o := orm.NewOrm()
v := Permissions{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&Permissions{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"github.com/astaxie/beego/orm"
)
type PicsLog struct {
Id int `orm:"column(id);auto" description:"主键ID"`
Url string `orm:"column(url);size(128)"`
Thumbnail string `orm:"column(thumbnail);size(128)" description:"缩略图"`
Width int `orm:"column(width)" description:"宽度"`
Length int `orm:"column(length)" description:"长度"`
}
func (t *PicsLog) TableName() string {
return "pics_log"
}
func init() {
orm.RegisterModel(new(PicsLog))
}
// AddPicsLog insert a new PicsLog into database and returns
// last inserted Id on success.
func AddPicsLog(m *PicsLog) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetPicsLogById retrieves PicsLog by Id. Returns error if
// Id doesn't exist
func GetPicsLogById(id int) (v *PicsLog, err error) {
o := orm.NewOrm()
v = &PicsLog{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllPicsLog retrieves all PicsLog matches certain condition. Returns empty list if
// no records exist
func GetAllPicsLog(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(PicsLog))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []PicsLog
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdatePicsLog updates PicsLog by Id and returns error if
// the record to be updated doesn't exist
func UpdatePicsLogById(m *PicsLog) (err error) {
o := orm.NewOrm()
v := PicsLog{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeletePicsLog deletes PicsLog by Id and returns error if
// the record to be deleted doesn't exist
func DeletePicsLog(id int) (err error) {
o := orm.NewOrm()
v := PicsLog{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&PicsLog{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/astaxie/beego/orm"
)
type Positions struct {
Id int `orm:"column(id);auto"`
CompanyId int `orm:"column(company_id)"`
Name string `orm:"column(name);size(255)"`
Pid string `orm:"column(pid);size(255)"`
Path string `orm:"column(path);size(1000)"`
Level int8 `orm:"column(level)" description:"级别"`
CreateTime time.Time `orm:"column(create_time);type(timestamp);auto_now"`
Enabled int8 `orm:"column(enabled)"`
}
func (t *Positions) TableName() string {
return "positions"
}
func init() {
orm.RegisterModel(new(Positions))
}
// AddPositions insert a new Positions into database and returns
// last inserted Id on success.
func AddPositions(m *Positions) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetPositionsById retrieves Positions by Id. Returns error if
// Id doesn't exist
func GetPositionsById(id int) (v *Positions, err error) {
o := orm.NewOrm()
v = &Positions{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllPositions retrieves all Positions matches certain condition. Returns empty list if
// no records exist
func GetAllPositions(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(Positions))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []Positions
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdatePositions updates Positions by Id and returns error if
// the record to be updated doesn't exist
func UpdatePositionsById(m *Positions) (err error) {
o := orm.NewOrm()
v := Positions{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeletePositions deletes Positions by Id and returns error if
// the record to be deleted doesn't exist
func DeletePositions(id int) (err error) {
o := orm.NewOrm()
v := Positions{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&Positions{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/astaxie/beego/orm"
)
type Question struct {
Id int `orm:"column(id);pk"`
Title string `orm:"column(title);size(30)" description:"标题"`
Content string `orm:"column(content)" description:"内容"`
Uid int64 `orm:"column(uid)" description:"用户ID"`
CreateTime time.Time `orm:"column(createTime);type(timestamp);auto_now_add"`
Way int `orm:"column(way)" description:"提问方式(0语音,1图文)"`
PageView int `orm:"column(pageView)" description:"浏览总数"`
CommentTotal int `orm:"column(commentTotal)" description:"评论总数"`
SympathyTotal int `orm:"column(sympathyTotal)" description:"同感总数"`
Review int `orm:"column(review)" description:"0 待审核 1已审核"`
Status int `orm:"column(status);null" description:"状态 0 未解决 1已解决"`
UpdateTime time.Time `orm:"column(updateTime);type(timestamp);null"`
ScoreAnalyze int `orm:"column(scoreAnalyze);null" description:"分析评分"`
ScoreAsk int `orm:"column(scoreAsk);null" description:"提问评分"`
ScoreScheme int `orm:"column(scoreScheme);null" description:"方案评分"`
Published int `orm:"column(published);null" description:"公开状态 0未公开、1本部门公开、2本公司公开"`
Level int `orm:"column(level)" description:"最后评分或审核人的级别"`
CheckUid int64 `orm:"column(checkUid);null" description:"审核人ID"`
Enabled int `orm:"column(enabled);null" description:"1有效 0删除"`
Tlevel int `orm:"column(tlevel)" description:"公开操作权限"`
PfUid int64 `orm:"column(pfUid)"`
QType int `orm:"column(qType)"`
SoluteTime time.Time `orm:"column(soluteTime);type(timestamp);auto_now_add"`
ResolverTime time.Time `orm:"column(resolverTime);type(timestamp);auto_now_add"`
Resolver int64 `orm:"column(resolver)"`
RelevantDepartmentId int `orm:"column(relevantDepartmentId)" description:"相关部门id"`
ReceiveStatus int8 `orm:"column(receiveStatus)" description:"领取状态 0未领取 1已领取"`
}
func (t *Question) TableName() string {
return "question"
}
func init() {
orm.RegisterModel(new(Question))
}
// AddQuestion insert a new Question into database and returns
// last inserted Id on success.
func AddQuestion(m *Question) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetQuestionById retrieves Question by Id. Returns error if
// Id doesn't exist
func GetQuestionById(id int) (v *Question, err error) {
o := orm.NewOrm()
v = &Question{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllQuestion retrieves all Question matches certain condition. Returns empty list if
// no records exist
func GetAllQuestion(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(Question))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []Question
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdateQuestion updates Question by Id and returns error if
// the record to be updated doesn't exist
func UpdateQuestionById(m *Question) (err error) {
o := orm.NewOrm()
v := Question{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteQuestion deletes Question by Id and returns error if
// the record to be deleted doesn't exist
func DeleteQuestion(id int) (err error) {
o := orm.NewOrm()
v := Question{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&Question{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/astaxie/beego/orm"
)
type QuestionDepartment struct {
Id int `orm:"column(id);pk"`
Qid int64 `orm:"column(qid)" description:"所属的问题ID"`
DepartmentId int `orm:"column(department_id)" description:"语音路径"`
CreateTime time.Time `orm:"column(createTime);type(timestamp);auto_now_add"`
}
func (t *QuestionDepartment) TableName() string {
return "question_department"
}
func init() {
orm.RegisterModel(new(QuestionDepartment))
}
// AddQuestionDepartment insert a new QuestionDepartment into database and returns
// last inserted Id on success.
func AddQuestionDepartment(m *QuestionDepartment) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetQuestionDepartmentById retrieves QuestionDepartment by Id. Returns error if
// Id doesn't exist
func GetQuestionDepartmentById(id int) (v *QuestionDepartment, err error) {
o := orm.NewOrm()
v = &QuestionDepartment{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllQuestionDepartment retrieves all QuestionDepartment matches certain condition. Returns empty list if
// no records exist
func GetAllQuestionDepartment(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(QuestionDepartment))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []QuestionDepartment
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdateQuestionDepartment updates QuestionDepartment by Id and returns error if
// the record to be updated doesn't exist
func UpdateQuestionDepartmentById(m *QuestionDepartment) (err error) {
o := orm.NewOrm()
v := QuestionDepartment{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteQuestionDepartment deletes QuestionDepartment by Id and returns error if
// the record to be deleted doesn't exist
func DeleteQuestionDepartment(id int) (err error) {
o := orm.NewOrm()
v := QuestionDepartment{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&QuestionDepartment{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/astaxie/beego/orm"
)
type QuestionDepartmentLog struct {
Id int `orm:"column(id);pk"`
Qid int64 `orm:"column(qid)" description:"所属的问题ID"`
DepartmentId int `orm:"column(department_id)" description:"相关部门id"`
OperatorId int64 `orm:"column(operator_id)" description:"操作者id"`
CreateTime time.Time `orm:"column(createTime);type(timestamp);auto_now_add"`
}
func (t *QuestionDepartmentLog) TableName() string {
return "question_department_log"
}
func init() {
orm.RegisterModel(new(QuestionDepartmentLog))
}
// AddQuestionDepartmentLog insert a new QuestionDepartmentLog into database and returns
// last inserted Id on success.
func AddQuestionDepartmentLog(m *QuestionDepartmentLog) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetQuestionDepartmentLogById retrieves QuestionDepartmentLog by Id. Returns error if
// Id doesn't exist
func GetQuestionDepartmentLogById(id int) (v *QuestionDepartmentLog, err error) {
o := orm.NewOrm()
v = &QuestionDepartmentLog{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllQuestionDepartmentLog retrieves all QuestionDepartmentLog matches certain condition. Returns empty list if
// no records exist
func GetAllQuestionDepartmentLog(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(QuestionDepartmentLog))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []QuestionDepartmentLog
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdateQuestionDepartmentLog updates QuestionDepartmentLog by Id and returns error if
// the record to be updated doesn't exist
func UpdateQuestionDepartmentLogById(m *QuestionDepartmentLog) (err error) {
o := orm.NewOrm()
v := QuestionDepartmentLog{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteQuestionDepartmentLog deletes QuestionDepartmentLog by Id and returns error if
// the record to be deleted doesn't exist
func DeleteQuestionDepartmentLog(id int) (err error) {
o := orm.NewOrm()
v := QuestionDepartmentLog{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&QuestionDepartmentLog{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"github.com/astaxie/beego/orm"
)
type QuestionImage struct {
Id int `orm:"column(id);pk"`
Qid int64 `orm:"column(qid);null" description:"所属的问题ID"`
Path string `orm:"column(path);size(500);null" description:"语音路径"`
W int `orm:"column(w)"`
H int `orm:"column(h)"`
}
func (t *QuestionImage) TableName() string {
return "question_image"
}
func init() {
orm.RegisterModel(new(QuestionImage))
}
// AddQuestionImage insert a new QuestionImage into database and returns
// last inserted Id on success.
func AddQuestionImage(m *QuestionImage) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetQuestionImageById retrieves QuestionImage by Id. Returns error if
// Id doesn't exist
func GetQuestionImageById(id int) (v *QuestionImage, err error) {
o := orm.NewOrm()
v = &QuestionImage{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllQuestionImage retrieves all QuestionImage matches certain condition. Returns empty list if
// no records exist
func GetAllQuestionImage(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(QuestionImage))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []QuestionImage
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdateQuestionImage updates QuestionImage by Id and returns error if
// the record to be updated doesn't exist
func UpdateQuestionImageById(m *QuestionImage) (err error) {
o := orm.NewOrm()
v := QuestionImage{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteQuestionImage deletes QuestionImage by Id and returns error if
// the record to be deleted doesn't exist
func DeleteQuestionImage(id int) (err error) {
o := orm.NewOrm()
v := QuestionImage{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&QuestionImage{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...
package models
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/astaxie/beego/orm"
)
type QuestionScore struct {
Id int `orm:"column(id);pk"`
Uid int64 `orm:"column(uid);null" description:"评分用户ID"`
Qid int64 `orm:"column(qid);null" description:"所属的问题ID"`
ScoreAnalyze int `orm:"column(scoreAnalyze);null"`
ScoreAsk int `orm:"column(scoreAsk);null"`
ScoreScheme int `orm:"column(scoreScheme);null"`
CreateTime time.Time `orm:"column(createTime);type(timestamp);null;auto_now_add" description:"评分时间"`
}
func (t *QuestionScore) TableName() string {
return "question_score"
}
func init() {
orm.RegisterModel(new(QuestionScore))
}
// AddQuestionScore insert a new QuestionScore into database and returns
// last inserted Id on success.
func AddQuestionScore(m *QuestionScore) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetQuestionScoreById retrieves QuestionScore by Id. Returns error if
// Id doesn't exist
func GetQuestionScoreById(id int) (v *QuestionScore, err error) {
o := orm.NewOrm()
v = &QuestionScore{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllQuestionScore retrieves all QuestionScore matches certain condition. Returns empty list if
// no records exist
func GetAllQuestionScore(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(QuestionScore))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []QuestionScore
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdateQuestionScore updates QuestionScore by Id and returns error if
// the record to be updated doesn't exist
func UpdateQuestionScoreById(m *QuestionScore) (err error) {
o := orm.NewOrm()
v := QuestionScore{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteQuestionScore deletes QuestionScore by Id and returns error if
// the record to be deleted doesn't exist
func DeleteQuestionScore(id int) (err error) {
o := orm.NewOrm()
v := QuestionScore{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&QuestionScore{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...