【GO】gorm - Go语言中文社区

【GO】gorm


参考资料
[1] 连接到数据库
[2] 官方文档

1. 简介

gorm是使用的orm映射,所以需要定义要操作的表的model,在go中需要定义一个structstruct的名字就是对应数据库中的表名,注意gorm查找struct名对应数据库中的表名的时候会默认把你的struct中的大写字母转换为小写并加上“s”,所以可以加上 db.SingularTable(true)gorm转义struct名字的时候不用加上“s”。

golang中,首字母大小写来表示public或者private,因此结构体中字段首字母必须大写。

定义model,即struct时,我们可以只定义我们需要从数据库中取回的特定字段:
gorm在转义表名的时候会把struct的大写字母(首字母除外) 替换成“_”,所以下面的”GoSystemInfo”会转义成数据库中对应的“go_system_info”的表名, 对应的字段名的查找会先按照tag里面的名称去里面查找,如果没有定义标签则按照struct定义的字段查找,查找的时候struct字段中的大写会被转义成“_”,如:“SystemId”会去查找表中的system_id字段。

1. join查询

https://blog.csdn.net/f95_slj...

type JobCKDao struct{}
 
func (dao *JobCKDao) MonitorQuery(ctx context.Context, gSession *gorm.DB) []*JobData {
   var db *gorm.DB
   var jobDatas []*JobData
   db = gSession.Table("job").Order("job.ysid DESC") //.Where("job.state in (?)", []int{0, 1, 3}) // 只查询状态为0, 1, 3的job
   db.Select("job.ysid as job_id,job.project_id as project_id,user.name as user_name,job.name as job_name,job.state as status,project.maxproc as maxproc,job.created_at as create_time,job.end_time as end_time").
      Joins("join user on user.ysid = job.user_id").Joins("join project on job.project_id = project.ysid").Limit(5).Scan(&jobDatas)
   return jobDatas
}

2. 关联查询

https://www.jianshu.com/p/b2d...

3.连接clickhouse遇到的坑

如果在go 中执行:

// 每时刻所有节点cpu的平均值
type AllNodeCpuAveData struct {
   User   float64 `json:"user" binding:"required"`
   Free   float64 `json:"free" binding:"required"`
   System float64 `json:"system" binding:"required"`
   Time   int64   `json:"time" binding:"required"`
}


type Cpu struct {
   Ysid        int64     `gorm:"primary_key;AUTO_INCREMENT;column:ysid;type:bigint;"`
   NodeName    string    `gorm:"column:node_name;type:varchar;size:128;"`
   NodeIp      string    `gorm:"column:node_ip;type:varchar;size:128;"`
   User        float64   `gorm:"column:user;type:decimal;"`     //从系统启动开始累计到当前时刻,用户态的CPU时间(单位:jiffies) ,不包含 nice值为负进程。1jiffies=0.01秒
   Nice        float64   `gorm:"column:nice;type:decimal;"`     //从系统启动开始累计到当前时刻,nice值为负的进程所占用的CPU时间(单位:jiffies)
   System      float64   `gorm:"column:system;type:decimal;"`   //从系统启动开始累计到当前时刻,内核态时间(单位:jiffies)
   Idle        float64   `gorm:"column:idle;type:decimal;"`     //从系统启动开始累计到当前时刻,空闲时间(单位:jiffies)
   IoWait      float64   `gorm:"column:io_wait;type:decimal;"`  //从系统启动开始累计到当前时刻,空闲时间(单位:jiffies)
   Irq         float64   `gorm:"column:irq;type:decimal;" `     //从系统启动开始累计到当前时刻,硬中断时间(单位:jiffies)
   SoftIrq     float64   `gorm:"column:soft_irq;type:decimal;"` //从系统启动开始累计到当前时刻,软中断时间(单位:jiffies)
   Steal       float64   `gorm:"column:steal;type:decimal;"`
   Guest       float64   `gorm:"column:guest;type:decimal;"`
   GuestNice   float64   `gorm:"column:guest_nice;type:decimal;"`
   TotalLast   float64   `gorm:"column:total_last;type:decimal;"`  //上次总时间 User + Nice + System + Idle + Iowait + IRQ + SoftIRQ + Steal + Guest
   UsageRate   float64   `gorm:"column:usage_rate;type:decimal;"`  //当前总使用百分比
   IowaitRate  float64   `gorm:"column:iowait_rate;type:decimal;"` // IO等待使用百分比
   UserRate    float64   `gorm:"column:user_rate;type:decimal;"`   //用户态百分比
   SystemRate  float64   `gorm:"column:system_rate;type:decimal;"` //内核态百分比
   IdleRate    float64   `gorm:"column:idle_rate;type:decimal;"`   //空闲态百分比
   NanoTime    int64     `gorm:"column:nano_time;type:bigint;"`    // 时间戳,单位:秒
   CollectTime time.Time `gorm:"column:collect_time;type:timestamp;default:CURRENT_TIMESTAMP;"`
   CreatedAt   time.Time `gorm:"column:created_at;type:timestamp;default:CURRENT_TIMESTAMP;"`
   UpdatedAt   time.Time `gorm:"column:updated_at;type:timestamp;default:CURRENT_TIMESTAMP;"`
}


db, err := gorm.Open(clickhouse.Open(dsn), &gorm.Config{})
if err!=nil{
   fmt.Print("报错了,err=",err)
   return
}
fmt.Println("连接成功!")

//var db1  *gorm.DB
var result []AllNodeCpuAveData
db.Table("cpu").Select("nano_time,avg(user) as user,avg(system)-avg(user) as free,avg(system) as system").Group("nano_time").Scan(&result) // 找出符合时间段内并以时间分组
fmt.Println("result=",result)

报错:

2021/02/04 20:00:29 ?[31;1mD:/wzz/study/clickHouseDemo/fl/fl.go:66 ?[35;1mcode: 184, message: Aggregate function avg(nano_time) is found inside another aggregate function in query: While processing avg(nano_time) AS user; code: 184,
 message: Aggregate function avg(nano_time) is found inside another aggregate function in query: While processing avg(nano_time) AS user
?[0m?[33m[1.995ms] ?[34;1m[rows:-]?[0m SELECT max(ysid) as system,avg(user) as free,avg(nano_time) as user FROM `cpu`
result= []

原因在于AllNodeCpuAveData的字段名称与cpu中的字段名称相同。
解决方法

// 将字段名称改为不同
type AllNodeCpuAveData struct {
   Userd   float64 `json:"userd" binding:"required"`
   Freed   float64 `json:"freed" binding:"required"`
   Systemd float64 `json:"systemd" binding:"required"`
   Time   int64   `json:"time" binding:"required"`
}

db.Table("cpu").Select("nano_time,avg(user) as userd,avg(system)-avg(user) as freed,avg(system) as systemd").Group("nano_time").Scan(&result) // 找出符合时间段内并以时间分组
版权声明:本文来源Segmentfault,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://segmentfault.com/a/1190000040053911
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-06-13 14:10:42
  • 阅读 ( 706 )
  • 分类:Go

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢